Authorizing only users with a specific role to view some pages

There are pages that only a few users should be allowed to access. For example, admin pages should be accessible only to admin users. This is done by matching the URLs of these pages to user roles, which were defined when the users were created; refer to the Authenticating users using the default login page and Authenticating users using a database recipes.

How to do it…

In the configure() method, use the hasRole() method:

http.authorizeRequests() 
    .antMatchers("/admin/**").hasRole("ADMIN") 
    .anyRequest().authenticated(); 

How it works…

This allows access to URLs starting with the /admin path only to users with the ADMIN role.

Get Spring Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.