自己开发完整项目一、登录功能-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中流式并行操作parallelStream的原理和使用方法

《Java中流式并行操作parallelStream的原理和使用方法》本文详细介绍了Java中的并行流(parallelStream)的原理、正确使用方法以及在实际业务中的应用案例,并指出在使用并行流... 目录Java中流式并行操作parallelStream0. 问题的产生1. 什么是parallelS

Linux join命令的使用及说明

《Linuxjoin命令的使用及说明》`join`命令用于在Linux中按字段将两个文件进行连接,类似于SQL的JOIN,它需要两个文件按用于匹配的字段排序,并且第一个文件的换行符必须是LF,`jo... 目录一. 基本语法二. 数据准备三. 指定文件的连接key四.-a输出指定文件的所有行五.-o指定输出

Java中Redisson 的原理深度解析

《Java中Redisson的原理深度解析》Redisson是一个高性能的Redis客户端,它通过将Redis数据结构映射为Java对象和分布式对象,实现了在Java应用中方便地使用Redis,本文... 目录前言一、核心设计理念二、核心架构与通信层1. 基于 Netty 的异步非阻塞通信2. 编解码器三、

Linux jq命令的使用解读

《Linuxjq命令的使用解读》jq是一个强大的命令行工具,用于处理JSON数据,它可以用来查看、过滤、修改、格式化JSON数据,通过使用各种选项和过滤器,可以实现复杂的JSON处理任务... 目录一. 简介二. 选项2.1.2.2-c2.3-r2.4-R三. 字段提取3.1 普通字段3.2 数组字段四.

Linux kill正在执行的后台任务 kill进程组使用详解

《Linuxkill正在执行的后台任务kill进程组使用详解》文章介绍了两个脚本的功能和区别,以及执行这些脚本时遇到的进程管理问题,通过查看进程树、使用`kill`命令和`lsof`命令,分析了子... 目录零. 用到的命令一. 待执行的脚本二. 执行含子进程的脚本,并kill2.1 进程查看2.2 遇到的

SpringBoot基于注解实现数据库字段回填的完整方案

《SpringBoot基于注解实现数据库字段回填的完整方案》这篇文章主要为大家详细介绍了SpringBoot如何基于注解实现数据库字段回填的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以了解... 目录数据库表pom.XMLRelationFieldRelationFieldMapping基础的一些代

一篇文章彻底搞懂macOS如何决定java环境

《一篇文章彻底搞懂macOS如何决定java环境》MacOS作为一个功能强大的操作系统,为开发者提供了丰富的开发工具和框架,下面:本文主要介绍macOS如何决定java环境的相关资料,文中通过代码... 目录方法一:使用 which命令方法二:使用 Java_home工具(Apple 官方推荐)那问题来了,

Java HashMap的底层实现原理深度解析

《JavaHashMap的底层实现原理深度解析》HashMap基于数组+链表+红黑树结构,通过哈希算法和扩容机制优化性能,负载因子与树化阈值平衡效率,是Java开发必备的高效数据结构,本文给大家介绍... 目录一、概述:HashMap的宏观结构二、核心数据结构解析1. 数组(桶数组)2. 链表节点(Node

Java AOP面向切面编程的概念和实现方式

《JavaAOP面向切面编程的概念和实现方式》AOP是面向切面编程,通过动态代理将横切关注点(如日志、事务)与核心业务逻辑分离,提升代码复用性和可维护性,本文给大家介绍JavaAOP面向切面编程的概... 目录一、AOP 是什么?二、AOP 的核心概念与实现方式核心概念实现方式三、Spring AOP 的关

详解SpringBoot+Ehcache使用示例

《详解SpringBoot+Ehcache使用示例》本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录摘要概念内存与磁盘持久化存储:配置灵活性:编码示例引入依赖:配置ehcache.XML文件:配置