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

相关文章

解密SQL查询语句执行的过程

《解密SQL查询语句执行的过程》文章讲解了SQL语句的执行流程,涵盖解析、优化、执行三个核心阶段,并介绍执行计划查看方法EXPLAIN,同时提出性能优化技巧如合理使用索引、避免SELECT*、JOIN... 目录1. SQL语句的基本结构2. SQL语句的执行过程3. SQL语句的执行计划4. 常见的性能优

SpringBoot监控API请求耗时的6中解决解决方案

《SpringBoot监控API请求耗时的6中解决解决方案》本文介绍SpringBoot中记录API请求耗时的6种方案,包括手动埋点、AOP切面、拦截器、Filter、事件监听、Micrometer+... 目录1. 简介2.实战案例2.1 手动记录2.2 自定义AOP记录2.3 拦截器技术2.4 使用Fi

C++11右值引用与Lambda表达式的使用

《C++11右值引用与Lambda表达式的使用》C++11引入右值引用,实现移动语义提升性能,支持资源转移与完美转发;同时引入Lambda表达式,简化匿名函数定义,通过捕获列表和参数列表灵活处理变量... 目录C++11新特性右值引用和移动语义左值 / 右值常见的左值和右值移动语义移动构造函数移动复制运算符

最新Spring Security的基于内存用户认证方式

《最新SpringSecurity的基于内存用户认证方式》本文讲解SpringSecurity内存认证配置,适用于开发、测试等场景,通过代码创建用户及权限管理,支持密码加密,虽简单但不持久化,生产环... 目录1. 前言2. 因何选择内存认证?3. 基础配置实战❶ 创建Spring Security配置文件

Python对接支付宝支付之使用AliPay实现的详细操作指南

《Python对接支付宝支付之使用AliPay实现的详细操作指南》支付宝没有提供PythonSDK,但是强大的github就有提供python-alipay-sdk,封装里很多复杂操作,使用这个我们就... 目录一、引言二、准备工作2.1 支付宝开放平台入驻与应用创建2.2 密钥生成与配置2.3 安装ali

Spring Security 单点登录与自动登录机制的实现原理

《SpringSecurity单点登录与自动登录机制的实现原理》本文探讨SpringSecurity实现单点登录(SSO)与自动登录机制,涵盖JWT跨系统认证、RememberMe持久化Token... 目录一、核心概念解析1.1 单点登录(SSO)1.2 自动登录(Remember Me)二、代码分析三、

C#中lock关键字的使用小结

《C#中lock关键字的使用小结》在C#中,lock关键字用于确保当一个线程位于给定实例的代码块中时,其他线程无法访问同一实例的该代码块,下面就来介绍一下lock关键字的使用... 目录使用方式工作原理注意事项示例代码为什么不能lock值类型在C#中,lock关键字用于确保当一个线程位于给定实例的代码块中时

PyQt5 GUI 开发的基础知识

《PyQt5GUI开发的基础知识》Qt是一个跨平台的C++图形用户界面开发框架,支持GUI和非GUI程序开发,本文介绍了使用PyQt5进行界面开发的基础知识,包括创建简单窗口、常用控件、窗口属性设... 目录简介第一个PyQt程序最常用的三个功能模块控件QPushButton(按钮)控件QLable(纯文本

MySQL 强制使用特定索引的操作

《MySQL强制使用特定索引的操作》MySQL可通过FORCEINDEX、USEINDEX等语法强制查询使用特定索引,但优化器可能不采纳,需结合EXPLAIN分析执行计划,避免性能下降,注意版本差异... 目录1. 使用FORCE INDEX语法2. 使用USE INDEX语法3. 使用IGNORE IND

C# $字符串插值的使用

《C#$字符串插值的使用》本文介绍了C#中的字符串插值功能,详细介绍了使用$符号的实现方式,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧... 目录$ 字符使用方式创建内插字符串包含不同的数据类型控制内插表达式的格式控制内插表达式的对齐方式内插表达式中使用转义序列内插表达式中使用