创建spring安全Java配置
该配置创建了一个servlet筛选器,称为springSecurityFilterChain,负责所有安全(保护应用程序URL、验证提交的用户名和密码、重定向到表单中的日志等)。
方式一:
方式二:spring官网上给出的示例方法
思考:
01. 两种方法有什么区别?(我采用的是第一种)
这个配置所做的事情有:
- 在应用程序中对每个URL进行验证
- 为你生成一个登陆表单
- 允许使用用户名Username user和密码Password password使用验证表单
- 允许用户登出
- CSRF攻击预防
- 会话固定 Session保护
- 安全Header集成
- HTTP Strict Transport Security 对安全要求严格的HTTP传输安全
- X-Content-Type-Options集成
- 缓存控制(稍后可以允许你缓存静态资源)
- X-XSS-Protection集成
- X-Frame-Options 集成防止点击劫持
8. 和以下Servlet API方法集成
- HttpServletRequest#getRemoteUser()
- HttpServletRequest.html#getUserPrincipal()
- HttpServletRequest.html#isUserInRole(java.lang.String)
- HttpServletRequest.html#login(java.lang.String, java.lang.String) HttpServletRequest.html#logout()
思考:
02. Spring Security怎么知道我们相对所有的用户进行验证? Spring Securityn怎么知道我们需要支持基于表单的验证?
原因是 WebSecurityConfigurerAdapter 在 configure(HttpSecurity http) 方法中提 供了一个默认的配置。
上面的默认配置:
- 确保我们应用中的所有请求都需要用户被认证
- 允许用户进行基于表单的认证
- 允许用户使用HTTP基于验证进行认证
你可以看到这个配置和下面的XML命名配置相似:
<http>
<intercept-url pattern="/**" access="authenticated"/> <form-login />
<http-basic /></http>
java配置使用 and() 方法相当于XML标签的关闭。 这样允许我们继续配置父类节点。如果你阅读代码很合理,想配置请求验证, 并使用表单和HTTP基本身份验证进行登录。
自定义登陆页
重写protected void configure(HttpSecurity http) 方法自定义登陆页面
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll();
}
注意: .loginPage("/login")要加“/”否则疯狂报错=、=
Caused by: java.lang.IllegalArgumentException: 'login?error' is not a valid redirect URL
启动项目,配置登陆失败跳转页面
废话不多说,直接上代码
@Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .passwordEncoder( new BCryptPasswordEncoder()) .withUser("user") .password(new BCryptPasswordEncoder() .encode("user")) .roles("USER"); } protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/index").permitAll() .anyRequest() .authenticated() .and() .formLogin() .loginPage("/login").failureUrl("/errorPage") .permitAll(); }
注意:要加上密码验证 passwordEncoder( new BCryptPasswordEncoder()),否则会报错误:
java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"