本文主要是介绍自己开发完整项目一、登录功能-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安全框架,查询用户角色权限)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!