Intro to Spring Security Expressions – Spring安全表达式介绍

最后修改: 2016年 7月 27日


1. Introduction


In this tutorial, we’ll focus on Spring Security Expressions and practical examples using these expressions.


Before looking at more complex implementations, such as ACL, it’s important to have a solid grasp on security expressions, as they can be quite flexible and powerful if used correctly.


2. Maven Dependencies


In order to use Spring Security, we need to include the following section in our pom.xml file:

为了使用Spring Security,我们需要在pom.xml文件中包含以下部分。


The latest version can be found here.


Please note that this dependency only covers Spring Security; we’ll need to add spring-core and spring-context for a full web application.

请注意,这个依赖关系只包括Spring Security;我们需要添加spring-corespring-context来实现一个完整的Web应用。

3. Configuration


First, let’s take a look at a Java configuration:


@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityJavaConfig {

We can, of course, do an XML configuration as well:


<?xml version="1.0" encoding="UTF-8"?>
<beans:beans ...>
    <global-method-security pre-post-annotations="enabled"/>

4. Web Security Expressions


Now let’s explore the security expressions:


  • hasRole, hasAnyRole
  • hasAuthority, hasAnyAuthority
  • permitAll, denyAll
  • isAnonymous, isRememberMe, isAuthenticated, isFullyAuthenticated
  • principal, authentication
  • hasPermission

4.1. hasRole, hasAnyRole

4.1.hasRole, hasAnyRole

These expressions are responsible for defining the access control or authorization to specific URLs and methods in our application:


public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

In the above example, we specified access to all the links starting with /auth/, restricting them to users that log in with role USER or role ADMIN. Moreover, to access links starting with /auth/admin/, we need to have an ADMIN role in the system.


We can achieve the same configuration in an XML file by writing:


    <intercept-url pattern="/auth/admin/*" access="hasRole('ADMIN')"/>
    <intercept-url pattern="/auth/*" access="hasAnyRole('ADMIN','USER')"/>

4.2. hasAuthority, hasAnyAuthority

4.2.hasAuthority, hasAnyAuthority

Roles and authorities are similar in Spring.


The main difference is that roles have special semantics. Starting with Spring Security 4, the ‘ROLE_‘ prefix is automatically added (if it’s not already there) by any role-related method.

主要的区别在于,角色有特殊的语义。从Spring Security 4开始,任何角色相关的方法都会自动添加’ROLE_‘前缀(如果它不在那里)。

So hasAuthority(‘ROLE_ADMIN’) is similar to hasRole(‘ADMIN’) because the ‘ROLE_‘ prefix gets added automatically.


The benefit to using authorities is that we don’t have to use the ROLE_ prefix at all.


Here’s a quick example defining users with specific authorities:


public InMemoryUserDetailsManager userDetailsService() {
    UserDetails admin = User.withUsername("admin")
    UserDetails user = User.withUsername("user")
    return new InMemoryUserDetailsManager(admin, user);

We can then use these authorities expressions:


public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    .antMatchers("/auth/*").hasAnyAuthority("ADMIN", "USER")

As we can see, we don’t mention roles here at all.


Additionally, starting with Spring 5, we need a PasswordEncoder bean:

此外,从Spring 5开始,我们需要一个PasswordEncoder bean。

public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();

Finally, we have the option to achieve the same functionality using XML configuration as well:


            <user name="user1" password="user1Pass" authorities="ROLE_USER"/>
            <user name="admin" password="adminPass" authorities="ROLE_ADMIN"/>
<bean name="passwordEncoder" 



    <intercept-url pattern="/auth/admin/*" access="hasAuthority('ADMIN')"/>
    <intercept-url pattern="/auth/*" access="hasAnyAuthority('ADMIN','USER')"/>

4.3. permitAll, denyAll

4.3.permitAll, denyAll

These two annotations are also quite straightforward. We may either permit or deny access to some URL in our service.


Let’s have a look at the example:



With this config, we’ll authorize all users (both anonymous and logged in) to access the page starting with ‘/’ (for example, our homepage).


We can also deny access to our entire URL space:



And again, we can do the same configuration with XML as well:


<http auto-config="true" use-expressions="true">
    <intercept-url access="permitAll" pattern="/*" /> <!-- Choose only one -->
    <intercept-url access="denyAll" pattern="/*" /> <!-- Choose only one -->

4.4. isAnonymous, isRememberMe, isAuthenticated, isFullyAuthenticated

4.4. isAnonymous, isRememberMe, isAuthenticated, isFullyAuthenticated

In this subsection, we’ll focus on expressions related to the login status of the user. Let’s start with a user that didn’t log in to our page. By specifying the following in the Java config, we’ll enable all unauthorized users to access our main page:



Here’s the same in XML config:


    <intercept-url pattern="/*" access="isAnonymous()"/>

If we want to secure the website so that everyone who uses it needs to log in, we’ll need to use the isAuthenticated() method:

如果我们想确保网站的安全,使每个使用它的人都需要登录,我们就需要使用isAuthenticated() 方法。


Or we can use the XML version:


    <intercept-url pattern="/*" access="isAuthenticated()"/>

We also have two additional expressions, isRememberMe() and isFullyAuthenticated(). Through the use of cookies, Spring enables remember-me capabilities, so there’s no need to log into the system each time. We can read more about Remember Me here.

我们还有两个额外的表达式:isRememberMe()isFullyAuthenticated()。通过使用cookies,Spring实现了记住我的功能,所以不需要每次都登录到系统中。我们可以在这里阅读更多关于Remember Me的内容

In order to give access to users that were logged in by the remember me function, we can use:



We can also use the XML version:


    <intercept-url pattern="*" access="isRememberMe()"/>

Finally, some parts of our services require the user to be authenticated again, even if the user is already logged in. For example, let’s say a user wants to change the settings or payment information; it’s good practice to ask for manual authentication in the more sensitive areas of the system.


In order to do this, we can specify isFullyAuthenticated(), which returns true if the user isn’t an anonymous or remember-me user:



Here’s the XML version:


    <intercept-url pattern="*" access="isFullyAuthenticated()"/>

4.5. principal, authentication


These expressions allow us to access the principal object representing the current authorized (or anonymous) user and the current Authentication object from the SecurityContext, respectively.


We can, for example, use principal to load a user’s email, avatar, or any other data that’s accessible from the logged-in user.


And authentication provides information about the full Authentication object, along with its granted authorities.


Both of these expressions are described in further detail in the article Retrieve User Information in Spring Security.

Retrieve User Information in Spring Security一文中对这两个表达式进行了进一步的详细描述。

4.6. hasPermission APIs


This expression is documented, and intended to be a bridge between the expression system and Spring Security’s ACL system, allowing us to specify authorization constraints on individual domain objects based on abstract permissions.

该表达式是文档化的,旨在成为表达式系统和Spring Security的ACL系统之间的桥梁,允许我们根据抽象权限对单个域对象指定授权约束。

Let’s look at an example. Imagine that we have a service that allows cooperative article writing, with a main editor who decides which articles proposed by the authors should be published.


In order to allow the use of such a service, we can create the following methods with access control methods:


@PreAuthorize("hasPermission(#articleId, 'isEditor')")
public void acceptArticle(Article article) {

Only the authorized user can call this method, and they need to have isEditor permission in the service.

只有被授权的用户可以调用这个方法,而且他们需要在服务中拥有isEditor 权限。

We also need to remember to explicitly configure a PermissionEvaluator in our application context, where customInterfaceImplementation will be the class that implements PermissionEvaluator:


<global-method-security pre-post-annotations="enabled">
    <expression-handler ref="expressionHandler"/>

<bean id="expressionHandler"
    <property name="permissionEvaluator" ref="customInterfaceImplementation"/>

Of course, we can also do this with Java configuration as well:


protected MethodSecurityExpressionHandler expressionHandler() {
    DefaultMethodSecurityExpressionHandler expressionHandler = 
      new DefaultMethodSecurityExpressionHandler();
    expressionHandler.setPermissionEvaluator(new CustomInterfaceImplementation());
    return expressionHandler;

5. Conclusion


This article is a comprehensive introduction and guide to Spring Security Expressions.

本文是对Spring Security Expressions的全面介绍和指导。

All of the examples discussed here are available on the GitHub project.