Spring Security
食用前注意,Spring Security整合前要了解到:
- 应该在开发前构思
- 其属于aop思想
- 本篇基于狂神学习课程,先了解课程食用更佳
1 使用步骤
-
引入依赖
-
编写配置类开启注解@EnableWebSecurity
-
继承并定义方法
2 授权(授权通过访问)
http链式编程:允许与禁止(http.formlogin有自带识别注解,登录认证的规范和强大之处)
授权代码思路:
http.授权认证请求
.对应页面.全都可以
.对应页面.对应角色可以通过
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
http.没有权限则回到登录页面
http.formLogin();
3 认证(确认授予身份)
注意密码加密
认证代码思路:
auth.在内存请求认证.密码加密(编码规则)
.对用户姓名.密码(编码规则).角色
.且
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("kuangshen").password("123456").roles("vip2","vip3")
.and()
.withUser("root").password("123456").roles("vip1","vip2","vip3")
.and()
.withUser("guest").password("123456").roles("vip1","vip2");
4 注销
注销代码思路:
开启自动配置的注销的功能(跳转到登录页)
http.logout();
前端,增加一个注销的按钮
<a class="item" th:href="@{/logout}">
<i class="address card icon"></i> 注销
</a>
注销后跳转到其他页面
http.logout().logoutSuccessUrl("/");
5 根据thymeleaf动态显示(权限)
https://www.cnblogs.com/xiaoqi/p/spring-security-usage.html
6 记住我(cookie)
略
7 定制登录页
略
8 其他
- 后续补充前后分离版本