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
2
3
4
5
6
@Override
protected void configure (HttpSecurity http) throws Exception {
http.authorizeRequests ().antMatchers ("/", "/index").permitAll ()
.antMatchers ("/level1/*").hasRole ("vip1")
.antMatchers ("/level2/*").hasRole ("vip2")
.antMatchers ("/level3/*").hasRole ("vip3");

使用antMatchershasRole控制访问的人的权限,前者是控制我们访问的路径,后者是控制我们的访问对象角色;

1
2
3
4
5
6
7
protected void configure (AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication ().passwordEncoder (new BCryptPasswordEncoder ())
.withUser ("saxon").password (new BCryptPasswordEncoder ().encode ("123456")).roles ("vip1", "vip2", "vip3")
.and ()
.withUser ("root").password (new BCryptPasswordEncoder ().encode ("123456")).roles ("vip1");
}
}

为了安全,我们的密码必须要加密,不然系统认为你的密码不安全就会报错;

.withUser (“saxon”).password (new BCryptPasswordEncoder ().encode (“123456”)).roles (“vip1”, “vip2”, “vip3”)

  • withUser :用户名
  • password :密码
  • roles :用户可以拥有的权限,和前面的hasRole对应

二、实现登录和注销的功能

一、登录功能
1
http.formLogin ();

自定义登陆页面:

1
http.formLogin ().loginPage ("/toLogin");

前端:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<form th:action="@{/toLogin}" method="post">
<div class="field">
<label>Username</label>
<div class="ui left icon input">
<input type="text" placeholder="Username" name="username">
<i class="user icon"></i>
</div>
</div>
<div class="field">
<label>Password</label>
<div class="ui left icon input">
<input type="password" name="password">
<i class="lock icon"></i>
</div>
</div>
<input type="submit" class="ui blue submit button"/>
</form>

在看一下原码,我们就知道他的默认选项与前端的name对应;

1
2
3
4
5
public FormLoginConfigurer() {
super(new UsernamePasswordAuthenticationFilter(), null);
usernameParameter("username");
passwordParameter("password");
}

我们就明白如果要后台接收这个数据的话,由以下两种方法

  • 直接使用username和password
  • 第二种,自己配置修改usernameParameterpasswordParameter就可以了;
二、注销功能

使CSRF失效;

关于CSRF的博文

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Provides logout support. This is automatically applied when using
* {@link WebSecurityConfigurerAdapter}. The default is that accessing the URL
* "/logout" will log the user out by invalidating the HTTP Session, cleaning up any
* {@link #rememberMe()} authentication that was configured, clearing the
* {@link SecurityContextHolder}, and then redirect to "/login?success".
*
* <h2>Example Custom Configuration</h2>
*
* The following customization to log out when the URL "/custom-logout" is invoked.
* Log out will remove the cookie named "remove", not invalidate the HttpSession,
* clear the SecurityContextHolder, and upon completion redirect to "/logout-success".
*
* <pre>
* &#064;Configuration
* &#064;EnableWebSecurity
* public class LogoutSecurityConfig extends WebSecurityConfigurerAdapter {
*
* &#064;Override
* protected void configure(HttpSecurity http) throws Exception {
* http
* .authorizeRequests(authorizeRequests ->
* authorizeRequests
* .antMatchers(&quot;/**&quot;).hasRole(&quot;USER&quot;)
* )
* .formLogin(withDefaults())
* // sample logout customization
* .logout(logout ->
* logout.deleteCookies(&quot;remove&quot;)
* .invalidateHttpSession(false)
* .logoutUrl(&quot;/custom-logout&quot;)
* .logoutSuccessUrl(&quot;/logout-success&quot;)
* );
* }
* }
* </pre>
*
* @param logoutCustomizer the {@link Customizer} to provide more options for
* the {@link LogoutConfigurer}
* @return the {@link HttpSecurity} for further customizations
* @throws Exception
*/
1
"/logout" will log the user out by invalidating the HTTP Session, cleaning up any

关键语句;

1
2
3
<a class="item" th:href="@{/loginout}">
<i class="address card icon"></i> 注销
</a>
1
2
http.csrf ().disable ();
http.logout ().logoutSuccessUrl ("/");

至于和thymeleaf的结合以后用到再说;再去网上查就可以了;

三、记住我功能
1
http.rememberMe ().rememberMeParameter ("remember");

rememberMeParameter和前端的name属性结合,不然的话,就会失败;

记住我功能:

就是在你登陆的时候,会把你的信息存放在session与cookie里面,你下次打开浏览器就可以直接使用;不用再继续输入和登录,当然这是没有人显得无聊的时候,会去清除浏览器记录的情况下;