2

I have a jdbc-authentication with an oauth2-authorization in my Spring-Boot Application. Here is my code for the jdbc-authentication:

auth.jdbcAuthentication().dataSource(dataSource)
      .usersByUsernameQuery(
       "select username, password, 1 from users where username = ?") 
      .authoritiesByUsernameQuery(
       "select u.username, r.name from users u, roles r, role_users ru "
       + "where u.username = ? and u.id =  ru.users_id  and ru.roles_id = r.id "); 

and my authorization configuration looks like this:

http.
    anonymous().disable()
    .requestMatchers().antMatchers("/api/v1/users/**")
    .and().authorizeRequests()
    .antMatchers("/api/v1/users/**").access("hasRole('ADMIN')")
    .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());

Now when i authenticate with a user in my database, everything goes fine. I authenticate with a user who has a role "ADMIN" and so i think it should allow me to access the /api/v1/users/** resource.

But all i get is an access_denied error. what am i doing wrong? Let me know if you have to see more code snippets. I appreciate all your help.

Beytullah Güneyli
  • 518
  • 2
  • 8
  • 21

1 Answers1

1

not a big expert but I never used the method access(...)

Have you tried with hasRole ?

something like

.antMatchers("/api/v1/users/**").hasRole("ADMIN")
rick
  • 1,869
  • 13
  • 22
  • your case seems similar to this one: https://dzone.com/articles/spring-security-4-authenticate-and-authorize-users take a look at the httpsecurity config, even the order of rules matters (as described here http://stackoverflow.com/questions/30819337/multiple-antmatcher-in-spring-security) – rick Mar 27 '17 at 12:28
  • somehow the `/api/v1/users/**` endpoint doesn't work. I changed it to `/api/v1/users` and now the access is granted. But unfortunately for all users (also those who has not the "ADMIN" role). – Beytullah Güneyli Mar 27 '17 at 13:07