SpringBoot2.0 整合 SpringSecurity 框架,实现用户权限安全管理
本文源码:GitHub·点这里 || GitEE·点这里
一、Security简介
1、基础概念
Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring的IOC,DI,AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为安全控制编写大量重复代码的工作。
2、核心API解读
1)、SecurityContextHolder
最基本的对象,保存着当前会话用户认证,权限,鉴权等核心数据。SecurityContextHolder默认使用ThreadLocal策略来存储认证信息,与线程绑定的策略。用户退出时,自动清除当前线程的认证信息。
初始化源码:明显使用ThreadLocal线程。
private static void initialize() {
if (!StringUtils.hasText(strategyName)) {
strategyName = "MODE_THREADLOCAL";
}
if (strategyName.equals("MODE_THREADLOCAL")) {
strategy = new ThreadLocalSecurityContextHolderStrategy();
} else if (strategyName.equals("MODE_INHERITABLETHREADLOCAL")) {
strategy = new InheritableThreadLocalSecurityContextHolderStrategy();
} else if (strategyName.equals("MODE_GLOBAL")) {
strategy = new GlobalSecurityContextHolderStrategy();
} else {
try {
Class<?> clazz = Class.forName(strategyName);
Constructor<?> customStrategy = clazz.getConstructor();
strategy = (SecurityContextHolderStrategy)customStrategy.newInstance();
} catch (Exception var2) {
ReflectionUtils.handleReflectionException(var2);
}
}
++initializeCount;
}
2)、Authentication
源代码
public interface Authentication extends Principal, Serializable {
Collection<? extends GrantedAuthority> getAuthorities();
Object getCredentials();
Object getDetails();
Object getPrincipal();
boolean isAuthenticated();
void setAuthenticated(boolean var1) throws IllegalArgumentException;
}
源码分析
1)、getAuthorities,权限列表,通常是代表权限的字符串集合;
2)、getCredentials,密码,认证之后会移出,来保证安全性;
3)、getDetails,请求的细节参数;
4)、getPrincipal, 核心身份信息,一般返回UserDetails的实现类。
3)、UserDetails
封装了用户的详细的信息。
public interface UserDetails extends Serializable {
Collection<? extends GrantedAuthority> getAuthorities();
String getPassword();
String getUsername();
boolean isAccountNonExpired();
boolean isAccountNonLocked();
boolean isCredentialsNonExpired();
boolean isEnabled();
}
4)、UserDetailsService
实现该接口,自定义用户认证流程,通常读取数据库,对比用户的登录信息,完成认证,授权。
public interface UserDetailsService {
UserDetails loadUserByUsername(String var1) throws UsernameNotFoundException;
}
5)、AuthenticationManager
认证流程顶级接口。可以通过实现AuthenticationManager接口来自定义自己的认证方式,Spring提供了一个默认的实现,ProviderManager。
public interface AuthenticationManager {
Authentication authenticate(Authentication var1) throws AuthenticationException;
}
二、与SpringBoot2整合
1、流程描述
1)、三个页面分类,page1、page2、page3
2)、未登录授权都不可以访问
3)、登录后根据用户权限,访问指定页面
4)、对于未授权页面,访问返回403:资源不可用
2、核心依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
3、核心配置
/**
* EnableWebSecurity注解使得SpringMVC集成了Spring Security的web安全支持
*/
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 权限配置
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
// 配置拦截规则
http.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/page1/**").hasRole("LEVEL1")
.antMatchers("/page2/**").hasRole("LEVEL2")
.antMatchers("/page3/**").hasRole("LEVEL3");
// 配置登录功能
http.formLogin().usernameParameter("user")
.passwordParameter("pwd")
.loginPage("/userLogin");
// 注销成功跳转首页
http.logout().logoutSuccessUrl("/");
//开启记住我功能
http.rememberMe().rememberMeParameter("remeber");
}
/**
* 自定义认证数据源
*/
@Override
protected void configure(AuthenticationManagerBuilder builder) throws Exception{
builder.userDetailsService(userDetailService())
.passwordEncoder(passwordEncoder());
}
@Bean
public UserDetailServiceImpl userDetailService (){
return new UserDetailServiceImpl () ;
}
/**
* 密码加密
*/
@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
/*
* 硬编码几个用户
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("spring").password("123456").roles("LEVEL1","LEVEL2")
.and()
.withUser("summer").password("123456").roles("LEVEL2","LEVEL3")
.and()
.withUser("autumn").password("123456").roles("LEVEL1","LEVEL3");
}
*/
}
4、认证流程
@Service
public class UserDetailServiceImpl implements UserDetailsService {
@Resource
private UserRoleMapper userRoleMapper ;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 这里可以捕获异常,使用异常映射,抛出指定的提示信息
// 用户校验的操作
// 假设密码是数据库查询的 123
String password = "$2a$10$XcigeMfToGQ2bqRToFtUi.sG1V.HhrJV6RBjji1yncXReSNNIPl1K";
// 假设角色是数据库查询的
List<String> roleList = userRoleMapper.selectByUserName(username) ;
List<GrantedAuthority> grantedAuthorityList = new ArrayList<>() ;
/*
* Spring Boot 2.0 版本踩坑
* 必须要 ROLE_ 前缀, 因为 hasRole("LEVEL1")判断时会自动加上ROLE_前缀变成 ROLE_LEVEL1 ,
* 如果不加前缀一般就会出现403错误
* 在给用户赋权限时,数据库存储必须是完整的权限标识ROLE_LEVEL1
*/
if (roleList != null && roleList.size()>0){
for (String role : roleList){
grantedAuthorityList.add(new SimpleGrantedAuthority(role)) ;
}
}
return new User(username,password,grantedAuthorityList);
}
}
5、测试接口
@Controller
public class PageController {
/**
* 首页
*/
@RequestMapping("/")
public String index (){
return "home" ;
}
/**
* 登录页
*/
@RequestMapping("/userLogin")
public String loginPage (){
return "pages/login" ;
}
/**
* page1 下页面
*/
@PreAuthorize("hasAuthority('LEVEL1')")
@RequestMapping("/page1/{pageName}")
public String onePage (@PathVariable("pageName") String pageName){
return "pages/page1/"+pageName ;
}
/**
* page2 下页面
*/
@PreAuthorize("hasAuthority('LEVEL2')")
@RequestMapping("/page2/{pageName}")
public String twoPage (@PathVariable("pageName") String pageName){
return "pages/page2/"+pageName ;
}
/**
* page3 下页面
*/
@PreAuthorize("hasAuthority('LEVEL3')")
@RequestMapping("/page3/{pageName}")
public String threePage (@PathVariable("pageName") String pageName){
return "pages/page3/"+pageName ;
}
}
6、登录界面
这里要和Security的配置文件相对应。
<div align="center">
<form th:action="@{/userLogin}" method="post">
用户名:<input name="user"/><br>
密 码:<input name="pwd"><br/>
<input type="checkbox" name="remeber"> 记住我<br/>
<input type="submit" value="Login">
</form>
</div>
三、源代码地址
GitHub·地址
https://github.com/cicadasmile/middle-ware-parent
GitEE·地址
https://gitee.com/cicadasmile/middle-ware-parent

