I’m building a microservice architecture using spring boot. I developed an authServer using spring authorization server and I implemented authorization code flow to get the access and refresh tokens to consume the APIs of the different services (resource server).
I want to add an option for users to authenticate using their social accounts (google, for instance). The problem I’m facing is that Google issue an IdToken which can not be used in resource server and even its access token is an opaque token and I would not be able to verify it unless I made another call to the userinfo end point to validate it and also will not include my custom authorities, any way it wont be a good option.
A better option is to use Google only for authentication and in the authentication success handler I call the spring authorization server to generate an access token and refresh token for me, this way it will be the same token therefore I won’t have a problem validating it in my resource server.
However, I’m kinda lost on how to do it? and is it even a good practice to do so? or is there a better solution?
Thank you!
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;
}
```java
**TokenConfiguration**
```java
@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;
}