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.
This project initially look like this:
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.tutoraspire 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.tutoraspire.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:
Run Server
Output:
First login as ADMIN
After login,
Click on update record and see, record is updated because the user’s role is ADMIN.
User Login
Now, login as user.
Now, click on update record and see server decline the access because the user’s role is USER.