Hello Spring Security Java Config

Using Spring Security without using any XML

本文只做简单的翻译,想看原文请移步官网,有问题请留言。

 

1、配置环境

  • 下载 Spring Tool Suite (STS)
  • 下载并解压Spring Security Distribution,假设解压后的目录为 SPRING_SECURITY_HOME.

2、导入空项目

  • 导入项目(i.e. SPRING_SECURITY_HOME/samples/insecure)
  • 右键点击项目,Run As→Run on Server
  • 在浏览器里访问http://localhost:8080/sample/

3、Securing the application

  • add maven dependency
    pom.xml

  
  
    org.springframework.security
    spring-security-web
    4.0.1.RELEASE
  
  
    org.springframework.security
    spring-security-config
    4.0.1.RELEASE
  

  •  Maven→Update project…​
  • 创建包org.springframework.security.samples.config,包下创建类SecurityConfig.java,like this

    src/main/java/org/springframework/security/samples/config/SecurityConfig.java 

package org.springframework.security.samples.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.*;

@EnableWebSecurity
public class SecurityConfig {

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

 

官网写道
The name of the configureGlobal method is not important. However, it is important to only configure AuthenticationManagerBuilder in a class annotated with either @EnableWebSecurity, @EnableGlobalMethodSecurity, or @EnableGlobalAuthentication. Doing otherwise has unpredictable results.
大致的意思是:configureGlobal方法名不重要,重要的是需要在有@EnableWebSecurity、 @EnableGlobalMethodSecurity、@EnableGlobalAuthentication等注解的类下配置 AuthenticationManagerBuilder,否则导致不可预知的结果。

 

SecurityConfig 的作用:

  • Require authentication to every URL in your application(访问应用中的每一个url都需要认证)

  • Generate a login form for you(生成一个登陆的表单)

  • Allow the user with the Username user and the Password password to authenticate with form based authentication(使用 用户名user 密码password 的认证信息进行认证)

  • Allow the user to logout

  • CSRF attack prevention(防范CSRF攻击)

  • Session Fixation protection(session固化保护)

  • Security Header integration(集成Security Header)

    • HTTP Strict Transport Security for secure requests

    • X-Content-Type-Options integration

    • Cache Control (can be overridden later by your application to allow caching of your static resources)

    • X-XSS-Protection integration

    • X-Frame-Options integration to help prevent Clickjacking

  • Integrate with the following Servlet API methods(整合了以下这些方法的功能)

    • HttpServletRequest#getRemoteUser()

    • HttpServletRequest.html#getUserPrincipal()

    • HttpServletRequest.html#isUserInRole(java.lang.String)

    • HttpServletRequest.html#login(java.lang.String, java.lang.String)

    • HttpServletRequest.html#logout()

 4、注册springSecurityFilterChain

  • org.springframework.security.samples.config里再创建一个类SecurityWebApplicationInitializer.java

    src/main/java/org/springframework/security/samples/config/SecurityWebApplicationInitializer.java

package org.springframework.security.samples.config;

import org.springframework.security.web.context.*;

public class SecurityWebApplicationInitializer
      extends AbstractSecurityWebApplicationInitializer {

    public SecurityWebApplicationInitializer() {
        super(SecurityConfig.class);
    }
}

 

 SecurityWebApplicationInitializer主要做下面几个事情:

  • Automatically register the springSecurityFilterChain Filter for every URL in your application(自动为每个url注册一个springSecurityFilterChain Filte)

  • Add a ContextLoaderListener that loads the SecurityConfig.(增加一个context监听器去加载SecurityConfig)

 5、部署项目,并尝试登陆

  • 启动server后,会看到一个登录页面,使用user和password进行登录。
  • 在页面上增加登陆后的用户名信息

    src/main/webapp/index.jsp


  

This is secured!

Hello

 

 6、退出登陆

    src/main/webapp/index.jsp


  

This is secured!

Hello

 

In order to help protect against CSRF attacks, by default, Spring Security Java Configuration log out requires:

  • the HTTP method must be a POST

  • the CSRF token must be added to the request You can access it on the ServletRequest using the attribute _csrf as illustrated above.

你可能感兴趣的:(Spring,Security,java)