I’m building a microservice architecture using spring boot. I want to centralize all authentication and authorizations in one module “Auth-server”.
in my auth server I implemented the authorization code flow using spring authorization server.It’s working fine and the user can obtain the access and refresh tokens which I use as a bearer tokens in the header of API requests to my resource servers where I verify the tokens and also the user role to my end points with @Preauthorize(hasRole…)
Till now everything works just fine.
The problem started when I wanted to allow the users to authenticate with there google accounts.
I addedd google as a provider then I follwed the documentation so when the user want to authenticate with google I cupture him in my success handler to save it in data base if it’s a first login. the redirect url of google contain the authorization code and in the authentication object I can see the Idtoken which is a jwt token but it doeesn’t have my custom roles. After reading documentation I concluded that IdTokens should not be used for authentication. So I tried to hit the google token endpoint to get an access token using insomnia and the code I obtained from the redirect url and it did work but the google access toiken is not a JWT token it’s an Opaque token and I have no idea how to verify it in my ressource server.
Long story short, how to make my ressoiurce server validate tokens regardless if they are from spring authorization servers or google (and I will add facebook in the future)?
I tried to use OAuth2TokenCustomizer to custom the google token and signed it using spring auth server to be the same when sending it to the ressource server but I kinda lost there!!.
Thank you in advance.
Below is the code I’m using
AuthorizationServerConfiguration
@Configuration(proxyBeanMethods = false)
public class AuthorizationServerConfiguration {
private final CustomUserDetailsService customUserDetailsService;
@Autowired
public AuthorizationServerConfiguration(CustomUserDetailsService customUserDetailsService) {
this.customUserDetailsService = customUserDetailsService;
}
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public SecurityFilterChain authorizationSecurityFilterChain(HttpSecurity http) throws Exception {
OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
http.getConfigurer(OAuth2AuthorizationServerConfigurer.class)
.oidc(Customizer.withDefaults());
http
.exceptionHandling(
exceptions ->
exceptions.authenticationEntryPoint(
new LoginUrlAuthenticationEntryPoint("/login")
)
);
return http.build();
}
@Bean
public RegisteredClientRepository registeredClientRepository() {
RegisteredClient demoClient = RegisteredClient.withId(UUID.randomUUID().toString())
.clientName("Demo client")
.clientId("demo-client")
.clientSecret(passwordEncoder().encode("secret"))
.redirectUri("http://localhost:8080/auth")
// .clientAuthenticationMethod(ClientAuthenticationMethod.NONE)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
//
// .scope(OidcScopes.OPENID)
// .scope(OidcScopes.PROFILE)
// .clientSettings(ClientSettings.builder()
// .requireAuthorizationConsent(false)
// .requireProofKey(true)
// .build()
// )
.build();
return new InMemoryRegisteredClientRepository(demoClient);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
var provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(customUserDetailsService);
provider.setPasswordEncoder(passwordEncoder());
return new ProviderManager(provider);
}
@Bean
public OAuth2TokenCustomizer<JwtEncodingContext> idTokenCustomizer() {
return new FederatedIdentityIdTokenCustomizer();
}
@Bean
public UserDetailsService userDetailsService() {
return this.customUserDetailsService;
}
}
SecurityConfiguration
@EnableWebSecurity
@Configuration(proxyBeanMethods = false)
public class SecurityConfiguration {
@Bean
public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http,
AuthenticationSuccessHandler authenticationSuccessHandler
) throws Exception {
http.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(
authorize -> authorize
.requestMatchers("api/users/**").permitAll()
.anyRequest().authenticated()
)
.formLogin(withDefaults())
.oauth2Login(oauth ->
oauth
.successHandler(authenticationSuccessHandler)
)
.logout(LogoutConfigurer::permitAll);
return http.build();
}
@Bean
public AuthenticationSuccessHandler authenticationSuccessHandler(UserServiceOAuth2UserHandler handler) {
SocialLoginAuthenticationSuccessHandler authenticationSuccessHandler =
new SocialLoginAuthenticationSuccessHandler();
authenticationSuccessHandler.setOidcUserHandler(handler);
return authenticationSuccessHandler;
}
TokenConfiguration
@Configuration(proxyBeanMethods = false)
public class TokenConfiguration {
@Bean
public JWKSource<SecurityContext> jwkSource() {
KeyPair keyPair = generateRsaKey();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
RSAKey rsaKey = new RSAKey.Builder(publicKey)
.privateKey(privateKey)
.keyID(UUID.randomUUID().toString())
.build();
JWKSet jwkSet = new JWKSet(rsaKey);
return new ImmutableJWKSet<>(jwkSet);
}
private static KeyPair generateRsaKey() {
KeyPair keyPair;
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
keyPair = keyPairGenerator.generateKeyPair();
}
catch (Exception ex) {
throw new IllegalStateException(ex);
}
return keyPair;
}
@Bean
public OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator(
JWKSource<SecurityContext> jwkSource,
OAuth2TokenCustomizer<JwtEncodingContext> jwtTokenCustomizer
) {
NimbusJwtEncoder jwtEncoder = new NimbusJwtEncoder(jwkSource);
JwtGenerator jwtGenerator = new JwtGenerator(jwtEncoder);
jwtGenerator.setJwtCustomizer(jwtTokenCustomizer);
OAuth2AccessTokenGenerator accessTokenGenerator = new OAuth2AccessTokenGenerator();
OAuth2RefreshTokenGenerator refreshTokenGenerator = new OAuth2RefreshTokenGenerator();
return new DelegatingOAuth2TokenGenerator(
jwtGenerator, accessTokenGenerator, refreshTokenGenerator
);
}
@Bean
public OAuth2TokenCustomizer<JwtEncodingContext> jwtTokenCustomizer() {
return context -> {
UserDetails principal = (UserDetails) context.getPrincipal().getPrincipal();
context.getClaims()
.claim(
"authorities",
principal.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.toSet())
);
};
}
}
SocialLoginAuthenticationSuccessHandler
public class SocialLoginAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
private final AuthenticationSuccessHandler delegate = new SavedRequestAwareAuthenticationSuccessHandler();
private Consumer<OAuth2User> oauth2UserHandler = (user) -> {};
@Setter
private Consumer<OidcUser> oidcUserHandler = (user) -> this.oauth2UserHandler.accept(user);
@Override
public void onAuthenticationSuccess(
HttpServletRequest request, HttpServletResponse response, Authentication authentication
) throws IOException, ServletException {
// String authorizationCode = request.getParameter("code");
if (authentication instanceof OAuth2AuthenticationToken) {
if (authentication.getPrincipal() instanceof OidcUser) {
this.oidcUserHandler.accept((OidcUser) authentication.getPrincipal());
} else if (authentication.getPrincipal() != null) {
this.oauth2UserHandler.accept((OAuth2User) authentication.getPrincipal());
}
}
this.delegate.onAuthenticationSuccess(request, response, authentication);
}
public void setOAuth2UserHandler(Consumer<OAuth2User> oauth2UserHandler) {
this.oauth2UserHandler = oauth2UserHandler;
}
}
application.properties
spring.security.oauth2.client.registration.google.provider=google
spring.security.oauth2.client.registration.google.client-id=***************
spring.security.oauth2.client.registration.google.client-secret=**************
spring.security.oauth2.client.provider.google.authorization-uri=https://accounts.google.com/o/oauth2/auth
spring.security.oauth2.client.provider.google.token-uri=https://oauth2.googleapis.com/token
spring.security.oauth2.client.provider.google.user-info-uri=https://www.googleapis.com/oauth2/v3/userinfo
spring.security.oauth2.client.provider.google.redirect-uri=http://localhost:8080
RessourceServer CONFIG
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((auth) -> auth
.requestMatchers("/demo/public/**").permitAll()
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));
return http.build();
}
@Bean
public JwtDecoder jwtDecoder(){
return NimbusJwtDecoder.withJwkSetUri(
"http://localhost:8080/oauth2/jwks"
).build();
}
@Bean
public JwtAuthenticationConverter jwtAuthenticationConverter(){
JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
jwtGrantedAuthoritiesConverter.setAuthorityPrefix("");
jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName("authorities");
JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwtGrantedAuthoritiesConverter);
return jwtAuthenticationConverter;
}