自己开发完整项目一、登录功能-03(使用springSecurity安全框架,查询用户角色权限)

本文主要是介绍自己开发完整项目一、登录功能-03(使用springSecurity安全框架,查询用户角色权限),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、说明

在前面两章节,实现了通过springsecurity来进行用的登录认证,当用户输入用户名和密码之后,通过额数据库中的信息比对,比对成功那么放行。但是还存在一个问题:因为系统的所有页面包括按钮都是有各自的权限,那么要想实现不同的用户登录成功看到的页面不同并且有不同的操作范围,那么就需要对用户的权限进行验证。

实现的思路:在用户登录的时候,将用户的权限查询出来。

二、具体实现

1、创建roleModel

package com.ljy.myspringbootlogin.model;import com.baomidou.mybatisplus.annotation.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;import java.io.Serializable;
import java.util.List;@TableName("role")
public class RoleModel implements Serializable {/*** id*/@TableId(type = IdType.AUTO)private Long id;/*** 角色名称*/@TableField("role_name")private String roleName;/*** 角色标签*/@TableField("role_tag")private String roleTag;/*** 是否删除*/@TableField("is_deleted")private Long isDeleted;public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getRoleName() {return roleName;}public void setRoleName(String roleName) {this.roleName = roleName;}public String getRoleTag() {return roleTag;}public void setRoleTag(String roleTag) {this.roleTag = roleTag;}public Long getIsDeleted() {return isDeleted;}public void setIsDeleted(Long isDeleted) {this.isDeleted = isDeleted;}
}

2、创建menuModel

package com.ljy.myspringbootlogin.model;import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;import java.io.Serializable;
import java.util.List;@TableName("menu")
public class MenuModel implements Serializable {/*** id*/@TableId(type = IdType.AUTO)private Long id;/*** 权限名称*/@TableField("menu_name")private String menuName;/*** 权限标签*/@TableField("menu_tag")private String menuTag;/*** 是否删除*/@TableField("is_deleted")private Long isDeleted;/*** 权限父id*/@TableField("parent_id")private Long partendId;/*** 权限类型*/@TableField("menu_type")private Long menuType;public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getMenuName() {return menuName;}public void setMenuName(String menuName) {this.menuName = menuName;}public String getMenuTag() {return menuTag;}public void setMenuTag(String menuTag) {this.menuTag = menuTag;}public Long getIsDeleted() {return isDeleted;}public void setIsDeleted(Long isDeleted) {this.isDeleted = isDeleted;}public Long getPartendId() {return partendId;}public void setPartendId(Long partendId) {this.partendId = partendId;}public Long getMenuType() {return menuType;}public void setMenuType(Long menuType) {this.menuType = menuType;}
}

3、修改userModel

我们需要将用户的权限返回,而在springsecurity中,必须返回一个集成了userDetails的用户,所以我们为了方便,将角色信息和权限信息全部的返回到UserModel中。

package com.example.springsecurity03.model;import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;import java.util.Collection;
import java.util.List;/*** 用户*/
//当使用springsecurity做为安全框架的时候,用户model必须实现UserDetails,因为springsecuritty会使用UserDetails里面的权限信息和账号密码等信息
//进行认证和授权public class UserModel implements UserDetails {//idprivate Long id;//用户名private String username;//密码private String password;//权限private Collection<GrantedAuthority>  authorities;//是否锁定private boolean enabled;public void setEnabled(boolean enabled) {this.enabled = enabled;}public Long getId() {return id;}public void setId(Long id) {this.id = id;}@Overridepublic String getUsername() {return username;}public void setUsername(String username) {this.username = username;}@Overridepublic String getPassword() {return password;}public void setPassword(String password) {this.password = password;}@Overridepublic Collection<GrantedAuthority> getAuthorities() {return authorities;}public void setAuthorities(Collection<GrantedAuthority> authorities) {this.authorities = authorities;}/*** 判断账号是否未过期* @return*/@Overridepublic boolean isAccountNonExpired() {return true;}/***判断账号是否未被锁定* @return*/@Overridepublic boolean isAccountNonLocked() {return true;}/*** 判断密码是否未过期* @return*/@Overridepublic boolean isCredentialsNonExpired() {return true;}/*** 判断账号是否启用* @return*/@Overridepublic boolean isEnabled() {return enabled;}
}

 4、创建roleService

因为我们需要通过用户的id去查询角色的信息,所以我们需要在roleService中编写一个查询角色信息的接口,方便后续调用。

package com.ljy.myspringbootlogin.service;import com.baomidou.mybatisplus.extension.service.IService;
import com.ljy.myspringbootlogin.commont.Reuslt;
import com.ljy.myspringbootlogin.model.RoleModel;
import com.ljy.myspringbootlogin.model.UserModel;
import org.apache.ibatis.annotations.Param;import java.util.List;public interface IRoleService extends IService<RoleModel> {/*** 根据用户id查询角色信息*/List<RoleModel> getRoleByUserId(@Param("userId") Long userId);
}

 5、创建roleServieImpl

