1

I am using spring boot Oauth2 security with grant_type = authorization_code flow.

I have successfully received response of code with oauth/authorize request and then passing this code in oauth/token request and also successfully received access_token in response.

Now, I want to call API with request mapping /admin/, it gives me error 401 Unauthorized. I have already provided access to this (/admin/) URL to any ROLE_ADMIN. But it ignores or not working.

I have given all my configuration here at last after screens.

When I request /admin/getData from postman, it will throw 401 Unauthorized error.

Here, I post all the screen shots step-by-step which I follows from postman, Please note as It is localhost, after getting code value with oauth/authorize, I have manually request for oauth/token from postman.

Step-1 Get New Access Token With Details

enter image description here

Step-2 Got Login Form for Authentication

enter image description here

Step-3 Received code in response

enter image description here

Step-4 Request oauth/token with same code and state value and Successfully received Access Token with other values

enter image description here

Step-5 Request Controller URL /admin/api/getData with Access Token pass as Bearer RECEIVED_ACCESS_TOKEN in header, Got 401 Unauthorized error

enter image description here

I am using ClientDetailService form database authentication. My complete code is as below.

Config for WebSecurityConfigurerAdapter

@Configuration
@EnableWebSecurity
@Order(1)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationService authenticationService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Bean(name = "myAuthenticationManager")
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {

        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(authenticationService).passwordEncoder(passwordEncoder);
    }

}

Config for ResourceServerConfigurerAdapter

@Configuration
@EnableResourceServer
public class ResourceServer extends ResourceServerConfigurerAdapter {

    @Autowired
    private TokenStore tokenStore;

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

        http.cors().and().csrf().disable();

        // Open access to all
        http.authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/oauth/authorize", "/login", "/oauth/token", "/oauth/logout")
                .permitAll();

        http.formLogin().permitAll().and().logout().permitAll();

        // Access to Admin
        http.authorizeRequests().antMatchers("/admin/**").hasAuthority("ADMIN");

        // All other request are authenticated
        http.authorizeRequests().anyRequest().authenticated();

    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {

        resources.resourceId("resource_id").tokenStore(tokenStore).stateless(false);
    }

}

Config for AuthorizationServerConfigurerAdapter

@Configuration
@EnableAuthorizationServer
public class OAuth2Server extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    public AuthenticationManager authenticationManager;

    @Autowired
    private AuthenticationService authenticationService;

    @Autowired
    private DynamicClientDetailService dynamicClientDetailService;

    @Autowired
    private TokenEnhancer tokenEnhancer;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

        endpoints.authenticationManager(authenticationManager).tokenStore(tokenStore).tokenEnhancer(tokenEnhancer)
                .userDetailsService(authenticationService).setClientDetailsService(dynamicClientDetailService);

    }

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

        clients.withClientDetails(dynamicClientDetailService);
    }

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

}

Config for ClientDetailsService

@Configuration
public class DynamicClientDetailService implements ClientDetailsService {

    @Autowired
    private DynamicClientDetailsRepository dynamicClientDetailsRepository;

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {

        DynamicClientDetails client = dynamicClientDetailsRepository.findByClientId(clientId);

        BaseClientDetails base = new BaseClientDetails(client.getClientId(), client.getResourceIds(), client.getScope(),
                client.getAuthorizedGrantTypes(), client.getAuthorities());

        base.setClientSecret(client.getClientSecret());
        base.setAccessTokenValiditySeconds(client.getAccessTokenValiditySeconds());
        base.setRefreshTokenValiditySeconds(client.getRefreshTokenValiditySeconds());
        base.setAutoApproveScopes(getScopes(client.getScope()));
        base.setRegisteredRedirectUri(getRegisteredRedirectURL(client));

        return base;

    }

    /**
     * Get registered redirect URL
     * 
     * @param client
     * @return
     */
    private Set<String> getRegisteredRedirectURL(DynamicClientDetails client) {

        return StringUtils.isEmpty(client.getRegisteredRedirectUri()) ? null
                : Arrays.stream(client.getRegisteredRedirectUri().split(",")).collect(Collectors.toSet());
    }

    /**
     * Get collection from string
     * 
     * @param scope
     * @return
     */
    private Collection<String> getScopes(String scope) {

        Collection<String> scopes = new ArrayList<String>();

        if (StringUtils.isEmpty(scope))
            return scopes;

        String[] scopesArr = scope.split(",");

        if (scopesArr.length == 0)
            return scopes;

        scopes = Arrays.asList(scopesArr);

        return scopes;
    }

}

