Spring Security 简单配置一则
参考另一篇笔记: N_SpringSecurity
引入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>什么都没有配置
使用 user用户名及随机密码, 登陆
如果是非常简单的认证, 在application.properties 简单配置用户名密码即可,
spring.security.user.name=admin
spring.security.user.password=123456简单配置, 只有成功失败处理器其余默认
@Configuration//表明配置类
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
/**成功与失败的处理bean
*/
@Autowired
private AuthFailHandler authFailHandler;
@Autowired
private AuthSuccessHandler authSuccessHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
//这个配置 类似于 xml上的 security:http 配置
http.
authorizeRequests()//所有请求需要认证
// 如果有允许匿名的url, 填下面排除
// .antMatchers().permitAll()
.anyRequest().authenticated()
.and()
// 设置登陆页
.headers().frameOptions().sameOrigin()//注意这里! 它设置页面 frame 请求
//他的值有三个:
//(1)DENY — 表示该页面不允许在 frame 中展示, 即便是在相同域名的页面中嵌套也不允许;
//(2)SAMEORIGIN — 表示该页面可以在相同域名页面的 frame 中展示;
//(3)ALLOW-FROM https://example.com/ — 表示该页面可以在指定来源的 frame 中展示;
.and()
//授权异常的入口点
.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint ).and()
.formLogin()//类似xml form login
.failureHandler(authFailHandler)//失败处理
.successHandler(authSuccessHandler)//成功处理
// 设置默认成功失败页, 看源码这个与自定义处理器冲突
//.defaultSuccessUrl("/main")
//.failureForwardUrl("/").permitAll()
// 自定义登陆用户名和密码参数, 默认为username和password
// .usernameParameter("username")
// .passwordParameter("password")
.and()
.logout().permitAll();
// 关闭CSRF跨域
http.csrf().disable();
}
}