package com.ljy.myspringbootlogin.impl;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljy.myspringbootlogin.commont.Reuslt;
import com.ljy.myspringbootlogin.mapper.RoleMapper;
import com.ljy.myspringbootlogin.mapper.UserMapper;
import com.ljy.myspringbootlogin.model.RoleModel;
import com.ljy.myspringbootlogin.model.UserModel;
import com.ljy.myspringbootlogin.service.IRoleService;
import com.ljy.myspringbootlogin.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;import java.util.List;
import java.util.UUID;@Service
@Slf4j
public class RoleServiceImpl extends ServiceImpl<RoleMapper, RoleModel> implements IRoleService {@AutowiredRoleMapper roleMapper;@Overridepublic List<RoleModel> getRoleByUserId(Long userId) {List<RoleModel> roleByUserId = roleMapper.getRoleByUserId(userId);return roleByUserId;}
}

6、创建roleMapper

package com.ljy.myspringbootlogin.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ljy.myspringbootlogin.model.RoleModel;
import com.ljy.myspringbootlogin.model.UserModel;
import org.apache.ibatis.annotations.Mapper;import java.util.List;@Mapper
public interface RoleMapper extends BaseMapper<RoleModel> {List<RoleModel> getRoleByUserId(Long userId);
}

7、创建roleMapper.xml

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.ljy.myspringbootlogin.mapper.RoleMapper"><select id="getRoleByUserId" resultType="com.ljy.myspringbootlogin.model.RoleModel">select a.*from role aleft join user_role b on a.id=b.role_idwhere b.user_id=#{userId}</select></mapper>

8、创建menuService

上面创建了通过用户id查询角色的接口,那么现在创建通过角色id查询权限的接口。

package com.ljy.myspringbootlogin.service;import com.baomidou.mybatisplus.extension.service.IService;
import com.ljy.myspringbootlogin.model.MenuModel;
import com.ljy.myspringbootlogin.model.RoleModel;
import org.apache.ibatis.annotations.Param;import java.util.List;public interface IMenuService extends IService<MenuModel> {/*** 根据juese集合查询权限集合*/List<MenuModel> getMenuByRoleIds(@Param("roleIds") List<Long> roleIds);}

9、创建menuServiceImpl

package com.ljy.myspringbootlogin.impl;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljy.myspringbootlogin.mapper.MenuMapper;
import com.ljy.myspringbootlogin.model.MenuModel;
import com.ljy.myspringbootlogin.model.RoleModel;
import com.ljy.myspringbootlogin.service.IMenuService;
import com.ljy.myspringbootlogin.service.IRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
@Slf4j
public class MenuServiceImpl extends ServiceImpl<MenuMapper, MenuModel> implements IMenuService {@AutowiredMenuMapper menuMapper;@Overridepublic List<MenuModel> getMenuByRoleIds(List<Long> roleIds) {List<MenuModel> menuByRoleIds = menuMapper.getMenuByRoleIds(roleIds);return menuByRoleIds;}
}

10、创建menuMapper

package com.ljy.myspringbootlogin.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ljy.myspringbootlogin.model.MenuModel;
import com.ljy.myspringbootlogin.model.RoleModel;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;import java.util.List;@Mapper
public interface MenuMapper extends BaseMapper<MenuModel> {List<MenuModel> getMenuByRoleIds(@Param("roleIds") List<Long> roleIds);
}

11、创建menuMapper.xml

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.ljy.myspringbootlogin.mapper.MenuMapper"><select id="getMenuByRoleIds" resultType="com.ljy.myspringbootlogin.model.MenuModel">select a.*from menu aleft join role_menu b on a.id=b.menu_idwhere b.role_id in <foreach collection="roleIds" open="(" close=")" separator="," item="roleId">#{roleId}</foreach></select></mapper>

12、说明1

到此,通过用户id查询角色信息,通过角色id查询权限信息的两个接口都已经成功创建。接下来我们就需要在查询用户的接口处同时将角色信息和权限信息查询出来,并将角色信息放到userModel中的roleList中,将权限信息保存在userModel中的menuList中,注意:不管是roleList还是menuList,这两个都是我们自定义的属性,但是想要让springsecurity进行权限控制的话,我们必须将权限信息放到springsecurity中默认的权限属性中,也就是userModel中定义的private Collection<GrantedAuthority> authorities中,这个才是springsecurity提供的权限位置;。

13、修改查询用户信息的接口(springSecurityService.java)

