Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between hasRole() and hasAuthority() in Spring Security [duplicate]

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

like image 646
Bali Avatar asked Nov 07 '22 15:11

Bali


1 Answers

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

like image 198
DudeWhoWantsToLearn Avatar answered Nov 29 '22 10:11

DudeWhoWantsToLearn