Javatpoint Logo
Javatpoint Logo

Spring Security at Method Level

Apart from authentication, spring security also check authorization of the logged in user. After login which user is authorize to access the resource is done on the bases of user's ROLE.

At the time of creating user in WebSecurityConfig class, we can specify user?s ROLE as well.

Security applied on a method restricts to unauthorized user and allow only authentic user.

Let's see an example. First create a maven project by providing details.


Spring Security at Method Level

This project initially look like this:


Spring Security at Method Level 2

Spring Security Configuration

Now, configure the application to protect from unauthorized and unauthentic users. It requires four Java files that are given below, create a package com.javatpoint and place all these files inside it.

// AppConfig.java

This class is used to set view suffix and prefix with the help of view resolver.

// MvcWebApplicationInitializer.java.java

// SecurityWebApplicationInitializer.java

// WebSecurityConfig.java

This class is used to create user and set their authentication. Each time login is required when user want to access into the application.

Controller

Create a controller HomeController and place into com.javatpoint.controller package.

// HomeController.java

View

Create following views (JSP pages) to produce output for the user. Place all the views into WEB-INF/views folder.

// index.jsp

// admin.jsp

Package Dependencies

Following are the dependencies that are required to create this project.

Project Structure

After adding all the above files, our project looks like this:


Spring Security at Method Level 3

Run Server

Output:


Spring Security at Method Level 4

First login as ADMIN


Spring Security at Method Level 5

After login,


Spring Security at Method Level 6

Click on update record and see, record is updated because the user's role is ADMIN.


Spring Security at Method Level 7

User Login

Now, login as user.


Spring Security at Method Level 8
Spring Security at Method Level 9

Now, click on update record and see server decline the access because the user's role is USER.


Spring Security at Method Level 10




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials