How to protect Rest API with Spring Boot OAuth2

I want to create a Spring sample OAuth2 integration boot application that has a CustomTokenEnhancer and it should show the url / oauth / token to the client without an access token, but all other URLs can only be requested if they have a valid access token .

I can configure CustomTokenEnhancer, with which I can send additional material when the request arrives for / oauth / token.


Application.java project structure - Spring Boot application class
Authorization ServerConfiguration.java - Authorization server
ResourceServer.java -
OAuth2 resource server SecurityConfiguration.java - extends WebSecurityConfigurerAdapter and defines CustomTokenEnhancer.java in user
memory . Send additional material with an access token, like cookies.

In OAuth2SecurityConfiguration.java, I configure 3 URLs, / oauth / token can be requested by anyone with a clientId and secret, and after you have the access token. The client should be able to request all other urls in my case /testand/inventory/sku/{skuID}

protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/oauth/token").permitAll().antMatchers("/inventory/**","/test").hasAnyRole("USER","ADMIN");

}

But I get 401 ban when I request / check // inventory / sku / 1100.

URL/test /inventory/sku/ 1100, /oauth/token .

OAuth2SecurityConfiguration.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.approval.TokenApprovalStore;
import org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler;
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;

@Configuration
@EnableWebSecurity
public class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter {

    public OAuth2SecurityConfiguration() {
        System.out.println("OAuth2SecurityConfiguration()");
    }

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {

        System.out.println("OAuth2SecurityConfiguration globalUserDetails() ,invoke BJSCustomAuthentication");

        auth.inMemoryAuthentication() // authenticationProvider(new
                                        // BJsCustomAuthentication());
                .withUser("bill").password("abc123").roles("ADMIN").and().withUser("bob").password("abc123")
                .roles("USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/oauth/token").permitAll().antMatchers("/inventory/**","/test").hasAnyRole("USER","ADMIN");
        //http.authorizeRequests().antMatchers(HttpMethod.OPTIONS).permitAll().anyRequest().authenticated().and()
            //  .httpBasic().and().csrf().disable();

    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

    @Bean
    @Autowired
    public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore) {
        TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
        handler.setTokenStore(tokenStore);
        handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
        handler.setClientDetailsService(clientDetailsService);
        return handler;
    }

    @Bean
    @Autowired
    public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception {
        TokenApprovalStore store = new TokenApprovalStore();
        store.setTokenStore(tokenStore);
        return store;
    }

}

AuthorizationServer.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    public AuthorizationServerConfiguration() {

        System.out.println("AuthorizationServerConfiguration()");
    }

    @Autowired
    AuthenticationManager authenticationManager;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        System.out.println("AuthorizationServerConfiguration configure()");

        //endpoints.authenticationManager(authenticationManager).tokenEnhancer(tokenEnhancer()).tokenStore(tokenStore());

        endpoints.authenticationManager(authenticationManager);
    }

    /*@Bean
    public TokenEnhancer tokenEnhancer() {
        return new CustomTokenEnhancer();
    }

    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }*/

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        System.out.println("OAUTH CLIENT CONFIGURED in AuthorizationServerConfiguration !!!");

        clients.inMemory().withClient("my-trusted-client")
        .authorizedGrantTypes("password", "authorization_code",
                "refresh_token", "implicit")
        .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
        .scopes("read", "write", "trust").resourceIds("sparklr")
        .accessTokenValiditySeconds(60).
        and()
        .withClient("my-client-with-registered-redirect")
        .authorizedGrantTypes("authorization_code").authorities("ROLE_CLIENT")
        .scopes("read", "trust").resourceIds("sparklr")
        .redirectUris("http://anywhere?key=value").
        and()
        .withClient("angular") //my-client-with-secret
        .authorizedGrantTypes("password","refresh")
        .authorities("ROLE_CLIENT").scopes("read","write").resourceIds("sparklr").accessTokenValiditySeconds(100)
        .secret("secret");
    }


}

CustomTokenEnhancer.java

import java.util.HashMap;
import java.util.Map;

import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

public class CustomTokenEnhancer implements TokenEnhancer {

    public CustomTokenEnhancer() {
        System.out.println("CustomTokenEnhancer()");
    }

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {

        System.out.println("Custom Token Enhancer Initialized");

        WCSResponse wcsResponse = (WCSResponse) authentication.getPrincipal();
        authentication.getOAuth2Request().getRequestParameters();

        final Map<String, Object> additionalInfo = new HashMap<>();

        additionalInfo.put("wcsResponse", wcsResponse);

        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);

        return accessToken;
    }

}
+4

Source: https://habr.com/ru/post/1672915/


All Articles