Spring Security with Thymeleaf – 百里叶的Spring安全

最后修改: 2018年 4月 9日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this quick tutorial, we’ll focus on Spring Security with Thymeleaf. We’re going to create a Spring Boot application where we’ll demonstrate the usage of security dialect.

在这个快速教程中,我们将重点介绍Thymeleaf的Spring安全。我们将创建一个Spring Boot应用程序,在那里我们将演示安全方言的使用。

Our choice for frontend technology is Thymeleaf – a modern, server-side web templating engine, with good integration with Spring MVC framework. For more details, please look at our intro article on it.

我们选择的前端技术是Thymeleaf – 一个现代的服务器端Web模板引擎,与Spring MVC框架有着良好的集成。欲了解更多详情,请查看我们关于它的介绍文章。

Lastly, the Spring Security Dialect is a Thymeleaf extras module which, naturally, helps integrate both of these together.

最后,Spring安全方言是Thymeleaf的一个额外模块,自然有助于将这两个模块整合在一起。

We’re going to be using the simple project we built in our Spring Boot tutorial article; we also have a Thymeleaf tutorial with Spring, where the standard Thymeleaf configuration can be found.

我们将使用我们在Spring Boot教程文章中构建的简单项目;我们还有一个Thymeleaf教程与Spring,在那里可以找到标准Thymeleaf配置。

2. Dependencies

2.依赖性

First of all, let’s add the new dependency to our Maven pom.xml:

首先,让我们在Maven的pom.xml中添加新的依赖。

<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>

It’s recommended always to use the latest version – which we can get over on Maven Central.

建议始终使用最新版本–我们可以在Maven Central上获得。

3. Spring Security Configuration

3.Spring安全配置

Next, let’s define the configuration for Spring Security.

接下来,我们来定义Spring Security的配置。

We also need at least two different users to demonstrate the security dialect usage:

我们还需要至少两个不同的用户来证明安全方言的使用。

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

    // [...] 
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) 
      throws Exception {
        auth
          .inMemoryAuthentication()
          .withUser("user").password(passwordEncoder().encode("password")).roles("USER")
          .and()
          .withUser("admin").password(passwordEncoder().encode("admin")).roles("ADMIN");
    }
    
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

As we can see, in configureGlobal(AuthenticationManagerBuilder auth) we define two users with username and password. We can use these to access our application.

我们可以看到,在configureGlobal(AuthenticationManagerBuilder auth)中,我们定义了两个带有用户名和密码的用户。我们可以使用这些来访问我们的应用程序。

Our users have different roles: ADMIN and USER respectively so that we can present them specific content based on a role.

我们的用户有不同的角色。ADMINUSER分别,这样我们就可以根据一个角色向他们展示特定的内容。

4. Security Dialect

4.安全方言

The Spring Security dialect allows us to conditionally display content based on user roles, permissions or other security expressions. It also gives us access to the Spring Authentication object.

Spring安全方言允许我们根据用户角色、权限或其他安全表达式有条件地显示内容。它还允许我们访问Spring Authentication对象。

Let’s look at the index page, which contains examples of security dialect:

让我们看一下索引页,它包含了安全方言的例子。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>Welcome to Spring Security Thymeleaf tutorial</title>
    </head>
    <body>
        <h2>Welcome</h2>
        <p>Spring Security Thymeleaf tutorial</p>
        <div sec:authorize="hasRole('USER')">Text visible to user.</div>
        <div sec:authorize="hasRole('ADMIN')">Text visible to admin.</div>
        <div sec:authorize="isAuthenticated()">
            Text visible only to authenticated users.
        </div>
        Authenticated username:
        <div sec:authentication="name"></div>
        Authenticated user roles:
        <div sec:authentication="principal.authorities"></div>
    </body>
</html>

We can see the attributes specific to the Spring Security Dialect: sec:authorize and sec:authentication.

我们可以看到针对Spring安全方言的属性。sec:authorizesec:authentication

Let’s discuss these, one by one.

让我们逐一讨论这些问题。

4.1. Understanding sec:authorize

4.1.了解sec:authorize

Simply put, we use sec:authorize attribute to control displayed content.

简单地说,我们使用sec:authorize属性来控制显示的内容。

For example, if we want to only show content to a user with the role USER – we can do: <div sec:authorize=”hasRole(‘USER’)”>.

例如,如果我们想只向角色为USER的用户显示内容–我们可以这样做。<div sec:authorize=”hasRole(‘USER’)”>.

And, if we want to broaden the access to all authenticated users we can use the following expression:

而且,如果我们想扩大对所有认证用户的访问,我们可以使用以下表达式。

<div sec:authorize=”isAuthenticated()”>.

<div sec:authorize=”isAuthenticated()” >.

4.2. Understanding sec:authentication

4.2.了解sec:authentication

The Spring Security Authentication interface exposes useful methods concerning the authenticated principal or authentication request.

Spring Security 认证接口公开了有关认证委托人或认证请求的有用方法。

To access an authentication object withing Thymeleaf, we can simply use <div sec:authentication=”name”> or <div sec:authentication=”principal.authorities”>.

为了访问Thymeleaf中的认证对象,我们可以简单地使用<div sec:authentication=”name”>或者<div sec:authentication=”principal.authorities”>。

The former gives us access to the name of the authenticated user, the later allows us to access roles of the authenticated user.

前者使我们能够访问认证用户的名字,后者使我们能够访问认证用户的角色。

5. Summary

5.总结

In this article, we used the Spring Security support in Thymeleaf, in a simple Spring Boot application.

在这篇文章中,我们在一个简单的Spring Boot应用中使用了Thymeleaf的Spring Security支持。

As always, a working version of the code shown in this article is available in our GitHub repository.

一如既往,本文所示的工作版本的代码可在我们的GitHub仓库中找到。