Spring Security: Role-Based Authentication

Spring Security: Role-Based Authentication

Table of contents

No heading

No headings in the article.

In the previous article, we have created Roles and Permissions.

In this article, we will see how to secure APIs using user roles.

In our Employee Application, we have created an API (/api/v1/employees/{employeeId}), we want this API to access only by a user whose role as ADMIN.

For this, we will make use of antMatchers()

    protected void configure(HttpSecurity http) throws Exception {

We have used the pattern (/api/**), which means whichever endpoint starts with this pattern will be accessible only by ADMIN.

Note- we are still using Basic Auth.

Let's start the application and try using the API.

Failure - access by EMPLOYEE


Success - access by ADMIN


That's it for this short article.

You can find the code here

In the next one, we will start with Permission based authentication.

Till then Bye!