Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Using @PreAuthorize on Spring controllers methods

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 5.46k
    Comment on it

    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

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xmlns="http://java.sun.com/xml/ns/javaee"
    4. xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    5. 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">
    6.  
    7. <display-name>Test Application</display-name>
    8. <welcome-file-list>
    9. <welcome-file>/WEB-INF/jsp/login.jsp</welcome-file>
    10. </welcome-file-list>
    11. <filter>
    12. <filter-name>springSecurityFilterChain</filter-name>
    13. <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    14. </filter>
    15. <filter-mapping>
    16. <filter-name>springSecurityFilterChain</filter-name>
    17. <url-pattern>/*</url-pattern>
    18. </filter-mapping>
    19. <servlet>
    20. <servlet-name>employee</servlet-name>
    21. <servlet-class>
    22. org.springframework.web.servlet.DispatcherServlet
    23. </servlet-class>
    24. <load-on-startup>1</load-on-startup>
    25. </servlet>
    26. <servlet-mapping>
    27. <servlet-name>employee</servlet-name>
    28. <url-pattern>/</url-pattern>
    29. </servlet-mapping>
    30. <context-param>
    31. <param-name>contextConfigLocation</param-name>
    32. <param-value>
    33. /WEB-INF/spring-servlet.xml
    34. /WEB-INF/spring-security.xml
    35. </param-value>
    36. </context-param>
    37. <listener>
    38. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    39. </listener>
    40. </web-app>

    spring-servlet.xml

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xmlns:context="http://www.springframework.org/schema/context"
    5. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    6. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    7.  
    8. <context:annotation-config />
    9. <context:component-scan base-package="com.evon.controller" />
    10.  
    11. <bean id="jspViewResolver"
    12. class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    13. <property name="viewClass"
    14. value="org.springframework.web.servlet.view.JstlView" />
    15. <property name="prefix" value="/WEB-INF/view/" />
    16. <property name="suffix" value=".jsp" />
    17. </bean>
    18. </beans>

    spring-security.xml

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <beans:beans xmlns="http://www.springframework.org/schema/security"
    3. xmlns:beans="http://www.springframework.org/schema/beans"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://www.springframework.org/schema/beans
    6. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    7. http://www.springframework.org/schema/security
    8. http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">
    9.  
    10. <http auto-config="true" use-expressions="true">
    11. <form-login login-page="/login" default-target-url="/empList" authentication-failure-url="/accessdenied" />
    12. </http>
    13.  
    14. <authentication-manager alias="authenticationManager">
    15. <authentication-provider>
    16. <user-service>
    17. <user name="admin" password="password123" authorities="ROLE_ADMIN" />
    18. <user name="user1" password="user1234" authorities="ROLE_USER" />
    19. </user-service>
    20. </authentication-provider>
    21. </authentication-manager>
    22. </beans:beans>

    login.jsp

    1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    2. <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
    3. <%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
    4.  
    5. <html>
    6. <body>
    7. <h1 id="banner">Login to Security Demo</h1>
    8. <form name="f" action="<c:url value='j_spring_security_check'/>"
    9. method="POST">
    10. <table>
    11. <tr>
    12. <td>Username:</td>
    13. <td><input type='text' name='j_username' /></td>
    14. </tr>
    15. <tr>
    16. <td>Password:</td>
    17. <td><input type='password' name='j_password'></td>
    18. </tr>
    19. <tr>
    20. <td colspan="2">&nbsp;</td>
    21. </tr>
    22. <tr>
    23. <td colspan='2'><input name="submit" type="submit">&nbsp;<input name="reset" type="reset"></td>
    24. </tr>
    25. </table>
    26. </form>
    27. </body>
    28. </html>

    logout.jsp

    1. <% session.invalidate(); %>
    2. You are successfully logged out!!
    3. <a href="${pageContext.request.contextPath}/login">Login</a>

    denied.jsp

    1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    2. <html>
    3. <body>
    4. <h1 id="banner">Unauthorized Access !!</h1>
    5. <hr />
    6. <c:if test="${not empty error}">
    7. <div style="color:red">
    8. Your fake login attempt was bursted, dare again !!<br />
    9. Caused : ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
    10. </div>
    11. </c:if>
    12. <p class="message">Access denied!</p>
    13. <a href="/login">Go back to login page</a>
    14. </body>
    15. </html>

    EmployeeEntity.java

    1. package com.evon.entity;
    2. public class EmployeeEntity {
    3. private Integer id;
    4. private String firstname;
    5. private String lastname;
    6. private String email;
    7. private String telephone;
    8.  
    9. EmployeeEntity(firstname , lastname, email, telephone){
    10. this.firstname= firstname;
    11. this.lastname = lastname;
    12. this.email = email;
    13. this.telephone = telephone;
    14. }
    15. public String getEmail() {
    16. return email;
    17. }
    18. public String getTelephone() {
    19. return telephone;
    20. }
    21. public void setEmail(String email) {
    22. this.email = email;
    23. }
    24. public void setTelephone(String telephone) {
    25. this.telephone = telephone;
    26. }
    27. public String getFirstname() {
    28. return firstname;
    29. }
    30. public String getLastname() {
    31. return lastname;
    32. }
    33. public void setFirstname(String firstname) {
    34. this.firstname = firstname;
    35. }
    36. public void setLastname(String lastname) {
    37. this.lastname = lastname;
    38. }
    39. public Integer getId() {
    40. return id;
    41. }
    42. public void setId(Integer id) {
    43. this.id = id;
    44. }
    45. }

    EmployeeController.java

    1. package com.evon.controller;
    2.  
    3. import org.springframework.beans.factory.annotation.Autowired;
    4. import org.springframework.stereotype.Controller;
    5. import org.springframework.ui.ModelMap;
    6. import org.springframework.validation.BindingResult;
    7. import org.springframework.web.bind.annotation.ModelAttribute;
    8. import org.springframework.web.bind.annotation.PathVariable;
    9. import org.springframework.web.bind.annotation.RequestMapping;
    10. import org.springframework.web.bind.annotation.RequestMethod;
    11.  
    12. import com.evon.entity.EmployeeEntity;
    13.  
    14. @Controller
    15. public class EmployeeController {
    16.  
    17. <pre>@PreAuthorize("isAuthenticated()")
    18. @RequestMapping(value = "/", method = RequestMethod.GET)
    19. public String defaultPage(ModelMap map) {
    20. return "redirect:/empList";
    21. }
    22.  
    23. @PreAuthorize("hasRole('ROLE_USER')")
    24. @RequestMapping(value = "/empList", method = RequestMethod.GET)
    25. public String listEmployees(ModelMap map) {
    26.  
    27. map.addAttribute("employee", new EmployeeEntity());
    28. map.addAttribute("employeeList", getEmployeeList());
    29.  
    30. return "employeeList";
    31. }
    32. @PreAuthorize("hasRole('ROLE_USER')")
    33. @RequestMapping(value = "/add", method = RequestMethod.POST)
    34. public String addEmployee(@ModelAttribute(value = "employee") EmployeeEntity employee,BindingResult result) {
    35.  
    36. return "redirect:/empList";
    37. }
    38.  
    39. @PreAuthorize("permitAll")
    40. @RequestMapping(value = "/login", method = RequestMethod.GET)
    41. public String login(ModelMap model) {
    42. return "login";
    43. }
    44.  
    45. @PreAuthorize("permitAll")
    46. @RequestMapping(value = "/accessdenied", method = RequestMethod.GET)
    47. public String loginerror(ModelMap model) {
    48. model.addAttribute("error", "true");
    49. return "denied";
    50. }
    51.  
    52. @PreAuthorize("permitAll")
    53. @RequestMapping(value = "/logout", method = RequestMethod.GET)
    54. public String logout(ModelMap model) {
    55. return "logout";
    56. }
    57.  
    58. private ArrayList&lt;EmployeeEntity&gt; getEmployeeList(){
    59. EmployeeEntity emp1 = new EmployeeEntity("Rajesh","Singh","rajesh@test.com",123456789);
    60. empList.add(emp1);
    61. return empList;
    62. }
    63. }

    employeeList.jsp

    1. <%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
    2. <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
    3. <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    4. <html>
    5. <head>
    6. <title>Spring 3 hibernate integration example on www.howtodoinjava.com</title>
    7. </head>
    8. <body>
    9.  
    10. <h2>Employee Management Screen</h2>
    11. <h6><a href="<c:url value='j_spring_security_logout'/>">Click here to logout</a></h6>
    12. <form:form method="post" action="add" commandName="employee">
    13.  
    14. <table>
    15. <tr>
    16. <td><form:label path="firstname"><spring:message code="label.firstname"/></form:label></td>
    17. <td><form:input path="firstname" /></td>
    18. </tr>
    19. <tr>
    20. <td><form:label path="lastname"><spring:message code="label.lastname"/></form:label></td>
    21. <td><form:input path="lastname" /></td>
    22. </tr>
    23. <tr>
    24. <td><form:label path="email"><spring:message code="label.email"/></form:label></td>
    25. <td><form:input path="email" /></td>
    26. </tr>
    27. <tr>
    28. <td><form:label path="telephone"><spring:message code="label.telephone"/></form:label></td>
    29. <td><form:input path="telephone" /></td>
    30. </tr>
    31. <tr>
    32. <td colspan="2">
    33. <input type="submit" value="<spring:message code="label.add"/>"/>
    34. </td>
    35. </tr>
    36. </table>
    37. </form:form>
    38.  
    39. <h3>Employees</h3>
    40. <c:if test="${!empty employeeList}">
    41. <table class="data">
    42. <tr>
    43. <th>Name</th>
    44. <th>Email</th>
    45. <th>Telephone</th>
    46. <th>&nbsp;</th>
    47. </tr>
    48. <c:forEach items="${employeeList}" var="emp">
    49. <tr>
    50. <td>${emp.lastname}, ${emp.firstname} </td>
    51. <td>${emp.email}</td>
    52. <td>${emp.telephone}</td>
    53. <td><a href="delete/${emp.id}">delete</a></td>
    54. </tr>
    55. </c:forEach>
    56. </table>
    57. </c:if>
    58. </body>
    59. </html>

    In this example you can see that we are using @PreAuthorize annotation to protect the controller's method.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: