12

assume that I have an user who has following authentication:

 List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
 grantedAuthorities.add(new SimpleGrantedAuthority("READ_PRODUCT"));
 grantedAuthorities.add(new SimpleGrantedAuthority("WRITE_PRODUCT"));

 SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("usr", "pwd", grantedAuthorities));

In the security check, I should check if the user has the right authority to access the API. I did the following to achive it:

 http
    .httpBasic().disable()
    .authorizeRequests()
    .antMatchers(HttpMethod.GET, "/product/**").hasAuthority("READ_PRODUCT");

Here I use hasAuthority() to check if the user has the right authority, but I found that there is also a method called hasRole() but I dont know that is the difference between these two methods? Can anyone explain me the difference and if I want to use hasRole() here, how can I use it here? I tried to replace hasAuthority() by hasRole() but it was not successful

Bali
  • 705
  • 4
  • 13
  • 21
  • The answer to [this](https://stackoverflow.com/questions/19525380/difference-between-role-and-grantedauthority-in-spring-security) question may help you. – Eleftheria Stein-Kousathana Jul 22 '19 at 13:46
  • 7
    In your case `hasRole()` does not apply, because your authorities are not prefixed with "ROLE_". If you have an authority e.g "ROLE_USER", then `hasRole("USER")` is equivalent to `hasAuthority("ROLE_USER")`. In your case, for the authority "READ_PRODUCT", there is no equivalent role. – Eleftheria Stein-Kousathana Jul 22 '19 at 13:49
  • ah I see, thank you very much @EleftheriaStein-Kousathana – Bali Jul 22 '19 at 14:50

1 Answers1

4

hasRole() defines the Role (for Example: "Employee" or "Visitor"), while hasAuthority() defines the Rights (for Example: One Employee can only use the Main Door, but another one can also use the Backdoor

Apostolos
  • 10,033
  • 5
  • 24
  • 39
DudeWhoWantsToLearn
  • 751
  • 2
  • 10
  • 29