自己开发完整项目一、登录功能-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

相关文章

Java线程池核心参数原理及使用指南

《Java线程池核心参数原理及使用指南》本文详细介绍了Java线程池的基本概念、核心类、核心参数、工作原理、常见类型以及最佳实践,通过理解每个参数的含义和工作原理,可以更好地配置线程池,提高系统性能,... 目录一、线程池概述1.1 什么是线程池1.2 线程池的优势二、线程池核心类三、ThreadPoolE

VSCode开发中有哪些好用的插件和快捷键

《VSCode开发中有哪些好用的插件和快捷键》作为全球最受欢迎的编程工具,VSCode的快捷键体系是提升开发效率的核心密码,:本文主要介绍VSCode开发中有哪些好用的插件和快捷键的相关资料,文中... 目录前言1、vscode插件1.1 Live-server1.2 Auto Rename Tag1.3

Mysql中RelayLog中继日志的使用

《Mysql中RelayLog中继日志的使用》MySQLRelayLog中继日志是主从复制架构中的核心组件,负责将从主库获取的Binlog事件暂存并应用到从库,本文就来详细的介绍一下RelayLog中... 目录一、什么是 Relay Log(中继日志)二、Relay Log 的工作流程三、Relay Lo

使用Redis实现会话管理的示例代码

《使用Redis实现会话管理的示例代码》文章介绍了如何使用Redis实现会话管理,包括会话的创建、读取、更新和删除操作,通过设置会话超时时间并重置,可以确保会话在用户持续活动期间不会过期,此外,展示了... 目录1. 会话管理的基本概念2. 使用Redis实现会话管理2.1 引入依赖2.2 会话管理基本操作

Springboot请求和响应相关注解及使用场景分析

《Springboot请求和响应相关注解及使用场景分析》本文介绍了SpringBoot中用于处理HTTP请求和构建HTTP响应的常用注解,包括@RequestMapping、@RequestParam... 目录1. 请求处理注解@RequestMapping@GetMapping, @PostMappin

Java调用DeepSeek API的8个高频坑与解决方法

《Java调用DeepSeekAPI的8个高频坑与解决方法》现在大模型开发特别火,DeepSeek因为中文理解好、反应快、还便宜,不少Java开发者都用它,本文整理了最常踩的8个坑,希望对... 目录引言一、坑 1:Token 过期未处理,鉴权异常引发服务中断问题本质典型错误代码解决方案:实现 Token

springboot3.x使用@NacosValue无法获取配置信息的解决过程

《springboot3.x使用@NacosValue无法获取配置信息的解决过程》在SpringBoot3.x中升级Nacos依赖后,使用@NacosValue无法动态获取配置,通过引入SpringC... 目录一、python问题描述二、解决方案总结一、问题描述springboot从2android.x

SpringBoot整合AOP及使用案例实战

《SpringBoot整合AOP及使用案例实战》本文详细介绍了SpringAOP中的切入点表达式,重点讲解了execution表达式的语法和用法,通过案例实战,展示了AOP的基本使用、结合自定义注解以... 目录一、 引入依赖二、切入点表达式详解三、案例实战1. AOP基本使用2. AOP结合自定义注解3.

Python中Request的安装以及简单的使用方法图文教程

《Python中Request的安装以及简单的使用方法图文教程》python里的request库经常被用于进行网络爬虫,想要学习网络爬虫的同学必须得安装request这个第三方库,:本文主要介绍P... 目录1.Requests 安装cmd 窗口安装为pycharm安装在pycharm设置中为项目安装req

Qt实现对Word网页的读取功能

《Qt实现对Word网页的读取功能》文章介绍了几种在Qt中实现Word文档(.docx/.doc)读写功能的方法,包括基于QAxObject的COM接口调用、DOCX模板替换及跨平台解决方案,重点讨论... 目录1. 核心实现方式2. 基于QAxObject的COM接口调用(Windows专用)2.1 环境