SpringBoot2.0 整合 SpringSecurity 框架,实现用户权限安全管理的更多相关文章
- SpringBoot2.0 整合 Dubbo框架 ,实现RPC服务远程调用
一.Dubbo框架简介 1.框架依赖 图例说明: 1)图中小方块 Protocol, Cluster, Proxy, Service, Container, Registry, Monitor 代表层 ...
- SpringBoot2.0 整合 Shiro 框架,实现用户权限管理
本文源码:GitHub·点这里 || GitEE·点这里 一.Shiro简介 1.基础概念 Apache Shiro是一个强大且易用的Java安全框架,执行身份验证.授权.密码和会话管理.作为一款安全 ...
- springboot2.0整合springsecurity前后端分离进行自定义权限控制
在阅读本文之前可以先看看springsecurity的基本执行流程,下面我展示一些核心配置文件,后面给出完整的整合代码到git上面,有兴趣的小伙伴可以下载进行研究 使用maven工程构建项目,首先需要 ...
- SpringBoot2.0 整合 JWT 框架,解决Token跨域验证问题
本文源码:GitHub·点这里 || GitEE·点这里 一.传统Session认证 1.认证过程 1.用户向服务器发送用户名和密码. 2.服务器验证后在当前对话(session)保存相关数据. 3. ...
- SpringBoot2.0整合SpringSecurity实现自定义表单登录
我们知道企业级权限框架一般有Shiro,Shiro虽然强大,但是却不属于Spring成员之一,接下来我们说说SpringSecurity这款强大的安全框架.费话不多说,直接上干货. pom文件引入以下 ...
- SpringBoot2.0 整合 ElasticSearch框架,实现高性能搜索引擎
本文源码:GitHub·点这里 || GitEE·点这里 一.安装和简介 ElasticSearch是一个基于Lucene的搜索服务器.它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful ...
- SpringBoot2.0整合SpringSecurity实现WEB JWT认证
相信很多做技术的朋友都做过前后端分离项目,项目分离后认证就靠JWT,费话不多说,直接上干活(写的不好还请多多见谅,大牛请绕行) 直接上代码,项目为Maven项目,结构如图: 包分类如下: com.ap ...
- (十三)整合 SpringSecurity 框架,实现用户权限管理
整合 SpringSecurity 框架,实现用户权限管理 1.Security简介 1.1 基础概念 1.2 核心API解读 2.SpringBoot整合SpringSecurity 2.1 流程描 ...
- SpringBoot2.0 整合 QuartJob ,实现定时器实时管理
一.QuartJob简介 1.一句话描述 Quartz是一个完全由java编写的开源作业调度框架,形式简易,功能强大. 2.核心API (1).Scheduler 代表一个 Quartz 的独立运行容 ...
随机推荐
- 【TCP/IP网络编程】:04基于TCP的服务器端/客户端
摘要:结合前面所讲述的知识,本篇文章主要介绍了简单服务器端和客户端实现的框架流程及相关函数接口. 理解TCP和UDP 根据数据传输方式的不同,基于网络协议的套接字一般分为TCP套接字和UDP套接字(本 ...
- NodeJS3-4基础API----fs(文件系统)
异步的形式总是将完成回调作为其最后一个参数. 传给完成回调的参数取决于具体方法,但第一个参数始终预留用于异常. 如果操作成功完成,则第一个参数将为 null 或 undefined. 1.读取文件操作 ...
- hexo + next 搭建博客时Cannot GET /tags/问题处理
原来是要修改新建的index.md文件,不仔细. 此外,愈发觉得百度和谷歌搜索同一问题的差距,谷歌更适合程序员! https://www.zhihu.com/question/29017171 这个可 ...
- 《Dotnet9》系列-FluentValidation在C# WPF中的应用
时间如流水,只能流去不流回! 点赞再看,养成习惯,这是您给我创作的动力! 本文 Dotnet9 https://dotnet9.com 已收录,站长乐于分享dotnet相关技术,比如Winform.W ...
- PHP中抽象类和接口的区别
抽象类 抽象类无法被实例化,它的作用是为所有继承自它的类定义(或部分实现)接口. 使用 abstract 关键字定义抽象类. 可以像在普通类中那样在抽象类中创建方法和属性,在大多数情况下,一个抽象类至 ...
- Visual Studio中相对路径中的宏定义
$(RemoteMachine) 设置为“调试”属性页上“远程计算机”属性的值.有关更多信息,请参见更改用于 C/C++ 调试配置的项目设置. $(References) 以分号分隔的引用列表被添加到 ...
- Appium(九):Appium API(三) 滑动和拖拽、高级手势、手机操作
1. 滑动和拖拽 我们在做自动化测试的时候,有些按钮是需要滑动几次屏幕后才会出现,此时,我们需要使用代码来模拟手指的滑动,也就是接下来要学的滑动和拖拽了. 1.1 swipe滑动事件 从一个坐标位置滑 ...
- How we implemented consistent hashing efficiently
原文链接https://medium.com/ably-realtime/how-to-implement-consistent-hashing-efficiently-fe038d59fff2 我们 ...
- JavaScript数组循环
JavaScript数组循环 一.前言 利用Javascript map(),reduce()和filter()数组方法可以遍历数组.而不是积累起来for循环和嵌套来处理列表和集合中的数据,利用这些方 ...
- Vue---记一次通过{{}}获取json数据-页面渲染不出来的坑
前两天干活儿的时候碰到一个Vue的问题,让我这个菜鸡完全摸不到头脑,需求如下:前端页面点击表格中的某一行的详情按钮,会弹出一个Dialog,然后Dialog中有选项卡,选项卡中再有具体的table来展 ...