Spring Data with Spring Security – 带有Spring安全的Spring数据

最后修改: 2018年 3月 18日

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

1. Overview

1.概述

Spring Security provides a good support for integration with Spring Data. While the former handles security aspects of our application, the latter provides convenient access to the database containing the application’s data.

Spring Security为与Spring Data的集成提供了良好的支持。前者处理我们应用程序的安全问题,而后者则提供了对包含应用程序数据的数据库的方便访问。

In this article, we’ll discuss how Spring Security can be integrated with Spring Data to enable more user-specific queries.

在这篇文章中,我们将讨论Spring Security如何与Spring Data集成,以实现更多的用户特定查询

2. Spring Security + Spring Data Configuration

2.Spring安全+Spring数据配置

In our introduction to Spring Data JPA, we saw how to setup Spring Data in a Spring project. To enable spring security and spring data, as usual, we can adopt either the Java or XML-based configuration.

在我们的Spring Data JPA 介绍中,我们看到了如何在 Spring 项目中设置 Spring Data。为了启用Spring安全和Spring数据,像往常一样,我们可以采用基于Java或XML的配置。

2.1. Java Configuration

2.1. Java配置

Recall that from Spring Security Login Form (sections 4 & 5), we can add Spring Security to our project using the annotation based configuration:

回顾一下,从Spring Security Login Form(第4和5节),我们可以使用基于注解的配置将Spring Security添加到我们的项目中。

@EnableWebSecurity
public class WebSecurityConfig {
    // Bean definitions
}

Other configuration details would include the definition of filters, beans, and other security rules as required.

其他配置细节将包括定义过滤器、Bean和其他必要的安全规则。

To enable Spring Data in Spring Security, we simply add this bean to WebSecurityConfig:

为了在Spring Security中启用Spring Data,我们只需在WebSecurityConfig中添加这个bean:

@Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
    return new SecurityEvaluationContextExtension();
}

The above definition enables activation of automatic resolving of spring-data specific expressions annotated on classes.

上述定义可以激活对类上注释的spring-data特定表达的自动解析。

2.2. XML Configuration

2.2.XML配置

The XML-based configuration begins with the inclusion of the Spring Security namespace:

基于XML的配置以包含Spring Security命名空间开始。

<beans:beans xmlns="http://www.springframework.org/schema/security"
  xmlns:beans="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
  http://www.springframework.org/schema/security
  http://www.springframework.org/schema/security/spring-security.xsd">
...
</beans:beans>

Just like in the Java-based configuration, for the XML or namespace based configuration, we’d add SecurityEvaluationContextExtension bean to the XML configuration file:

就像基于Java的配置一样,对于基于XML或命名空间的配置,我们要在XML配置文件中添加SecurityEvaluationContextExtensionBean。

<bean class="org.springframework.security.data.repository
  .query.SecurityEvaluationContextExtension"/>

Defining the SecurityEvaluationContextExtension makes all the common expressions in Spring Security available from within Spring Data queries.

定义SecurityEvaluationContextExtension使Spring Security中的所有常用表达式在Spring Data查询中可用。

Such common expressions include principal, authentication, isAnonymous(), hasRole([role]), isAuthenticated, etc.

这种常见的表达式包括principal, authentication, isAnonymous(), hasRole([角色]), isAuthenticated, 等。

3. Example Usage

3.使用示例

Let’s consider some use cases of Spring Data and Spring Security.

让我们考虑一下Spring Data和Spring Security的一些用例。

3.1. Restrict AppUser Field Update

3.1.限制AppUser字段更新

In this example, we’ll look at restricting AppUser‘s lastLogin field update to the only currently authenticated user.

在这个例子中,我们将看看如何将AppUserlastLogin字段更新限制在当前唯一认证的用户。

By this, we mean that anytime updateLastLogin method is triggered, it only updates the lastLogin field of the currently authenticated user.

我们的意思是,无论何时updateLastLogin方法被触发,它只更新当前已认证用户的lastLogin字段。

To achieve this, we add the query below to our UserRepository interface:

为了实现这个目标,我们在UserRepository接口中添加以下查询。

@Query("UPDATE AppUser u SET u.lastLogin=:lastLogin WHERE" 
  +" u.username = ?#{ principal?.username }")
void updateLastLogin (Date lastLogin);

Without Spring Data and Spring Security integration, we’d normally have to pass the username as an argument to updateLastLogin.

如果没有Spring Data和Spring Security的集成,我们通常必须将用户名作为参数传递给updateLastLogin

In a case where the wrong user credentials are provided, the login process will fail and we do not need to bother about ensuring validation of access.

在提供错误的用户凭证的情况下,登录过程将失败,我们不需要为确保验证访问而烦恼。

3.2. Fetch Specific AppUser’ Content With Pagination

3.2.用分页法获取特定的AppUser’内容

Another scenario where Spring Data and Spring Security work perfectly hand-in-hand is a case where we need to retrieve content from our database that is owned by the currently authenticated user.

Spring Data和Spring Security完美配合的另一个场景是,我们需要从数据库中检索当前认证用户所拥有的内容。

For instance, if we have a tweeter application, we may want to display tweets created or liked by current user on their personalized feeds page.

例如,如果我们有一个tweeter应用程序,我们可能想在他们的个性化feeds页面上显示当前用户创建或喜欢的tweets。

Of course, this may involve writing queries to interact with one or more tables in our database. With Spring Data and Spring Security, this is as simple as writing:

当然,这可能涉及到编写查询,与我们数据库中的一个或多个表进行交互。有了Spring Data和Spring Security,这就像编写一样简单。

public interface TweetRepository extends PagingAndSortingRepository<Tweet, Long> {
    @Query("SELECT twt FROM Tweet twt JOIN twt.likes AS lk WHERE lk = ?#{ principal?.username }" +
      " OR twt.owner = ?#{ principal?.username }")
    Page<Tweet> getMyTweetsAndTheOnesILiked(Pageable pageable);
}

Because we want our results paginated, our TweetRepository extends PagingAndSortingRepository in the above interface definition.

因为我们希望我们的结果是分页的,所以我们的TweetRepository在上述接口定义中扩展了PagingAndSortingRepository

4. Conclusion

4.结论

Spring Data and Spring Security integration bring a lot of flexibility to managing authenticated states in Spring applications.

Spring Data和Spring Security的集成为管理Spring应用程序中的认证状态带来了很大的灵活性。

In this session, we’ve had a look at how to add Spring Security to Spring Data. More about other powerful features of Spring Data or Spring Security can be found in our collection of Spring Data and Spring Security articles.

在本次会议中,我们已经了解了如何将Spring Security添加到Spring Data中。关于Spring Data或Spring Security的其他强大功能的更多信息,可以在我们的Spring DataSpring Security文章集中找到。

As usual, code snippets can be found over on GitHub.

像往常一样,代码片段可以在GitHub上找到over