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()

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/api/**").hasRole(ADMIN.name())
                .anyRequest()
                .authenticated()
                .and()
                .httpBasic();
    }

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

image.png

Success - access by ADMIN

image.png

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!