准备登录页面
登录页面名称随便取,我们假设为 login.html
登录的 form 表单 submit 链接随便取,我们假设为 /login
简单的登录页面, 假定只有 username 和 password, form 表单提交方式为 POST
这样就准备就绪了, 开始配置 Spring Security 吧
Spring Security 配置
如果你用的 gradle, 在 spring-boot 依赖后面添加 spring-security 的依赖:
//${version} 请自己配置适合自己的版本 //下面是 Spring Boot 下的 Spring Security. 如果不是 boot 的,将会出现问题 compile('org.springframework.boot:spring-boot-starter-security:${version}') //下面是 thymeleaf 框架, 主要是给前段页面获取登录状态用的 //如果你用的 Spring3,记得最后改为thymeleaf-extras-springsecurity3 compile('org.thymeleaf.extras:thymeleaf-extras-springsecurity4:${version}')
然后新建一个配置 class, 比如 SecurityConfig
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() // 不用防跨站攻击防御 .authorizeRequests() .antMatchers("/css/**","/js/**","/").permitAll() // 允许这些请求 .anyRequest().authenticated() // 请求记录为已验证 .and() .formLogin() // 表单登录 接收 POST /login .loginPage("/login") // 登录的页面, 一个 Spring 请求导向 login.html .loginProcessingUrl("/loginSuccess") // 登录成功后的页面, 不设置为上一个页面 或 主页 .permitAll() // 允许 login 的页面请求 .and() .logout() // 接收 POST /logout .logoutSuccessUrl("/logoutSuccess") .permitAll(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("username") //帐号 .password("password") // 密码 .roles("ADMIN"); // 登录用户角色 } }
此外你还必须在你的 Controller 中定义一个 GET /login 的请求, 指向你的 login.html
这样即可. 接下来你就可以试试你的登录页面啦.Spring Security 会自动为你生成 login 和 logout 的 POST 请求, 并且会签发验证.
页面上获取登录结果
最简单的就是引用 thymeleaf 的标签来实现
<html xmlns:th="http://www.thymeleaf.org">
然后用类似 th:text这样的标签就能获取到登录状态啦
<!-- 你可以 debug 打印 authentication 的内容 --> <div th:text="${#authentication}"></div>
其中 authentication 是注入的 org.springframework.security.authentication.UsernamePasswordAuthenticationToken 对象. 大家可以自己去看看里面有哪些方法, 就能在页面调用啦, 比如
<div th:if="${#authentication.isAuthenticated()}"></div> <div th:text="${#authentication.name}"></div>
Junit 测试
SpringSecurity 在测试中有不少的坑. 首先引依赖包
testCompile('org.springframework.boot:spring-boot-starter-test:${version}') testCompile('org.springframework.security:spring-security-test:${version}')
虽说不知道为什么, 但是如果你引入org.springframework.boot:spring–boot-security-tests 会出现问题! 不能用 boot 的包!
接下来在你的测试中 apply springSecurity()即可:
webAppContextSetup(context, springSecurity()) 或者 webAppContextSetup(context).apply(springSecurity())
这样测试才会应用 security 的配置.