Spring boot 1.5.10 : implementing implicit grant

Refresh

April 2019

Views

330 time

1

I am trying to implement Oauth2 with spring boot with the configurations as below

Securty configuration:

@Configuration
@EnableWebSecurity(debug = true)
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider());
        auth.userDetailsService(userDetailsService);
    }

    public AuthenticationProvider authenticationProvider(){
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(userDetailsService);
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder);
        return daoAuthenticationProvider;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(11);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().anonymous().disable().authorizeRequests()
                .antMatchers("/oauth2/login","/logout").permitAll()
                .anyRequest().authenticated()
                .and().formLogin().loginPage("/oauth2/login").loginProcessingUrl("/login").permitAll();
    }
}

Authorization configuration

@Configuration
@EnableAuthorizationServer
public class AuthServerConfiguration extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Bean
    public TokenStore tokenStore(DataSource dataSource){
        return new JdbcTokenStore(dataSource);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        enhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer()));
        endpoints.authenticationManager(authenticationManager)
                .tokenStore(tokenStore)
                .tokenEnhancer(enhancerChain)
                .tokenGranter(new CompositeTokenGranter(getCustomizedTokenGranters()))
                .tokenServices(tokenServices())
                .approvalStoreDisabled();

    }

    @Bean
    @Primary
    public AuthorizationServerTokenServices tokenServices() {
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setTokenEnhancer(tokenEnhancer());
        tokenServices.setTokenStore(tokenStore);
        tokenServices.setClientDetailsService(clientDetailsService);
        return tokenServices;
    }

    @Bean
    public TokenEnhancer tokenEnhancer(){
        return (accessToken, authentication) -> {
            if(!"client_credentials".equalsIgnoreCase(authentication.getOAuth2Request().getRequestParameters().get(OAuth2Utils.GRANT_TYPE)))
            {
                ExtendedUser principal = (ExtendedUser) authentication.getPrincipal();
                Map<String, Object> additionalInfo = Maps.newHashMap();
                additionalInfo.put("user_id", principal.getUserId());
                ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
            }

            return accessToken;
        };
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.checkTokenAccess("permitAll()")
        .tokenKeyAccess("permitAll()");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(clientDetailsService);
    }

    @Bean
    public ClientDetailsService clientDetailsService(DataSource dataSource){
        return new CachedClientDetailsService(dataSource);
    }

    private List<TokenGranter> getCustomizedTokenGranters() {
        AuthorizationServerTokenServices tokenServices = tokenServices();
        ClientDetailsService clientDetails = clientDetailsService;
        OAuth2RequestFactory requestFactory = new DefaultOAuth2RequestFactory(clientDetails);

        RefreshTokenGranter refreshTokenGranter = new RefreshTokenGranter(tokenServices, clientDetails, requestFactory);
        ImplicitTokenGranter implicit = new ImplicitTokenGranter(tokenServices, clientDetails, requestFactory);
        ClientCredentialsTokenGranter clientCredentialsTokenGranter = new ClientCredentialsTokenGranter(tokenServices, clientDetails, requestFactory);
        clientCredentialsTokenGranter.setAllowRefresh(true);//custom config, see AuthorizationServerEndpointsConfigurer.getDefaultTokenGranters

        List<TokenGranter> tokenGranters = Lists.newArrayList();
        tokenGranters.add(refreshTokenGranter);
        tokenGranters.add(implicit);
        tokenGranters.add(clientCredentialsTokenGranter);
        if (authenticationManager != null) {
            tokenGranters.add(new ResourceOwnerPasswordTokenGranter(authenticationManager, tokenServices, clientDetails, requestFactory));
        }
        return tokenGranters;
    }
}

Resource server configuration :

@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {


    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/api/**").authenticated();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId("identity-service");
    }

    @Bean
    public ResourceServerTokenServices resourceServerTokenServices(TokenStore tokenStore){
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setTokenStore(tokenStore);
        return tokenServices;
    }
}

application.properties

security.oauth2.resource.filter-order = 3

the resource server is on the same authorization server (Same Application), and I am trying to implement the Implicit grant (Password grant working just fine)

when I am trying to login in to complete the implicit grant (oauth/authorize endpoint need authentication) I am getting /login 404 ?

spring boot: 1.5.10, spring security Oauth2: 2.0.14

1 answers

0

Finally, i managed to make it work

Security Configuration :

protected void configure(HttpSecurity http) throws Exception {
    http.requestMatchers().antMatchers("/**").and().csrf().disable().authorizeRequests()
            .antMatchers("/oauth2/login","/logout").permitAll()
            .antMatchers("/oauth/authorize").authenticated()
            .and().formLogin().loginPage("/oauth2/login").loginProcessingUrl("/login").permitAll();
}

Resources Server Configuration

public void configure(HttpSecurity http) throws Exception {
    http.requestMatchers().antMatchers("/api/**").and().anonymous().disable().authorizeRequests()
           .anyRequest().authenticated();
}

I had to enable the anonymous in spring security and specify mapping URI matcher for both spring security and resource server

Resource server on /api/** ,Spring security on /**

and for taking care of the ordering (on version 1.5.10)

application.properties

security.oauth2.resource.filter-order = 3