Spring boot + Spring Security(一)

目标: Spring Boot + Spring Security + OAuth2 (数据库存储用户信息)
首先说下Spring Security,引入依赖:
org.springframework.boot
spring-boot-starter-security
org.springframework.boot
spring-boot-starter-web
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.2
com.alibaba
druid
1.1.9
org.springframework.boot
spring-boot-devtools
runtime
mysql
mysql-connector-java
runtime
根据数据库里的用户和角色表写实体类:
public class User implements Serializable {
private static final long serialVersionUID = 1L;
    private Integer id;
    private String username;
    private String password;
//get set
public class Role implements Serializable {
    private Integer id;
    private String role;
    private static final long serialVersionUID = 1L;
// get set
}
中间表:
public class UserRole implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private Integer uId;
private Integer rId;
private User users;
private Role roles;
//get set
}
根据实际需求,使用Spring Security时有两个顶级的接口要实现 UserDetails 和UserDetailsService,这里需要自己写这两个接口的实现 ,MyUserDetails 和MyUserDetailsService,在实现时需要重写里面的方法,有多种写法,都可以实现,就不再具体说明了。
下面写配置类 继承 WebSecurityConfigurerAdapter,并添加@Configuration @EnableWebSecurity 两个注解:
添加:
@Autowired
MyUserDetailsService userDetailsService;
@Bean(name="passwordEncoder")
public BCryptPasswordEncoder passworEncoder() {
return new BCryptPasswordEncoder();
}
重写configure(AuthenticationManagerBuilder auth) 方法,对登陆用户进行验证
//使用数据库验证(数据库中存储的是密文,后面要加上加密方式,securiyt 5 要求必须指定加密方式)
auth
.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
重写 configure(HttpSecurity http)进行网络访问控制
官方和源码中有各种配置方法可以参考,其中可能会出现的问题: (我出现的问题)
异常: Request method 'POST' not supported
原因:Spring Security默认开启CSRF(跨域请求保护),即使是在本机上,Spring Security也会模拟出是跨域请求,所以这里要对CSRF进行设置
解决方案:(官方)
(1)禁用CSRF
http.csrf().disable()
(2)使用_csrf请求属性来获取当前CsrfToken(jsp页面)
(3)提交HTTP报头中的令牌
(4)使用AJAX发送请求时把令牌包括进去
$(function () {
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function(e, xhr, options) {
xhr.setRequestHeader(header, token);
});
});
四种方法都可以解决这个问题。
源码: https://github.com/cyq741/project
自己写登陆页面(也可以用官方的登陆页面),跳转页面,写好Controller后,就可以看效果了。祝你成功!
需要交流请留言!

转载于:https://www.cnblogs.com/cyqjava/p/9041563.html

你可能感兴趣的:(数据库,java)