Config for UserDetailsService

@Configuration
public class AuthenticationService implements UserDetailsService {

    @Autowired
    private LoginCredentialService loginCredentialService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        LoginCredential loginCredential = loginCredentialService.getLoginCredentialByEmail(username);
    
        return new org.springframework.security.core.userdetails.User(loginCredential.getEmail(),
                loginCredential.getPassword(), loginCredential.getIsActive(), !loginCredential.getIsDelete(),
                loginCredential.isVerified(), true, getSimpleGrantedAuthorities(loginCredential.getRole().toString()));

    }

    private Collection<GrantedAuthority> getSimpleGrantedAuthorities(String role) {

        Collection<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();

        grantedAuthorities.add(new SimpleGrantedAuthority(role));

        return grantedAuthorities;

    }

}

Controller Code

@RestController
@RequestMapping("/admin/api")
public class DataController {

    @GetMapping("/getData")
    public ResponseEntity<String> getData() throws Exception {

        return ResponseEntity.ok("Success");
    }

}

Create Query for Client Details

CREATE TABLE public.dynamic_client_details
(
  id bigint NOT NULL DEFAULT nextval('dynamic_client_details_id_seq'::regclass),
  access_token_validity_seconds integer,
  authorities character varying(255),
  authorized_grant_types character varying(255),
  auto_approve boolean NOT NULL,
  client_id character varying(255),
  client_secret character varying(255),
  refresh_token_validity_seconds integer,
  registered_redirect_uri character varying(255),
  resource_ids character varying(255),
  scope character varying(255),
  scoped boolean NOT NULL,
  secret_required boolean NOT NULL,
  CONSTRAINT dynamic_client_details_pkey PRIMARY KEY (id),
);

Inset Query for Client Details With Value

INSERT INTO public.dynamic_client_details(id, access_token_validity_seconds, authorities, authorized_grant_types, auto_approve, client_id, 
            client_secret, refresh_token_validity_seconds, registered_redirect_uri, resource_ids, scope, scoped, secret_required)
    VALUES (1, 50000, 'ROLE_ADMIN', 'password,authorization_code,refresh_token', true, 'MY_CLIENT_ID', 
            'MY_ENCODED_SECRET', 50000, 'https://oauth.pstmn.io/v1/callback', 'resource_id', 'read,write,trust', true, true);

User Details With Role IN DB Login Table

email = abc@gmail.com
password = MY_PASSWORD
role = ROLE_ADMIN

Please guide me what should I change to call API with authorized user.

Thanks in advance.

Chirag Shah
  • 353
  • 1
  • 13
  • How are you passing the token to your endpoint? – James Sep 02 '20 at 21:49
  • @James I am passing my access_token like, Bearer ACCESS_TOKEN_RETURN – Chirag Shah Sep 03 '20 at 07:12
  • And you are passing it to the Authorisation header? – James Sep 03 '20 at 07:36
  • is it because the authority in the DB is ROLE_ADMIN, but you are requiring ADMIN authority on the endpoint http configuration? – James Sep 03 '20 at 08:04
  • @James : I have insert ROLE_ADMIN in DB, but spring will automatically append ROLE_ itself before role value. So, I have mention ADMIN only at http config, Also I have cross check both the scenario but no lead. Thank you for feedback and Yes, I am passing Access Token in header. I update my question with all required screen shots of Postman – Chirag Shah Sep 03 '20 at 08:12
  • not sure if it's much of a problem, but you have mixed some of your spring annotations up. I would only use `@Configuration` for classes that contain `@Bean` factory methods. Most of your classes I would use `@Component` instead and split any ban methods into another class – James Sep 03 '20 at 08:33
  • I have replaced @Configuration with Component except WebSecurityConfigurerAdapter class. But response is the same – Chirag Shah Sep 03 '20 at 09:13
  • I think it comes down to the configuration files. You have 2 currently (these should be annotated with `@Configuration`). But I think you need more. Take a look at this answer in stack overflow https://stackoverflow.com/a/51517627/7421645 that references this spring doc multiple http security https://docs.spring.io/spring-security/site/docs/current/reference/html5/#multiple-httpsecurity – James Sep 03 '20 at 09:54
  • You should consider adding `ROLE_` as preffix when using `hasAuthority` because hasAuthority parses roles and it doesn't add `ROLE_` as preffix. Or if you don't wanna add `ROLE_` then you can use `hasRole` that would work without adding `ROLE_` as preffix in your role names – Amit Mishra Dec 04 '20 at 09:05

0 Answers0