0

I have receivied access token with below request.

curl -X POST -H "Content-Type: application/json" -H "Authorization: Basic dHJ1c3RlZC1jbGllbnQ6c2VjcmV0" -H "Cache-Control: no-cache" -H "Postman-Token: 99a69c90-d7f0-64ae-bc8e-f682e84c58c3" "http://localhost:9090/oauth/token?grant_type=password&username=admin&password=admin123"

Below is the response

{
  "access_token": "597147a1-bf8a-47f5-bd22-74ea1cd1df8f",
  "token_type": "bearer",
  "refresh_token": "de680b4a-e94e-460a-8853-be1aa5a264a3",
  "expires_in": 4972,
  "scope": "read write trust"
}

But when I am sending request with acess token getting 403. Error while sending get request.

{
  "timestamp": 1477034937446,
  "status": 403,
  "error": "Forbidden",
  "message": "Access Denied",
  "path": "/user/customers"
}

while sending get requests.

curl -X GET -H "Authorization: Bearer 597147a1-bf8a-47f5-bd22-74ea1cd1df8f" -H "Cache-Control: no-cache" -H "Postman-Token: 7d8dfa60-8aeb-90ad-1bbe-433b52ef8306" "http://localhost:9090/user/customers"

I have used Mongo DB, Morphia as User acess. Redis is used as token store. But authentication is not working.

Below is the spring related configuration

@Configuration
@EnableAuthorizationServer
@ComponentScan(value = "com.guddi.muneeb")
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    private static String REALM = "MUNEEB_OAUTH_REALM";

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private UserApprovalHandler userApprovalHandler;

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

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

        clients.inMemory()
                .withClient("trusted-client")
                .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
                .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT","ADMIN")
                .scopes("read", "write", "trust").resourceIds("MUNEEB_OAUTH_REALM")
                .secret("secret")
                .accessTokenValiditySeconds(6000).//Access token is only valid for 10 minutes.
                refreshTokenValiditySeconds(12000);//Refresh token is only valid for 20 minutes.
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore).userApprovalHandler(userApprovalHandler)
                .authenticationManager(authenticationManager);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.realm(REALM + "/client");
    }
}

OAuth:

@Configuration
@EnableWebSecurity
@ComponentScan(value = "com.guddi.muneeb")
public class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    ClientDetailsService clientDetailsService;

    @Autowired
    SecUserDetailsService userDetailsService;

    @Autowired
    public void configAuthBuilder(AuthenticationManagerBuilder builder) throws Exception {
        builder.userDetailsService(userDetailsService);
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .anonymous().disable()
                .authorizeRequests()
                .antMatchers("/user/**").authenticated()
                //.anyRequest().hasRole("ADMIN").and()
                //.anyRequest().permitAll()
                //.authorizeRequests()
                .antMatchers("/oauth/token").permitAll();
    }

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

    @Autowired
    public JedisConnectionFactory jedisConnectionFactory;

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

    @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;
    }

}

Resource Server Configuration

@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    private static final String RESOURCE_ID = "muneeb_resource";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(RESOURCE_ID).stateless(false);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                //anonymous().disable()
                .requestMatchers().antMatchers("/muneeb/**")
                //.requestMatchers().antMatchers("/muneeb/user/**")
                //.requestMatchers().antMatchers("/muneeb/admin/**")
                .and().authorizeRequests()
                //.antMatchers("/muneeb/admin/**").access("hasRole('ADMIN')")
                //.antMatchers("/muneeb/user/**").access("hasRole('ADMIN')")
                .antMatchers("/muneeb/**").access("hasRole('ADMIN')")
                .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
                //.anyRequest().permitAll();
    }
}

UserDetails implementations

   @Service
public class SecUserDetails implements UserDetails {

    private  User user;

    public SecUserDetails() {
        super();
    }

    public SecUserDetails(User user) {
        this.user = user;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
        for (String role : user.getRoles()) {
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(role);
            authorities.add(grantedAuthority);
        }
        //LOGGER.debug("user authorities are " + authorities.toString());
        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return user.isAccountNonExpired();
    }

    @Override
    public boolean isAccountNonLocked() {
        return user.isAccountNonLocked();
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return user.isCredentialsNonExpired();
    }

    @Override
    public boolean isEnabled() {
        return user.isEnabled();
    }

Please help me. If I am missing something.

Thanks in advance

freaksterz
  • 83
  • 3
  • 9
  • is it work if you change `.antMatchers("/user/**").authenticated()` to `.antMatchers("/user/**").permitAll()`?? let me know the result – Prasanna Kumar H A Oct 21 '16 at 11:46
  • @Sam Thanks for looking into it. I changed as you suggested.It is working with 'permitAll()' i.e it is not authenticating with 'permitAll()'. I can acess without acess_token too. – freaksterz Oct 22 '16 at 07:05
  • @Sam Just now found that it is Authentication is working with below configuration. However authorization is not working. Can you please suggest what am I missing. In resource server configuration ` @Override public void configure(HttpSecurity http) throws Exception { http .anonymous().disable() .requestMatchers().antMatchers("/user/**") .and().authorizeRequests() .antMatchers("/user/**").authenticated() }` – freaksterz Oct 22 '16 at 10:22
  • now what is not working exactly?? is role is not assigned?or not working according to roles? – Prasanna Kumar H A Oct 24 '16 at 04:44
  • @Prasana - Yes hasRole is not working. `.antMatchers("/user/**").hasRole("USER")` But .hasAuthority is working as expected. .antMatchers("/user/**").hasAuthority("USER") – freaksterz Oct 25 '16 at 12:28

0 Answers0