Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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.