简介:
Spring Security对Web安全性的支持大量地依赖于Servlet过滤器。
实际上是运用的springMVC的AOP实现的。(扩展性)
授权:
①角色授权
②注销
③记住我
④登录
认证:
①从数据库认证
②从内存认证
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import javax.sql.DataSource;
/**
* @Author: 说谎 说明:
* @Date 2022/4/28 11:35
*/
@EnableWebSecurity
public class securityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
//授权
@Override
protected void configure(HttpSecurity http) throws Exception {
//首页所有人都可以访问,功能页只有对应的vip才能访问
//请求授权(链式编程)
http.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/vip1/**").hasRole("vip1")
.antMatchers("/vip2/**").hasRole("vip2")
.antMatchers("/vip3/**").hasRole("vip3");
//没有权限全部跳转首页,开启登录的页面(请求登录url"/toLogin")
//login 定制登录页:.loginPage("/toLogin")
http.formLogin().loginPage("/toLogin")
//前端传的默认是username,那么这个可以不写,否则要设置
.usernameParameter("user")
//前端传的默认是password,那么这个可以不写,否则要设置
.passwordParameter("pwd")
//中转站:登录时先做验证,相当于走的security的login去进行验证
.loginProcessingUrl("/login")
//成功跳转主页
.successForwardUrl("/main")
//失败跳转回登录
.failureForwardUrl("/login");
//防止网站攻击 get post
http.csrf().disable(); //关闭 csrf 功能,这个是网站登出失败可能存在的原因
//注销。 开启注销功能(请求url"/logout")
//清除所有的cookie数据、session数据(一般不用)
http.logout().deleteCookies("remove").invalidateHttpSession(true)
//指定跳出的位置
.logoutSuccessUrl("/");
//开启记住我功能: ①实际就是添加了cookie 默认保存2周 ②在服务器端放了个session
http.rememberMe()
//自定义前端传过来的"记住我"的参数名
.rememberMeParameter("remember");
}
//认证
//密码编码: PasswordEncoder
//在spring Security 5.0+ 新增了很多加密方法
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//从数据库认证
auth.jdbcAuthentication().dataSource(dataSource)
//enabled 是否可用
.usersByUsernameQuery("select username,password,enabled from users WHERE username=?")
//authority 角色
.authoritiesByUsernameQuery("select username,authority from authorities where username=?")
.passwordEncoder(new BCryptPasswordEncoder());
//从内存认证
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("说谎").password(encodePassword("123456")).roles("vip1","vip3")
//用.and连接多个用户认证
.and()
.withUser("说谎的嘴").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2");
}
//注册时,给密码加密的方法 BCryptPasswordEncoder
public static String encodePassword(String password) {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder.encode(password);
}
}