Spring Security Authorization

The Authorization is mainly used to control access parts of the page.

There are multiple ways to lock down authorization.

The tag has various attributes, below are a few.

  • url
  • var
  • method
  • access
  • ifAnyGranted
  • ifAllGranted
  • ifNotGranted

Step -1

Let’ suppose that we want to add a functionality to print all users of our application, which should only be visible to an admin user of our website. we will need to add the below script to around the button for printing all users

 <sec:authorize ifAnyGranted="ROLE_ADMIN" />
   <a class="btn btn-primary" href="print-users.html">
     Print Users

The final code for the updated hello.jsp is like below

<%@ taglib uri="http://www.springframework.org/security/tags" prefix="sec" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page session="false"%>
<P>Welcome <sec:authentication property="name" /> !, <br/>
The time on the server is ${serverTime}.

  <!-- Authorization specific changes begins-->

  <sec:authorize ifAnyGranted="ROLE_ADMIN" />
   <a class="btn btn-primary" href="print-users.html">
     Print Users
 <!-- Authorization specific changes ends -->

<form action="whoami" method="get">
        <input type="text" name="userName">
 <input type="submit" value="Login">

Step -2

Now if we see carefully, we do not have any ROLE_ADMIN user created yet in our application. So what we should do next is to insert an user into our authorities table, having the access as ROLE_ADMIN

Insert into authorirties(username,authority) values
("saptarshi", "ROLE_ADMIN");
Doubts? WhatsApp me !