SpringSecurity简单入门,新手易懂
1、要实现SpringSecurity的功能,首先我们要去继承WebSecurityConfigurerAdapter类!
2、认证。
重写configure(AuthenticationManagerBuilder auth)
方法,对用户进行认证
如:用户名=小白说Java,密码=123456,认证以此信息登陆者为vip1和vip2角色,一个用户可以认证多个角色
//用户认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//这些数据正常在数据库里读
//为用户认证权限
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("小白说Java").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
.and().withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
.and().withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}
3、授权。
重写configure(HttpSecurity http)方法。对不同角色授予访问页面的权限。
如:
level1下的所有接口访问权限均给了vip1角色。
故为vip1角色的用户可以访问这些页面。
@Override
protected void configure(HttpSecurity http) throws Exception {
//首页所有人可以访问,功能页只有对应权限的人可以访问
//授权请求
http.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
//如果用户没有权限则自动跳到SpringSecuruty自带的登录页面
http.formLogin();
//如果需要跳到自己写的登录页面,
//则这么写:http.formLogin().loginPage("/login.html")
//开启SpringSecuruty自带注销功能
//SpringSecuruty同时自带了登出的配置,其默认地址为/logout
//只要开启此功能,当跳转到/logout即完成注销!
http.logout();
}