package com.ljy.myspringbootlogin;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ljy.myspringbootlogin.mapper.UserMapper;
import com.ljy.myspringbootlogin.model.MenuModel;
import com.ljy.myspringbootlogin.model.RoleModel;
import com.ljy.myspringbootlogin.model.UserModel;
import com.ljy.myspringbootlogin.service.IMenuService;
import com.ljy.myspringbootlogin.service.IRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;import java.util.ArrayList;
import java.util.Collection;
import java.util.List;@Service
@Slf4j
public class springSecurityService implements UserDetailsService {@AutowiredUserMapper userMapper;@AutowiredIRoleService iRoleService;@AutowiredIMenuService iMenuService;@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {/*** 根据用户名查询用户*///通过账号查询用户System.out.println("进入!!!!");//UserModel user = userMapper.getList(username);System.out.println("user:"+user.toString());//如果没有查询到用户,则抛出异常if(user == null){throw new UsernameNotFoundException("账号或密码错误!");}//TODO 后续可以查角色和权限//1.根据用户id查询出角色System.out.println("开始查询角色");List<RoleModel> roleByUserId = iRoleService.getRoleByUserId(user.getId());user.setRoleList(roleByUserId);System.out.println("角色查询完成");List<Long> roleIdList = new ArrayList<>();for (RoleModel roleModel : roleByUserId){roleIdList.add(roleModel.getId());}//2.根据角色id查询出权限System.out.println("开始查询权限");List<MenuModel> menuByRoleIds = iMenuService.getMenuByRoleIds(roleIdList);System.out.println("权限查询完成");user.setMenuList(menuByRoleIds);System.out.println("完成");//3.将权限信息放到springSecurity中List<String> roleSecurity = new ArrayList<>();for (MenuModel model : menuByRoleIds){roleSecurity.add(model.getMenuTag());}Collection<GrantedAuthority> grantedAuthorities = AuthorityUtils.createAuthorityList(roleSecurity.toArray(new String[0]));user.setAuthorities(grantedAuthorities);System.out.println("Authorities:"+user.getAuthorities());return user;}
}

14、到此查询用户的角色信息和权限信息功能完成,并将用户的权限信息返回给了springsecurity。执行查询返回效果

15、结束语句

这样写有一个问题,我们通过前端访问我们的系统,进行登录成功,进入到系统中,开始操作,那么上面的写法会存在一个问题,就是我们每次访问一个接口的时候,都需要重新登录,重新查询权限等等,这样不是预期效果,我们的预期效果是登录成功之后,在规定时间内,访问拥有权限的模块时候,是不需要每次都重新登录的,那么如何实现?就需要用到jwt来实现了,具体实现逻辑以及步骤在下篇文章进行记录。因为我还没有做到那里 哈哈哈哈哈

这篇关于自己开发完整项目一、登录功能-03(使用springSecurity安全框架,查询用户角色权限)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1125290

相关文章

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

Spring WebFlux 与 WebClient 使用指南及最佳实践

《SpringWebFlux与WebClient使用指南及最佳实践》WebClient是SpringWebFlux模块提供的非阻塞、响应式HTTP客户端,基于ProjectReactor实现,... 目录Spring WebFlux 与 WebClient 使用指南1. WebClient 概述2. 核心依

Spring Boot @RestControllerAdvice全局异常处理最佳实践

《SpringBoot@RestControllerAdvice全局异常处理最佳实践》本文详解SpringBoot中通过@RestControllerAdvice实现全局异常处理,强调代码复用、统... 目录前言一、为什么要使用全局异常处理?二、核心注解解析1. @RestControllerAdvice2

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

Python内置函数之classmethod函数使用详解

《Python内置函数之classmethod函数使用详解》:本文主要介绍Python内置函数之classmethod函数使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 类方法定义与基本语法2. 类方法 vs 实例方法 vs 静态方法3. 核心特性与用法(1编程客

从入门到精通MySQL联合查询

《从入门到精通MySQL联合查询》:本文主要介绍从入门到精通MySQL联合查询,本文通过实例代码给大家介绍的非常详细,需要的朋友可以参考下... 目录摘要1. 多表联合查询时mysql内部原理2. 内连接3. 外连接4. 自连接5. 子查询6. 合并查询7. 插入查询结果摘要前面我们学习了数据库设计时要满

Spring事务传播机制最佳实践

《Spring事务传播机制最佳实践》Spring的事务传播机制为我们提供了优雅的解决方案,本文将带您深入理解这一机制,掌握不同场景下的最佳实践,感兴趣的朋友一起看看吧... 目录1. 什么是事务传播行为2. Spring支持的七种事务传播行为2.1 REQUIRED(默认)2.2 SUPPORTS2

怎样通过分析GC日志来定位Java进程的内存问题

《怎样通过分析GC日志来定位Java进程的内存问题》:本文主要介绍怎样通过分析GC日志来定位Java进程的内存问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、GC 日志基础配置1. 启用详细 GC 日志2. 不同收集器的日志格式二、关键指标与分析维度1.

Java进程异常故障定位及排查过程

《Java进程异常故障定位及排查过程》:本文主要介绍Java进程异常故障定位及排查过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、故障发现与初步判断1. 监控系统告警2. 日志初步分析二、核心排查工具与步骤1. 进程状态检查2. CPU 飙升问题3. 内存

Linux中压缩、网络传输与系统监控工具的使用完整指南

《Linux中压缩、网络传输与系统监控工具的使用完整指南》在Linux系统管理中,压缩与传输工具是数据备份和远程协作的桥梁,而系统监控工具则是保障服务器稳定运行的眼睛,下面小编就来和大家详细介绍一下它... 目录引言一、压缩与解压:数据存储与传输的优化核心1. zip/unzip:通用压缩格式的便捷操作2.