Spring-security
简介:Spring Security is a framework that provides authentication, authorization, and protection against common attacks. With first class support for both imperative and reactive applications, it is the de-facto standard for securing Spring-based applications.spring-security官方文档
一、实现权限访问资源和授权操作
继承一个类WebSecurityConfigurerAdapter
复写方法
1 |
|
使用antMatchers和hasRole控制访问的人的权限,前者是控制我们访问的路径,后者是控制我们的访问对象角色;
1 | protected void configure (AuthenticationManagerBuilder auth) throws Exception { |
为了安全,我们的密码必须要加密,不然系统认为你的密码不安全就会报错;
.withUser (“saxon”).password (new BCryptPasswordEncoder ().encode (“123456”)).roles (“vip1”, “vip2”, “vip3”)
- withUser :用户名
- password :密码
- roles :用户可以拥有的权限,和前面的hasRole对应
二、实现登录和注销的功能
一、登录功能
1 | http.formLogin (); |
自定义登陆页面:
1 | http.formLogin ().loginPage ("/toLogin"); |
前端:
1 | <form th:action="@{/toLogin}" method="post"> |
在看一下原码,我们就知道他的默认选项与前端的name对应;
1 | public FormLoginConfigurer() { |
我们就明白如果要后台接收这个数据的话,由以下两种方法
- 直接使用username和password
- 第二种,自己配置修改usernameParameter和passwordParameter就可以了;
二、注销功能
使CSRF失效;
1 | /** |
1 | "/logout" will log the user out by invalidating the HTTP Session, cleaning up any |
关键语句;
1 | <a class="item" th:href="@{/loginout}"> |
1 | http.csrf ().disable (); |
至于和thymeleaf的结合以后用到再说;再去网上查就可以了;
三、记住我功能
1 | http.rememberMe ().rememberMeParameter ("remember"); |
rememberMeParameter和前端的name属性结合,不然的话,就会失败;
记住我功能:
就是在你登陆的时候,会把你的信息存放在session与cookie里面,你下次打开浏览器就可以直接使用;不用再继续输入和登录,当然这是没有人显得无聊的时候,会去清除浏览器记录的情况下;



