Spring Security Expressions – hasRole Example

1. Overview

Spring Security 3 provides a large variety of Expressions, using the powerful Spring Expression Language (SpEL) introduced in Spring 3. Most of these security expressions are evaluated against a contextual object – the currently authenticated principal.

The evaluation of these expressions is performed by the SecurityExpressionRoot – which provides the basis for both web security as well as method level security.

2. Web Authorization

By default, expressions are not enabled in the security configuration – the namespace support provides an easy way to enable them:

<http ... use-expressions="true">

Spring Security provides two types of web authorization – securing a full page based on the URL and conditionally showing parts of a JSP page based on security rules.

2.1. Full Page Authorization Example

With expressions enabled for the http element, a URL pattern can be secured as follows:

<intercept-url pattern="/user/**" access="hasRole('ROLE_USER')" />

The hasRole expression was used here to check if the currently authenticated principal has the specified authority.

2.2. In Page Authorization Example

The second kind of web authorization is conditionally showing some part of a JSP page based on the evaluation of a security expression.

But first, in order to start using the Spring Security JSP taglib support, the following dependency needs to be added to the pom.xml of the project:

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-taglibs</artifactId>
    <version>3.1.4.RELEASE</version>
</dependency>

Then, the taglib support has to be enabled in the page in order to use the security namespace:

<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>

Finally, the hasRole expression can now be used in the page, to show/hide HTML elements based on who is currently authenticated when the page is rendered:

<security:authorize access="hasRole('ROLE_USER')">
    This text is only visible to a user
    <br/>
</security:authorize>
<security:authorize access="hasRole('ROLE_ADMIN')">
    This text is only visible to an admin
    <br/>
</security:authorize>

3. Method Level Authorization Example – @PreAuthorize

Security Expressions can be used to secure business functionality at the method level as well, by using annotations. The older @Secured annotations did not allow expressions to be used, so in Spring Security 3, new and more flexible annotations are introduced for this purpose: @PreAuthorize and @PostAuthorize (as well as @PreFilter and @PostFilter).

First, in order to use method level security, it needs to be enabled in the security configuration:

<global-method-security pre-post-annotations="enabled" />

Then, methods can be secured using the Spring @PreAuthorize annotation:

@Service
public class FooService {
    @PreAuthorize("hasRole('ROLE_USER')")
    public List<Foo> findAll() { ... }
    ...
}

Now, only principals with the specified authority will be able to call the findAll method successfully.

Note that the Pre and Post annotations are evaluated and enforced via proxies – in case CGLIB proxies are used, the class and the public methods must not be declared as final.

4. Programmatic checking of the role

A user authority can also be checked programmatically, in raw java code, if the request is available:

import javax.servlet.http.HttpServletRequest;
...
@RequestMapping
public void someControllerMethod(HttpServletRequest request) {
    request.isUserInRole("someAuthority");
}

And of course, without access to the request, the check can also be done manually by simply verifying if the currently authenticated user has that particular authority. The user can be obtained from the Spring Security context in a variety of ways.

5. Conclusion

This tutorial is a quick introduction to using Spring Security Expressions in general, and the hasRole expression in particular – as a quick introduction of as various parts of the application can be secured.

For the web authorization example, check out this github simple tutorial; the method level security example is also on github.

I usually post about Security on Google+ - you can follow me there:

Free eBook - REST Services with Spring
Join more than 2,200 engineers!

,

  • Burak

    Is there any expression stating not hasRole in spring security ?

    • baeldung

      You can negate any expression using !: “!hasRole(‘ROLE_USER’)”.
      Hope that helps.
      Eugen.

  • Florian

    First of all: Great Tutorial! Thanks!

    In the method “someControllerMethod”, the parameter is named request. In the body of the method it is called httpRequest.

    import javax.servlet.http.HttpServletRequest;

    @RequestMapping
    public void someControllerMethod(HttpServletRequest request) {
    httpRequest.isUserInRole(“someAuthority”);
    }

    • baeldung

      Nice catch – thanks.