- Home
- >> Nerd Digest
- >> JAVA
-
Using @PreAuthorize on Spring controllers methods
over 9 years ago
Authenticate controller method using @PreAuthorize annotation : @PreAuthorize annotation is used to provide the method level security. We can secure our methods by using @PreAuthorize annotation. It is very easy to use and it is always preferred over the @Secured annotation.
@PreAuthorize is different in a way that it is more powerful than the @Secured. We can use Spring expression language(SpringEL) to validate the method before calling. Here we will show you how we can use the @PreAuthorize annotation in spring controller's method. It is always a good practice that use @PreAuthorize annotation in service methods instead of using methods of controller .
Example of @PreAuthorize annotation :
Web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
- <display-name>Test Application</display-name>
- <welcome-file-list>
- <welcome-file>/WEB-INF/jsp/login.jsp</welcome-file>
- </welcome-file-list>
- <filter>
- <filter-name>springSecurityFilterChain</filter-name>
- <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>springSecurityFilterChain</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <servlet>
- <servlet-name>employee</servlet-name>
- <servlet-class>
- org.springframework.web.servlet.DispatcherServlet
- </servlet-class>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>employee</servlet-name>
- <url-pattern>/</url-pattern>
- </servlet-mapping>
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>
- /WEB-INF/spring-servlet.xml
- /WEB-INF/spring-security.xml
- </param-value>
- </context-param>
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- </web-app>
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>Test Application</display-name> <welcome-file-list> <welcome-file>/WEB-INF/jsp/login.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>employee</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>employee</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/spring-servlet.xml /WEB-INF/spring-security.xml </param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>
spring-servlet.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
- <context:annotation-config />
- <context:component-scan base-package="com.evon.controller" />
- <bean id="jspViewResolver"
- class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="viewClass"
- value="org.springframework.web.servlet.view.JstlView" />
- <property name="prefix" value="/WEB-INF/view/" />
- <property name="suffix" value=".jsp" />
- </bean>
- </beans>
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:annotation-config /> <context:component-scan base-package="com.evon.controller" /> <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/view/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
spring-security.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <beans:beans xmlns="http://www.springframework.org/schema/security"
- xmlns:beans="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/security
- http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">
- <http auto-config="true" use-expressions="true">
- <form-login login-page="/login" default-target-url="/empList" authentication-failure-url="/accessdenied" />
- </http>
- <authentication-manager alias="authenticationManager">
- <authentication-provider>
- <user-service>
- <user name="admin" password="password123" authorities="ROLE_ADMIN" />
- <user name="user1" password="user1234" authorities="ROLE_USER" />
- </user-service>
- </authentication-provider>
- </authentication-manager>
- </beans:beans>
<?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.3.xsd"> <http auto-config="true" use-expressions="true"> <form-login login-page="/login" default-target-url="/empList" authentication-failure-url="/accessdenied" /> </http> <authentication-manager alias="authenticationManager"> <authentication-provider> <user-service> <user name="admin" password="password123" authorities="ROLE_ADMIN" /> <user name="user1" password="user1234" authorities="ROLE_USER" /> </user-service> </authentication-provider> </authentication-manager> </beans:beans>
login.jsp
- <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
- <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
- <%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
- <html>
- <body>
- <h1 id="banner">Login to Security Demo</h1>
- <form name="f" action="<c:url value='j_spring_security_check'/>"
- method="POST">
- <table>
- <tr>
- <td>Username:</td>
- <td><input type='text' name='j_username' /></td>
- </tr>
- <tr>
- <td>Password:</td>
- <td><input type='password' name='j_password'></td>
- </tr>
- <tr>
- <td colspan="2"> </td>
- </tr>
- <tr>
- <td colspan='2'><input name="submit" type="submit"> <input name="reset" type="reset"></td>
- </tr>
- </table>
- </form>
- </body>
- </html>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %> <%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %> <html> <body> <h1 id="banner">Login to Security Demo</h1> <form name="f" action="<c:url value='j_spring_security_check'/>" method="POST"> <table> <tr> <td>Username:</td> <td><input type='text' name='j_username' /></td> </tr> <tr> <td>Password:</td> <td><input type='password' name='j_password'></td> </tr> <tr> <td colspan="2"> </td> </tr> <tr> <td colspan='2'><input name="submit" type="submit"> <input name="reset" type="reset"></td> </tr> </table> </form> </body> </html>
logout.jsp
denied.jsp
- <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
- <html>
- <body>
- <h1 id="banner">Unauthorized Access !!</h1>
- <hr />
- <c:if test="${not empty error}">
- <div style="color:red">
- Your fake login attempt was bursted, dare again !!<br />
- Caused : ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
- </div>
- </c:if>
- <p class="message">Access denied!</p>
- <a href="/login">Go back to login page</a>
- </body>
- </html>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <html> <body> <h1 id="banner">Unauthorized Access !!</h1> <hr /> <c:if test="${not empty error}"> <div style="color:red"> Your fake login attempt was bursted, dare again !!<br /> Caused : ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message} </div> </c:if> <p class="message">Access denied!</p> <a href="/login">Go back to login page</a> </body> </html>
EmployeeEntity.java
- package com.evon.entity;
- public class EmployeeEntity {
- private Integer id;
- private String firstname;
- private String lastname;
- private String email;
- private String telephone;
- EmployeeEntity(firstname , lastname, email, telephone){
- this.firstname= firstname;
- this.lastname = lastname;
- this.email = email;
- this.telephone = telephone;
- }
- public String getEmail() {
- return email;
- }
- public String getTelephone() {
- return telephone;
- }
- public void setEmail(String email) {
- this.email = email;
- }
- public void setTelephone(String telephone) {
- this.telephone = telephone;
- }
- public String getFirstname() {
- return firstname;
- }
- public String getLastname() {
- return lastname;
- }
- public void setFirstname(String firstname) {
- this.firstname = firstname;
- }
- public void setLastname(String lastname) {
- this.lastname = lastname;
- }
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- }
package com.evon.entity; public class EmployeeEntity { private Integer id; private String firstname; private String lastname; private String email; private String telephone; EmployeeEntity(firstname , lastname, email, telephone){ this.firstname= firstname; this.lastname = lastname; this.email = email; this.telephone = telephone; } public String getEmail() { return email; } public String getTelephone() { return telephone; } public void setEmail(String email) { this.email = email; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getFirstname() { return firstname; } public String getLastname() { return lastname; } public void setFirstname(String firstname) { this.firstname = firstname; } public void setLastname(String lastname) { this.lastname = lastname; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } }
EmployeeController.java
- package com.evon.controller;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.ModelMap;
- import org.springframework.validation.BindingResult;
- import org.springframework.web.bind.annotation.ModelAttribute;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import com.evon.entity.EmployeeEntity;
- @Controller
- public class EmployeeController {
- <pre>@PreAuthorize("isAuthenticated()")
- @RequestMapping(value = "/", method = RequestMethod.GET)
- public String defaultPage(ModelMap map) {
- return "redirect:/empList";
- }
- @PreAuthorize("hasRole('ROLE_USER')")
- @RequestMapping(value = "/empList", method = RequestMethod.GET)
- public String listEmployees(ModelMap map) {
- map.addAttribute("employee", new EmployeeEntity());
- map.addAttribute("employeeList", getEmployeeList());
- return "employeeList";
- }
- @PreAuthorize("hasRole('ROLE_USER')")
- @RequestMapping(value = "/add", method = RequestMethod.POST)
- public String addEmployee(@ModelAttribute(value = "employee") EmployeeEntity employee,BindingResult result) {
- return "redirect:/empList";
- }
- @PreAuthorize("permitAll")
- @RequestMapping(value = "/login", method = RequestMethod.GET)
- public String login(ModelMap model) {
- return "login";
- }
- @PreAuthorize("permitAll")
- @RequestMapping(value = "/accessdenied", method = RequestMethod.GET)
- public String loginerror(ModelMap model) {
- model.addAttribute("error", "true");
- return "denied";
- }
- @PreAuthorize("permitAll")
- @RequestMapping(value = "/logout", method = RequestMethod.GET)
- public String logout(ModelMap model) {
- return "logout";
- }
- private ArrayList<EmployeeEntity> getEmployeeList(){
- EmployeeEntity emp1 = new EmployeeEntity("Rajesh","Singh","rajesh@test.com",123456789);
- empList.add(emp1);
- return empList;
- }
- }
package com.evon.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.evon.entity.EmployeeEntity; @Controller public class EmployeeController { <pre>@PreAuthorize("isAuthenticated()") @RequestMapping(value = "/", method = RequestMethod.GET) public String defaultPage(ModelMap map) { return "redirect:/empList"; } @PreAuthorize("hasRole('ROLE_USER')") @RequestMapping(value = "/empList", method = RequestMethod.GET) public String listEmployees(ModelMap map) { map.addAttribute("employee", new EmployeeEntity()); map.addAttribute("employeeList", getEmployeeList()); return "employeeList"; } @PreAuthorize("hasRole('ROLE_USER')") @RequestMapping(value = "/add", method = RequestMethod.POST) public String addEmployee(@ModelAttribute(value = "employee") EmployeeEntity employee,BindingResult result) { return "redirect:/empList"; } @PreAuthorize("permitAll") @RequestMapping(value = "/login", method = RequestMethod.GET) public String login(ModelMap model) { return "login"; } @PreAuthorize("permitAll") @RequestMapping(value = "/accessdenied", method = RequestMethod.GET) public String loginerror(ModelMap model) { model.addAttribute("error", "true"); return "denied"; } @PreAuthorize("permitAll") @RequestMapping(value = "/logout", method = RequestMethod.GET) public String logout(ModelMap model) { return "logout"; } private ArrayList<EmployeeEntity> getEmployeeList(){ EmployeeEntity emp1 = new EmployeeEntity("Rajesh","Singh","rajesh@test.com",123456789); empList.add(emp1); return empList; } }
employeeList.jsp
- <%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
- <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
- <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
- <html>
- <head>
- <title>Spring 3 hibernate integration example on www.howtodoinjava.com</title>
- </head>
- <body>
- <h2>Employee Management Screen</h2>
- <h6><a href="<c:url value='j_spring_security_logout'/>">Click here to logout</a></h6>
- <form:form method="post" action="add" commandName="employee">
- <table>
- <tr>
- <td><form:label path="firstname"><spring:message code="label.firstname"/></form:label></td>
- <td><form:input path="firstname" /></td>
- </tr>
- <tr>
- <td><form:label path="lastname"><spring:message code="label.lastname"/></form:label></td>
- <td><form:input path="lastname" /></td>
- </tr>
- <tr>
- <td><form:label path="email"><spring:message code="label.email"/></form:label></td>
- <td><form:input path="email" /></td>
- </tr>
- <tr>
- <td><form:label path="telephone"><spring:message code="label.telephone"/></form:label></td>
- <td><form:input path="telephone" /></td>
- </tr>
- <tr>
- <td colspan="2">
- <input type="submit" value="<spring:message code="label.add"/>"/>
- </td>
- </tr>
- </table>
- </form:form>
- <h3>Employees</h3>
- <c:if test="${!empty employeeList}">
- <table class="data">
- <tr>
- <th>Name</th>
- <th>Email</th>
- <th>Telephone</th>
- <th> </th>
- </tr>
- <c:forEach items="${employeeList}" var="emp">
- <tr>
- <td>${emp.lastname}, ${emp.firstname} </td>
- <td>${emp.email}</td>
- <td>${emp.telephone}</td>
- <td><a href="delete/${emp.id}">delete</a></td>
- </tr>
- </c:forEach>
- </table>
- </c:if>
- </body>
- </html>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%> <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <html> <head> <title>Spring 3 hibernate integration example on www.howtodoinjava.com</title> </head> <body> <h2>Employee Management Screen</h2> <h6><a href="<c:url value='j_spring_security_logout'/>">Click here to logout</a></h6> <form:form method="post" action="add" commandName="employee"> <table> <tr> <td><form:label path="firstname"><spring:message code="label.firstname"/></form:label></td> <td><form:input path="firstname" /></td> </tr> <tr> <td><form:label path="lastname"><spring:message code="label.lastname"/></form:label></td> <td><form:input path="lastname" /></td> </tr> <tr> <td><form:label path="email"><spring:message code="label.email"/></form:label></td> <td><form:input path="email" /></td> </tr> <tr> <td><form:label path="telephone"><spring:message code="label.telephone"/></form:label></td> <td><form:input path="telephone" /></td> </tr> <tr> <td colspan="2"> <input type="submit" value="<spring:message code="label.add"/>"/> </td> </tr> </table> </form:form> <h3>Employees</h3> <c:if test="${!empty employeeList}"> <table class="data"> <tr> <th>Name</th> <th>Email</th> <th>Telephone</th> <th> </th> </tr> <c:forEach items="${employeeList}" var="emp"> <tr> <td>${emp.lastname}, ${emp.firstname} </td> <td>${emp.email}</td> <td>${emp.telephone}</td> <td><a href="delete/${emp.id}">delete</a></td> </tr> </c:forEach> </table> </c:if> </body> </html>
In this example you can see that we are using @PreAuthorize annotation to protect the controller's method.
0 Comment(s)