Introduction to Java Config for Spring Security – Spring Security的Java配置介绍

最后修改: 2016年 10月 3日

1. Overview

1.概述

This article is an introduction to Java configuration for Spring Security which enables users to easily configure Spring Security without the use of XML.

本文是Spring Security的Java配置介绍,它使用户无需使用XML即可轻松配置Spring Security。

Java configuration was added to the Spring framework in Spring 3.1 and extended to Spring Security in Spring 3.2 and is defined in a class annotated @Configuration.

Spring 3.1中,Java配置被添加到Spring框架中,并在Spring 3.2中扩展到Spring Security中,并被定义在一个注释为@Configuration的类中。

2. Maven Setup

2.Maven的设置

To use Spring Security in a Maven projects, we first need to have the spring-security-core dependency in the project pom.xml:

要在Maven项目中使用Spring Security,我们首先需要在项目pom.xml中设置spring-security-core依赖项。

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-core</artifactId>
    <version>5.3.3.RELEASE</version>
</dependency>

The latest version can always be found here.

最新的版本总是可以在这里找到。

3. Web Security With Java Configuration

3.使用Java配置的网络安全

Let’s start with a basic example of a Spring Security Java configuration:

让我们从一个Spring Security Java配置的基本例子开始。

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) 
      throws Exception {
        auth.inMemoryAuthentication().withUser("user")
          .password(passwordEncoder().encode("password")).roles("USER");
    }
}

As you may have noticed, the configuration sets up a basic in-memory authentication config. Additionally, starting Spring 5, we need a PasswordEncoder bean:

正如你可能已经注意到的,该配置设置了一个基本的内存认证配置。此外,从Spring 5开始,我们需要一个PasswordEncoder bean。

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

4. HTTP Security

4.HTTP安全

To enable HTTP Security in Spring, we need to extend the WebSecurityConfigurerAdapter to provide a default configuration in the configure(HttpSecurity http) method:

为了在Spring中启用HTTP安全,我们需要扩展WebSecurityConfigurerAdapter,在configure(HttpSecurity http)方法中提供一个默认配置。

protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
      .anyRequest().authenticated()
      .and().httpBasic();
}

The above default configuration makes sure any request to the application is authenticated with form based login or HTTP basic authentication.

上述默认配置确保了对应用程序的任何请求都是通过基于表单的登录或HTTP基本认证来验证的。

Also, it is exactly similar to the following XML configuration:

而且,它与下面的XML配置完全相似。

<http>
    <intercept-url pattern="/**" access="isAuthenticated()"/>
    <form-login />
    <http-basic />
</http>

5. Form Login

5.表格登录

Interestingly, Spring Security generates a login page automatically, based on the features that are enabled and using standard values for the URL which processes the submitted login:

有趣的是,Spring Security会根据启用的功能自动生成一个登录页面,并对处理提交的登录的URL使用标准值。

protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
      .anyRequest().authenticated()
      .and().formLogin()
      .loginPage("/login").permitAll();
}

Here the automatically generated login page is convenient to get up and running quickly.

在这里,自动生成的登录页面很方便,可以快速启动和运行。

6. Authorization With Roles

6.带角色的授权

Let’s now configure some simple authorization on each URL using roles:

现在让我们使用角色在每个URL上配置一些简单的授权。

protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
      .antMatchers("/", "/home").access("hasRole('USER')")
      .antMatchers("/admin/**").hasRole("ADMIN")
      .and()
      // some more method calls
      .formLogin();
}

Notice how we’re using both the type-safe API – hasRole – but also the expression based API, via access.

注意我们是如何既使用类型安全的API–hasRole,又使用基于表达式的API,通过access.

7. Logout

7.注销

As many other aspects of Spring Security, logout has some great defaults provided by the framework.

正如Spring Security的许多其他方面,注销有一些由框架提供的伟大的默认值。

By default, a logout request invalidates the session, clears any authentication caches, clears the SecurityContextHolder and redirects to login page.

默认情况下,注销请求会使会话无效,清除任何认证缓存,清除SecurityContextHolder并重定向到登录页面。

Here is a simple logout config:

下面是一个简单的注销配置:

protected void configure(HttpSecurity http) throws Exception {
    http.logout();
}

However, if you want to get more control over the available handlers, here’s what a more complete implementation will look like:

然而,如果你想对可用的处理程序有更多的控制,下面是一个更完整的实现的样子。

protected void configure(HttpSecurity http) throws Exception {
    http.logout().logoutUrl("/my/logout")
      .logoutSuccessUrl("/my/index")
      .logoutSuccessHandler(logoutSuccessHandler) 
      .invalidateHttpSession(true)
      .addLogoutHandler(logoutHandler)
      .deleteCookies(cookieNamesToClear)
      .and()
      // some other method calls
}

8. Authentication

8.身份验证

Let’s have a look at another way of allowing authentication with Spring Security.

让我们来看看另一种允许用Spring Security进行认证的方式。

8.1. In-Memory Authentication

8.1.内存认证

We’ll start with a simple, in-memory configuration:

我们将从一个简单的、内存中的配置开始。

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) 
  throws Exception {
    auth.inMemoryAuthentication()
      .withUser("user").password(passwordEncoder().encode("password")).roles("USER")
      .and()
      .withUser("admin").password(passwordEncoder().encode("password")).roles("USER", "ADMIN");
}

8.2. JDBC Authentication

8.2.JDBC认证

To move that to JDBC, all you have to do is to define a data source within the application – and use that directly:

要将其转移到JDBC,你所要做的就是在应用程序中定义一个数据源,并直接使用它。

@Autowired
private DataSource dataSource;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) 
  throws Exception {
    auth.jdbcAuthentication().dataSource(dataSource)
      .withDefaultSchema()
      .withUser("user").password(passwordEncoder().encode("password")).roles("USER")
      .and()
      .withUser("admin").password(passwordEncoder().encode("password")).roles("USER", "ADMIN");
}

Of course, with both the above examples, we also need to define the PasswordEncoder bean as outlined in Section 3.

当然,在上述两个例子中,我们还需要定义PasswordEncoder豆,如第3节所述。

9. Conclusion

9.结论

In this quick tutorial, we went over the basics of Java Configuration for Spring Security and focused on the code samples that illustrate the simplest configuration scenarios.

在这个快速教程中,我们介绍了Spring Security的Java配置的基础知识,并重点介绍了说明最简单配置场景的代码样本。