Building OAuth2.0 SpringBoot
    • PDF

    Building OAuth2.0 SpringBoot

    • PDF

    Article Summary

    Available in Classic and VPC

    Project configuration

    This section describes based on Spring Authorization Server among Spring's various OAuth Authorization Server implementation projects. The necessary Authorization Code Grant and Refresh Token for PRISM OAuth integration are already implemented, so you can use it right away after a little customization according to the service.

    Implementation example

    The implementation example syntax is presented.

    Basic settings

    The example syntax for basic settings is as follows:

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.core.userdetails.User;
    import org.springframework.security.core.userdetails.UserDetails;
    import org.springframework.security.provisioning.InMemoryUserDetailsManager;
    import org.springframework.security.oauth2.core.AuthorizationGrantType;
    import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
    import org.springframework.security.oauth2.server.authorization.client.InMemoryRegisteredClientRepository;
    import org.springframework.security.oauth2.server.authorization.config.ProviderSettings;
    import org.springframework.security.oauth2.server.authorization.config.Settings;
    import org.springframework.security.oauth2.server.authorization.web.OAuth2AuthorizationService;
    import org.springframework.security.oauth2.server.authorization.web.OAuth2AuthorizationServiceConfigurers;
    import org.springframework.security.oauth2.server.authorization.web.OAuth2AuthorizationServer;
    import org.springframework.security.web.SecurityFilterChain;
     
    @Configuration
    public class AuthorizationServerConfig {
     
        @Bean
        public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
            http
                .authorizeRequests(authorizeRequests ->
                    authorizeRequests
                        .antMatchers("/.well-known/jwks.json").permitAll()
                        .anyRequest().authenticated()
                )
                .formLogin(withDefaults());
            return http.build();
        }
     
        @Bean
        public InMemoryUserDetailsManager userDetailsManager() {
            UserDetails user = User.withDefaultPasswordEncoder()
                    .username("user")
                    .password("password")
                    .roles("USER")
                    .build();
            return new InMemoryUserDetailsManager(user);
        }
     
        @Bean
        public InMemoryRegisteredClientRepository registeredClientRepository() {
            return new InMemoryRegisteredClientRepository(ClientRegistration.withRegistrationId("custom")
                    .clientId("custom-client")
                    .clientSecret("custom-secret")
                    .clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
                    .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
                    .redirectUri("http://localhost:8080/login/oauth2/code/custom")
                    .scope("openid")
                    .clientName("Custom Client")
                    .build()
            );
        }
     
        @Bean
        public OAuth2AuthorizationService authorizationService() {
            return new OAuth2AuthorizationService(new OAuth2AuthorizationServiceConfigurers()
                    .authorizationProviderSettings(ProviderSettings.builder().issuer("https://idp.example.com").build())
                    .settings(Settings.builder()
                            .issuer("https://idp.example.com")
                            .clientId("custom-client")
                            .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
                            .redirectUri("http://localhost:8080/login/oauth2/code/custom")
                            .clientName("Custom Client")
                            .build())
            );
        }
     
    }
    
    1. The example code shows the Spring Authorization Server configuration, including necessary dependencies and settings. User authentication, client registration, and OIDC configuration are included.
    2. OIDC endpoints: set up authentication and OpenID Connect (OIDC) endpoints according to the OIDC configuration.
    3. UserDetails Manager: set up InMemoryUserDetailsManager to manage user details.
    4. Registered Client Repository: register and set up client applications.
    5. OAuth2 Authorization Service: set up the OAuth 2.0 authorization service.
      • The above example provides the basic configuration and codes for implementing an OAuth 2.0 authentication server using the Spring Authorization Server. You need to edit the configuration to fit the actual environment and configure user, client, and OIDC settings appropriately. After checking the Spring Authorization Server documentation, additionally configure the necessary settings.
      • The part configured as InMemory needs to be changed to the Persistent DB used by each service.

    Endpoint configuration

    The example syntax for endpoint configuration is as follows:

    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
     
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                    .antMatchers("/oauth/authorize").permitAll()
                    .antMatchers("/prism/v1/service/oauth2/token").permitAll()
                    .antMatchers("/prism/v1/service/**").authenticated()
                    .and()
                .csrf().disable();
        }
    }
    
    • Configure paths for OAuth2 login and token issuance.
      • OAuth2 login: the default value is /oauth/authorize, and you can set it to the desired path in the service.
      • Token issuance and renewal: must be set to /prism/v1/service/oauth2/token.
    • permitAll(): this rule allows all requests for the specific URL or pattern. Configure paths for OAuth2 login and token issuance.
    • authenticated(): this rule allows only authenticated users to access the specific URL or pattern. It is used for resources that need protection. Configure service API patterns excluding URLs related to login.

    Was this article helpful?

    Changing your password will log you out immediately. Use the new password to log back in.
    First name must have atleast 2 characters. Numbers and special characters are not allowed.
    Last name must have atleast 1 characters. Numbers and special characters are not allowed.
    Enter a valid email
    Enter a valid password
    Your profile has been successfully updated.