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
Step-2 Got Login Form for Authentication
Step-3 Received code in response
Step-4 Request oauth/token with same code and state value and Successfully received Access Token with other values
Step-5 Request Controller URL /admin/api/getData with Access Token pass as Bearer RECEIVED_ACCESS_TOKEN in header, Got 401 Unauthorized error
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.