关键词:
1、概述
Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架。
它是用于保护基于Spring的应用程序的实际标准。
Spring Security是一个框架,致力于为Java应用程序提供身份验证和授权。
与所有Spring项目一样,Spring Security的真正强大之处在于可以轻松扩展以满足自定义要求
springboot对于springSecurity提供了自动化配置方案,可以使用更少的配置来使用springsecurity
而在项目开发中,主要用于对用户的认证和授权
官网:https://spring.io/projects/spring-security
2、数据库使用Mysql,使用mybatis-plus框架
3、大致结构图如下:
控制器用HelloController就行,因为使用mybatis-plus代码生成的有一些没用的配置
4、使用依赖如下:
spring-boot用的2.1.18 RELEASE
5、application.properties配置文件如下:
# 数据库驱动:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 数据库连接地址
spring.datasource.url=jdbc:mysql:///rog?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
# 数据库用户名&密码:
spring.datasource.username=root
spring.datasource.password=root
#日志输出,使用默认的控制台输出
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#mybatis plus 设置
mybatis-plus.mapper-locations=classpath*:com/xxx/mapper/xml/*Mapper.xml
#配置别名扫描
mybatis-plus.type-aliases-package=com.xxx.entity
6、mysql数据库
这里使用了3张表,分别是user、role、user_role
7、entity-实体类大致如下:
注意需要对应数据库的id自动递增
8、mapper包
因为使用的mabits-plus代码生成所以对应的mapper,所以生成好是继承了BaseMapper,如果手动写的话,就需要继承BaseMapper
查询数据库当前请求登录的用户,获取他所拥有的所有权限
9、service
@Service()
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService, UserDetailsService
@Autowired
private UsersMapper usersMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
QueryWrapper<Users> wrapper = new QueryWrapper<>();
wrapper.eq("user_name",username);
//根据页面传的用户名查找数据库判断是否存在该用户
Users users = usersMapper.selectOne(wrapper);
if (users==null)
throw new UsernameNotFoundException("用户不存在");
List<Role> roles = usersMapper.findRoles(users.getId());
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
//遍历当前用户的角色集合组装权限
for (Role role : roles)
authorities.add(new SimpleGrantedAuthority(role.getName()));
return new User(username,users.getPassword(),authorities);//如果用户没有角色会NullPointerException
需要实现 UserDetailsService接口重写 loadUserByUsername方法,做了一个简单逻辑
10、测试是否连接上了数据库
新增一个用户,数据新增成功返回row>0,表示已经连接数据库成功
11、controller层写一个简单的控制器
12、config包下配置一下权限认证框架配置
@Configuration
@MapperScan("com.xxx.mapper")
public class SecurityConfig extends WebSecurityConfigurerAdapter
@Autowired
private UserDetailsService userDetailsService;
@Bean
PasswordEncoder passwordEncoder()
//使用明文密码:为了简单方便测试
return NoOpPasswordEncoder.getInstance();
//暗文密码:会用salt加密
// return new BCryptPasswordEncoder();
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception
//设置注入的自定义认证实现类userService,必须实现了UserDetailsService接口
auth.userDetailsService(userDetailsService);
@Override
protected void configure(HttpSecurity http) throws Exception
http.authorizeRequests()
//.antMatchers需要写在 .anyRequest()之前
/* anyRequest 已经包含了其他请求了,在它之后如果还配置其他请求也没有任何意义。
anyRequest 应该放在最后,表示除了前面拦截规则之外,剩下的请求要如何处理。具体可以稍微查看一下源码,
在拦截规则的配置类 AbstractRequestMatcherRegistry 中*/
.antMatchers("/admin/**").hasRole("admin")//以/admin作为前缀的请求必须具有admin权限才能访问(当前也必须认证通过)
.antMatchers("/user/**").hasRole("user")//以/user作为前缀的请求必须具有user权限才能访问(当前也必须认证通过)
.anyRequest().authenticated()//任何请求都认证过放行
.and()//方法表示结束当前标签,上下文回到HttpSecurity,开启新一轮的配置。
.formLogin()//使用表单认证
.loginProcessingUrl("/doLogin")//指定登录页面提交数据的接口
.successHandler((req, resp, authentication) ->
Object principal = authentication.getPrincipal();//获取认证成功的用户对象
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
//使用Jackson将对象转换为JSON字符串
out.write(new ObjectMapper().writeValueAsString(principal));//将登录成功的对象基于JSON响应
out.flush();
out.close();
)
.failureHandler((req, resp, e) -> //根据异常信息判断哪一操作出现错误
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
Map<String, Object> map = new HashMap<String, Object>();
map.put("status", 400);
if (e instanceof LockedException)
map.put("msg", "账户被锁定,请联系管理员!");
else if (e instanceof CredentialsExpiredException)
map.put("msg", "密码过期,请联系管理员!");
else if (e instanceof AccountExpiredException)
map.put("msg", "账户过期,请联系管理员!");
else if (e instanceof DisabledException)
map.put("msg", "账户被禁用,请联系管理员!");
else if (e instanceof BadCredentialsException)
map.put("msg", "用户名或者密码输入错误,请重新输入!");
out.write(new ObjectMapper().writeValueAsString(map));
out.flush();
out.close();
)
.permitAll()//放行自定义登录页面请求
.and()
.logout()//默认注销接口/logout
.logoutUrl("/logout")//默认注销的URL
//基于前后端分离开发,前端发起/logout请求,后端自定义注销成功处理逻辑:返回json提示成功
.logoutSuccessHandler((req, resp, authentication) ->
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
out.write("注销成功");
out.flush();
out.close();
)
.permitAll()
.and()
.csrf().disable()//关闭csrf攻击拦截
//配置未认证提示,给未认证(登录成功)访问其他请求时,给前端响应json提示
.exceptionHandling()
.authenticationEntryPoint((req, resp, authException) ->
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
out.write("尚未登录,请先登录");
out.flush();
out.close();
);
因为使用postman测试所有就没有写自定义页面,如果自定义登录界面需要配置一个静态资源放行
13、postman测试
登录需要使用post请求,和表单提交方式
右边响应格式,如果你的实体没有实现UserDetails接口,返回的json格式便是固定的
属性对应分别是accountNonExpired、accountNonLocked、credentialsNonExpired、enabled 这四个属性分别用来描述用户的状态,表示账户是否没有过期、账户是否没有被锁定、密码是否没有过期、以及账户是否可用。
不需要任何授权即可访问:
需要用户权限才能访问:
需要管理员权限才能访问(当前登录用户没有管理员权限所以他无法访问当前页面):
注销当前登录用户,会默认清除Cookies以及认证信息和使session失效,当然也可以在配置类中显示配置一下
再次访问页面,就会提示先登录在访问
以上就是Spring Security 简单整合mybatis-plus大概的过程,个人觉得还算是比较详细哈哈。。。
springboot整合websocket简单聊天室(代码片段)
springboot整合websocket(一)简单聊天室springboot整合websocket(一)简单聊天室springboot整合websocket(二)上传文件(引导篇)springboot整合websocket(三)上传文件(终篇& 查看详情
websocket教程springboot+maven整合(目录)
...、课程技术选型和浏览器兼容讲解简介:简单介绍什么是springboot、socketjs、stompjs,及解决使用浏览器兼容问题3、websocket广播、单播、组播介绍和使用场景说明简介:主要讲解websocket的一些概念,如广播,单播等,他们的基本区... 查看详情
springboot日记——redis整合
...windows安装使用redis吧~(看这里也可以) 正题: SpringBoot对应(自带)Redis 查看详情
springboot检索篇ⅳ---整合elasticsearch
知识储备: 关于ElasticSearch的基本使用我已经在上一篇文章介绍过了(传送门),本篇文章主要讲述的是SpringBoot与ElasticSearch的整合以及简单的使用。 查看详情
springboot整合websocket
...t:在浏览器和服务器之间建立tcp连接,实现全双工通信??springboot使用websocket有两种方式,一种是实现简单的websocket,另外一种是实现STOMP协议。这一篇实现简单的webso 查看详情
springboot整合layui和thymeleaf制作简单登录页面
前面已经学习过SpringBoot整合Thymeleaf,这次主要把上次提到的简单登录界面用博文形式写出来记录一个小Demo的学习,如果没看过SpringBoot整合Thymeleaf可以看一下SpringBoot整合Thymeleaf(三)先上页面效果图:Demo所涉及的知识点1.SpringBoot... 查看详情
springboot整合flyway
SpringBoot整合Flyway数据库版本迁移工具使用Flyway官网:https://flywaydb.org/documentation/使用感想:数据库的传统部署到自动化部署,工具的便利性使的开发更具效率性!简介:Flyway是一个开源数据库迁移工具。与配置相比,它极力主张... 查看详情
springboot整合mongodb(实现一个简单缓存)(代码片段)
...预备工作缓存查询缓存更新、删除缓存更新缓存删除前言SpringBoot是常用开发框架,而MongoDB也是最近越来越火的非关系型数据库,这里使用SpringBoot+MongoDB实现一个小案例,当然MongoDB实际做缓存的可能不多,但是... 查看详情
springboot整合ehcache缓存
...分布式存储方式等多种灵活的cache管理方案,快速简单。Springboot对ehcache的使用非常支持,所以在Springboot中只需做些配置就可使用,且使用方式也简易。在你的项目上配置以下几步即可使用首先,老规矩,pom.xml加依赖; <!--S 查看详情
springboot整合layui和thymeleaf制作简单登录页面
前面已经学习过SpringBoot整合Thymeleaf,这次主要把上次提到的简单登录界面用博文形式写出来记录一个小Demo的学习,如果没看过SpringBoot整合Thymeleaf可以看一下SpringBoot整合Thymeleaf(三)先上页面效果图:Demo所涉及的知识... 查看详情
《springboot+dubbo+zookeeper整合搭建简单的分布式应用》(代码片段)
为什么要使用分布式系统?容错减少延迟/提高性能可用性负载均衡总而言之,其实目的只有一个,”用户体验“。什么是分布式系统?分布式系统是由使用分发中间件连接的自治计算机组成的网络。它们有助于共享不同的资源... 查看详情
springboot整合websocket,使用stomp协议,前后端整合实战(代码片段)
... 一篇极简风,最最最基础的方式整合websocket:《SpringBoot整合WebSocket简单实战案例》地址: https://blog.csdn.net/qq_35387940/article/details/ 查看详情
springboot学习——springboot快速整合rabbitmq
RabbitMQ消息队列@[toc]简介优点erlang开发,并发能力强。社区活跃,使用的人多,稳定性较强。延时低缺点erlang语言开发的,国内精通的不多,日后定制开发困难。RabbitMQ工作模式1,"HelloWorld!"模式简单模式是RabbitMQ最简单入... 查看详情
springboot整合guavacache缓存
缓存的主要作用是暂时在内存中保存业务系统的数据处理结果,并且等待下次访问使用。对于那些频繁需要查询比对的热点数据,我们采用使用缓存。 GuavaCache是google出品的内存缓存工具。对于数据量较小的,... 查看详情
springboot2系列教程|springboot整合mybatis
前言如题,今天介绍SpringBoot与Mybatis的整合以及Mybatis的使用,本文通过注解的形式实现。什么是MybatisMyBatis是支持定制化SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis避免了几乎所有的JDBC代码和手动设置参数以及获取... 查看详情
springboot整合redis缓存
...非常流行的NoSQL数据库(Redis)来实现我们的缓存需求。SpringBoot整合Redis是非常方便快捷的,我用的是Mybatis,这里就不说Springboot整合Mybatis了网上有很多,同样非常简单。下面进入正题: 查看详情
springboot整合mongodb及简单的操作
一,环境搭建1)引入依赖<parent><artifactId>spring-boot-parent</artifactId><groupId>org.springframework.boot</groupId><version>2.3.7.RELEASE</version></p 查看详情
springboot整合rocketmq实现入门案例
...习了Spring整合RocketMQ的第一个案例!现在我们来学习SpringBoot如何整合RocketMQ实现更加简单的使用!文章目录1创建maven项目2配置文件3生产者4消费者5测试1创建maven项目创建一个maven项目。引入sp 查看详情