
com.c4_soft.springaddons.security.oauth2.SynchronizedJwt2OAuthenticationConverter Maven / Gradle / Ivy
/*
* Copyright 2020 Jérôme Wacongne
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.c4_soft.springaddons.security.oauth2;
import org.springframework.security.oauth2.jwt.Jwt;
import com.c4_soft.springaddons.security.oauth2.config.Jwt2AuthoritiesConverter;
import lombok.RequiredArgsConstructor;
/**
*
* Turn a JWT into a spring-security Authentication instance.
*
* Sample configuration for Keyclkoak, getting roles from "realm_access" claim:
*
*
* @Bean
* public SynchronizedJwt2GrantedAuthoritiesConverter authoritiesConverter() {
* return (var jwt) -> {
* final var roles =
* Optional
* .ofNullable((JSONObject) jwt.getClaims().get("realm_access"))
* .flatMap(realmAccess -> Optional.ofNullable((JSONArray) realmAccess.get("roles")))
* .orElse(new JSONArray());
* return roles.stream().map(Object::toString).map(role -> new SimpleGrantedAuthority("ROLE_" + role)).collect(Collectors.toSet());
* };
* }
*
* @Bean
* public SynchronizedJwt2OidcIdAuthenticationConverter authenticationConverter(SynchronizedJwt2GrantedAuthoritiesConverter authoritiesConverter) {
* return new SynchronizedJwt2OidcIdAuthenticationConverter(authoritiesConverter);
* }
*
*
* @author [email protected]
*/
@RequiredArgsConstructor
public class SynchronizedJwt2OAuthenticationConverter implements SynchronizedJwt2AuthenticationConverter> {
private final Jwt2AuthoritiesConverter authoritiesConverter;
private final SynchronizedJwt2OpenidClaimSetConverter tokenConverter;
@Override
public OAuthentication convert(Jwt jwt) {
return new OAuthentication<>(tokenConverter.convert(jwt), authoritiesConverter.convert(jwt), jwt.getTokenValue());
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy