使用Spring Security防御CSRF攻击
- 解决方案就是提交表单加hash串
- 坑:表单提交携带csrf
<input th:name="${_csrf.parameterName}" th:value="${_csrf.token}">
- 配置csrf
- 关闭csrf
用户存储位置
配置文件
spring.security.user.name=aaa
spring.security.user.password=123
内存
- 不加密
- 或者
@Bean public UserDetailsService userDetailsService() { InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); User user = new User("a", new BCryptPasswordEncoder().encode("1"), true, true, true, true, Collections.singletonList(new SimpleGrantedAuthority("xx"))); manager.createUser(user); manager.createUser(User.withUsername("yiming").password(new BCryptPasswordEncoder().encode("xx")).roles("xxz").build()); return manager; }
Security中的User对象
private String password;
private final String username;
private final Set<GrantedAuthority> authorities;
private final boolean accountNonExpired;
private final boolean accountNonLocked;
private final boolean credentialsNonExpired;
private final boolean enabled;
Session中存储的对象
Enumeration<String> attributeNames = request.getSession().getAttributeNames();
// while (attributeNames.hasMoreElements()) {
// String string = (String) attributeNames.nextElement();
// System.out.println(string);
// System.out.println(request.getSession().getAttribute(string));
//
// }
SecurityContext attribute = (SecurityContext)request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
System.out.println(attribute.getAuthentication().getAuthorities());
忽略静态请求
@Override
public void configure(WebSecurity web) throws Exception {
// TODO Auto-generated method stub
web.ignoring().antMatchers("/img/**","/js/**");
// super.configure(web);
}
自定义登录页面
@Override
protected void configure(HttpSecurity http) throws Exception {
// TODO Auto-generated method stub
http.authorizeRequests()
//所有请求都需要验证
.anyRequest().authenticated()
.and()
//permitAll 给没登录的 用户可以访问这个地址的权限
.formLogin().loginPage("/login.html").permitAll();
}
自定义表单属性
@Override
protected void configure(HttpSecurity http) throws Exception {
// TODO Auto-generated method stub
http.authorizeRequests()
//所有请求都需要验证
.anyRequest().authenticated()
.and()
//permitAll 给没登录的 用户可以访问这个地址的权限
.formLogin().loginPage("/login.html")
//自定义表单
.usernameParameter("xx")
.passwordParameter("oo")
.loginProcessingUrl("/login")
.failureUrl("/login.html?error")
.defaultSuccessUrl("/").permitAll()
.and()
.csrf().csrfTokenRepository(new HttpSessionCsrfTokenRepository())
;
}
密码安全:暴力破解/字典/彩虹表
明文存储
- 网络中被偷窥:可以用https避免,但是电脑被黑了还是会泄露;
提交之前,就做加密,防止网络偷窥和程序员偷窥; - 持久化到数据库:暴露
摘要算法:快、不可逆、相同的源加密结果一样
- MD5,快就不健壮,穷举破解;
字典
- 每个人破解一小段,大家合并起来就是字典,就比如合买彩票;
彩虹表
- 分段碰撞
盐
注册阶段/校验阶段
固定盐(不安全)
随机盐
- 固定不变的用户名
- 随机数(拼接在hash完的密钥后)
- 多次加密(秒级别,性能比较差)
递归式的多次加密;
sha1 - sha256 区块链加密