0

I have following security config file in my authorization server :

@EnableWebSecurity
public class DefaultSecurityConfig {

    @Autowired 
    MyUserDetailService myUserDetailService;
    
    @Bean
    SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeRequests(authorizeRequests ->
          authorizeRequests.anyRequest().authenticated()
        ).authenticationProvider(authenticationProvider())
          .formLogin(withDefaults());
        return http.build();
    }

    @Bean
    UserDetailsService users() {
        UserDetails user = User.withDefaultPasswordEncoder()
          .username("admin")
          .password("password")
          .roles("USER")
          .build();
        return new InMemoryUserDetailsManager(user);
    }
    
    @Bean
    DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setPasswordEncoder(new BCryptPasswordEncoder());
        authenticationProvider.setUserDetailsService(myUserDetailService);
        return authenticationProvider;
    }

}



@Configuration(proxyBeanMethods = false)
public class AuthorizationServerConfig {

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SecurityFilterChain authServerSecurityFilterChain(HttpSecurity http) throws Exception {
        OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
        return http.formLogin(Customizer.withDefaults()).build();
    }

    @Bean
    public RegisteredClientRepository registeredClientRepository() {
        RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
          .clientId("articles-client")
          .clientSecret("{noop}secret")
          .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
          .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
          .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
          .redirectUri("http://127.0.0.1:8080/login/oauth2/code/articles-client-oidc")
          .redirectUri("http://127.0.0.1:8080/authorized")
          .scope(OidcScopes.OPENID)
          .scope("articles.read")
          .build();

        return new InMemoryRegisteredClientRepository(registeredClient);
    }

    @Bean
    public JWKSource<SecurityContext> jwkSource() {
        RSAKey rsaKey = generateRsa();
        JWKSet jwkSet = new JWKSet(rsaKey);
        return (jwkSelector, securityContext) -> jwkSelector.select(jwkSet);
    }

    private static RSAKey generateRsa() {
        KeyPair keyPair = generateRsaKey();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        return new RSAKey.Builder(publicKey)
          .privateKey(privateKey)
          .keyID(UUID.randomUUID().toString())
          .build();
    }

    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 ProviderSettings providerSettings() {
        return ProviderSettings.builder()
          .issuer("http://auth-server:9000")
          .build();
    }
}

Form login is working fine but its doesnt show google sign. I have added the below properties in application yaml

server:
  port: 9000

logging:
  level:
    root: INFO
    org.springframework.web: INFO
    org.springframework.security: INFO
    org.springframework.security.oauth2: INFO

spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-secret: XXXXXXXXXXXXXXXXXXXXXXXX
            client-id: XXXXXXXXXXXXXXXXXXXXXXXX

I wanted to implement all common oauth provider(google, facebook,linked in) along with some custom oauth provider from this list . I need an resources server which acts as generics for these providers.

Below is resource server security config:

@EnableWebSecurity
public class ResourceServerConfig {

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.mvcMatcher("/articles/**")
          .authorizeRequests()
          .mvcMatchers("/articles/**")
          .access("hasAuthority('SCOPE_articles.read')")
          .and()
          .oauth2ResourceServer()
          .jwt();
        return http.build();
    }
}

Please suggest how can i implement this at production level.

Feroz Siddiqui
  • 3,840
  • 6
  • 34
  • 69
  • What about using keycloak as single authorization-server? It can interface with most common identity providers. – ch4mp Sep 01 '22 at 05:58
  • need to understand the code structure. what is standard way of implementing authentication , authroization and resource server , how to handle these provider token on http request level. what if someone wanted a custom authentication not supported by keycloak. – Feroz Siddiqui Sep 01 '22 at 08:48
  • `Form login is working fine but its doesnt show google sign` are you expecting that springs default login page should show a extra login button automatically, because that is not the case. You need to build your login form yourself. – Toerktumlare Sep 01 '22 at 11:12
  • Have a look here for minimal OAuth2 theory and several resource-server configuration options: https://github.com/ch4mpy/spring-addons/tree/master/samples/tutorials. Same content maybe a bit more developped: https://dzone.com/articles/spring-oauth2-resource-servers – ch4mp Sep 01 '22 at 16:38

0 Answers0