0

I followed the article, https://docs.microsoft.com/en-us/azure/developer/java/spring-framework/configure-spring-boot-starter-java-app-with-azure-active-directory and created an App role

with hasAuthority, I could validate a single role. However, I want to allow the user who is either an Admin or has Contributor permission. I tried with hasRole annotation as suggested in Multiple roles using @PreAuthorize.

//  @PreAuthorize("hasAuthority('APPROLE_Admin')")
    @PreAuthorize("hasRole('Admin')")
    @GetMapping("/tutorials")
    public ResponseEntity<List<Tutorial>> getAllTutorials(@RequestParam(required = false) String title) {
        try {
            List<Tutorial> tutorials = new ArrayList<Tutorial>();

But it throws the following error

enter image description here

Update: 24/05/2022

This code is working

 @PreAuthorize("hasAnyAuthority('APPROLE_Admin', 'APPROLE_Contributor')")

But the below code is throwing an error

 //@PreAuthorize("hasRole('ROLE_Admin')")
 //@PreAuthorize("hasAnyRole('Admin', 'Contributor')")
 //@PreAuthorize("hasAnyRole('ROLE_Admin', 'ROLE_Contributor')")

Logs:

[nio-8080-exec-5] o.s.web.servlet.DispatcherServlet        : GET "/api/tutorials", parameters={}
[nio-8080-exec-5] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.bezkoder.spring.mssql.controller.TutorialController#getAllTutorials(String)
[nio-8080-exec-5] o.s.web.servlet.DispatcherServlet        : Failed to complete request: org.springframework.security.access.AccessDeniedException: Access is denied
[nio-8080-exec-5] o.s.web.servlet.DispatcherServlet        : "ERROR" dispatch for GET "/error", parameters={}
[nio-8080-exec-5] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#errorHtml(HttpServletRequest, HttpServletResponse)
[nio-8080-exec-5] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, text/html;q=0.8]
[nio-8080-exec-5] o.s.web.servlet.DispatcherServlet        : Exiting from "ERROR" dispatch, status 403

1 Answers1

1

The Spring Security provides two expressions, we can use with the @PreAuthorize annotation to check user roles:

To check single role we can use the below code:

@PreAuthorize("hasRole('ROLE_ADMIN')")  
@GetMapping("/user/{id}")  
public String getUser(@PathVariable("id") String id)
 { 
 ...
}

We can also check multiple roles in a single expression like below:

@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_MANAGER')")  
@GetMapping("/users")
  public String getUsers() 
  {
   ... 
}

In this case, the request will be allowed if the user has any of the specified roles.

If the method is called without having the proper role, Spring Security throws an exception and redirects to the error page.