Maven仓库:
dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<!-- 代码生成器 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.2</version>
</dependency>
<!-- 引擎模板-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
<!-- get set-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
五个模型类,User(用户),Role(角色),UserRole(中间表),Permission(权限表),RolePermission(用户权限中间表)
package com.example.rbac.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* <p>
* �û���
* </p>
*
* @author mgk
* @since 2020-07-16
*/
@Data
@EqualsAndHashCode(callSuper = false)
public class User implements Serializable {
private static final long serialVersionUID=1L;
@TableId(value = "u_id", type = IdType.AUTO)
private Integer uId;
private String name;
@TableField("passWord")
private String passWord;
private Integer status;
@TableField("create_Time")
private LocalDateTime createTime;
@TableField("update_Time")
private LocalDateTime updateTime;
}
package com.example.rbac.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* <p>
* ��ɫ��
* </p>
*
* @author mgk
* @since 2020-07-16
*/
@Data
@EqualsAndHashCode(callSuper = false)
public class Role implements Serializable {
private static final long serialVersionUID=1L;
@TableId(value = "role_id", type = IdType.AUTO)
private Integer roleId;
private String name;
private Integer status;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
package com.example.rbac.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* <p>
*
* </p>
*
* @author mgk
* @since 2020-07-16
*/
@Data
@EqualsAndHashCode(callSuper = false)
public class UserRole implements Serializable {
private static final long serialVersionUID=1L;
@TableId(value = "u_r_id", type = IdType.AUTO)
private Integer uRId;
private Integer uId;
private Integer roleId;
}
package com.example.rbac.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* <p>
* Ȩ�ޱ�
* </p>
*
* @author mgk
* @since 2020-07-16
*/
@Data
@EqualsAndHashCode(callSuper = false)
public class Permission implements Serializable {
private static final long serialVersionUID=1L;
@TableId(value = "permission_id", type = IdType.AUTO)
private Integer permissionId;
private String title;
private String action;
private Integer status;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
package com.example.rbac.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* <p>
*
* </p>
*
* @author mgk
* @since 2020-07-16
*/
@Data
@EqualsAndHashCode(callSuper = false)
public class RolePermission implements Serializable {
private static final long serialVersionUID=1L;
@TableId(value = "r_p_id", type = IdType.AUTO)
private Integer rPId;
private Integer roleId;
private Integer permissionId;
private LocalDateTime createTime;
}
工具包:Result(返回类),ResuleCode(枚举类),自动生成代码类(CodeGenerator)
package com.example.util;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
public class CodeGenerator {
/**
* <p>
* 读取控制台内容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("mgk");
gc.setOpen(false);
// gc.setSwagger2(true); 实体属性 Swagger2 注解
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://127.0.0.1:3306/mgk?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(scanner("模块名"));
pc.setParent("com.example");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 公共父类
//strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
// 写于父类中的公共字段
//strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
//mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
package com.example.util;
import java.util.HashMap;
import java.util.Map;
public class Result {
private ResultCode code;//响应码
private int status;
private String message;//响应信息
private Object body;//相应对象
private Result() {
this.code = ResultCode.SUCCESS;
this.status=this.code.getCode();
this.message=this.code.getMessage();
this.body = null;
}
private Result(Object body,ResultCode code) {
this.code = code;
this.status=this.code.getCode();
this.message=this.code.getMessage();
this.body = body;
}
public static Result createFail(){
Result result = new Result();
result.status=ResultCode.FAIL.getCode();
result.message=ResultCode.FAIL.getMessage();
return result;
}
public static Result createResult(Object body,ResultCode code){
return new Result(body, code);
}
public static Result createSuccessful(){
return new Result();
}
public Map<String,Object> toJsonMap(){
Map<String,Object> map = new HashMap<>();
map.put("data",this.body);
map.put("message",this.message);
map.put("status",this.status);
return map;
}
}
package com.example.util;
public enum ResultCode {
SUCCESS(1001,"成功"),
FAIL(1002,"失败"),
WRONGPASSWORD(1101,"密码错误"),
USERNOTEXIST(1102,"用户不存在"),
USEREXIST(1103,"用户已存在"),
USERNAMEERROR(1104,"用户名称错误"),
USERNOTLOGIN(1105,"用户未登陆"),
ROLEEXIST(1201,"权限已存在"),
ROLEEXISTINSUFFICIENT (1202,"无访问操作权限");
ResultCode(int code,String message) {
this.message = message;
this.code = code;
}
private int code;
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
Service层两个类
package com.example.rbac.service;
import com.example.rbac.entity.Role;
import com.example.rbac.entity.User;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.Set;
/**
* <p>
* �û��� 服务类
* </p>
*
* @author mgk
* @since 2020-07-16
*/
public interface IUserService extends IService<User> {
Set<Role> getUserRoles(Integer userId);
}
package com.example.rbac.service.impl;
import com.example.rbac.entity.Role;
import com.example.rbac.entity.User;
import com.example.rbac.mapper.UserMapper;
import com.example.rbac.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Set;
/**
* <p>
* �û��� 服务实现类
* </p>
*
* @author mgk
* @since 2020-07-16
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
@Autowired(required = true)
private UserMapper userMapper;
@Override
public Set<Role> getUserRoles(Integer userId) {
return userMapper.getUserRoles(userId);
}
}
package com.example.rbac.service.impl;
import com.example.rbac.entity.Role;
import com.example.rbac.mapper.RoleMapper;
import com.example.rbac.mapper.UserMapper;
import com.example.rbac.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import java.util.Set;
/**
* <p>
* ��ɫ�� 服务实现类
* </p>
*
* @author mgk
* @since 2020-07-16
*/
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
}
package com.example.rbac.service;
import com.example.rbac.entity.Role;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* ��ɫ�� 服务类
* </p>
*
* @author mgk
* @since 2020-07-16
*/
public interface IRoleService extends IService<Role> {
}
Mapper层
package com.example.rbac.mapper;
import com.example.rbac.entity.Role;
import com.example.rbac.entity.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Service;
import java.util.Set;
/**
* <p>
* �û��� Mapper 接口
* </p>
*
* @author mgk
* @since 2020-07-16
*/
public interface UserMapper extends BaseMapper<User> {
@Select("select * from role where role_id in(select role_id from user_role where u_id = #{userId})")
Set<Role> getUserRoles(Integer userId);
}
package com.example.rbac.mapper;
import com.example.rbac.entity.Role;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* ��ɫ�� Mapper 接口
* </p>
*
* @author mgk
* @since 2020-07-16
*/
public interface RoleMapper extends BaseMapper<Role> {
}
Controller层
package com.example.rbac.controller;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.config.CustomRealm;
import com.example.rbac.entity.User;
import com.example.rbac.service.IUserService;
import com.example.rbac.service.impl.UserServiceImpl;
import com.example.util.Result;
import com.example.util.ResultCode;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
/**
* <p>
* �û��� 前端控制器
* </p>
*
* @author mgk
* @since 2020-07-16
*/
@RestController
@RequestMapping("/rbac")
public class UserController {
@Autowired(required = true)
private IUserService userService;
@Autowired
private CustomRealm myShiroRealm;
@PostMapping("/login")
public Map<String, Object> login(User user){
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
user.getName(),
user.getPassWord()
);
try {
//进行验证,这里可以捕获异常,然后返回对应信息
subject.login(usernamePasswordToken);
} catch (AuthenticationException e) {
e.printStackTrace();
Result fail = Result.createResult(null, ResultCode.WRONGPASSWORD);
return fail.toJsonMap();
} catch (AuthorizationException e) {
e.printStackTrace();
}
return Result.createResult(null, ResultCode.SUCCESS).toJsonMap();
}
/**
* 注册用户
* @return
*/
@PostMapping("/user")
public Map<String, Object> registerUser(User user){
QueryWrapper<User> wrapper = new QueryWrapper();
wrapper.eq("name",user.getName());
User one = userService.getOne(wrapper);
if(!(one==null)){
Result fail = Result.createResult(null, ResultCode.USEREXIST);
return fail.toJsonMap();
}
if(StringUtils.isEmpty(user.getName())){
Result fail = Result.createResult(null, ResultCode.USERNAMEERROR);
return fail.toJsonMap();
}
userService.save(user);
return Result.createSuccessful().toJsonMap();
}
}
package com.example.rbac.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.rbac.entity.Role;
import com.example.rbac.entity.User;
import com.example.rbac.service.IRoleService;
import com.example.util.Result;
import com.example.util.ResultCode;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
/**
* <p>
* ��ɫ�� 前端控制器
* </p>
*
* @author mgk
* @since 2020-07-16
*/
@RestController
@RequestMapping("/rbac")
public class RoleController {
@Autowired(required = true)
private IRoleService roleService;
/**
* 添加角色
* @param role
* @return
*/
@PostMapping("/role")
public Map<String,Object> addRole(Role role){
Subject subject = SecurityUtils.getSubject();
if(subject.hasRole("viewManager")){
System.out.println("有viewManager权限");
}else {
System.out.println("无viewManager权限");
}
QueryWrapper<Role> wrapper = new QueryWrapper();
wrapper.eq("name",role.getName());
Role one = roleService.getOne(wrapper);
if(one!=null){
Result fail = Result.createResult(null, ResultCode.ROLEEXIST);
return fail.toJsonMap();
}
if(StringUtils.isEmpty(role.getName())){
Result fail = Result.createResult(null, ResultCode.FAIL);
return fail.toJsonMap();
}
roleService.save(role);
Result fail = Result.createResult(null, ResultCode.SUCCESS);
return fail.toJsonMap();
}
}
主程序入口:
package com.example;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.example.rbac.mapper")
public class RbacApplication {
public static void main(String[] args) {
SpringApplication.run(RbacApplication.class, args);
}
}
sql数据:
INSERT INTO `user`(`u_id`, `name`, `passWord`, `status`, `create_Time`, `update_Time`) VALUES (2, 'mgk', '123456', 1, '2020-02-26 17:23:30', '2020-02-26 17:23:30');
INSERT INTO `user`(`u_id`, `name`, `passWord`, `status`, `create_Time`, `update_Time`) VALUES (7, 'admin', '123456', NULL, '2020-07-17 16:10:23', '2020-07-17 16:10:23');
INSERT INTO `user`(`u_id`, `name`, `passWord`, `status`, `create_Time`, `update_Time`) VALUES (8, '\"\"', '123456', NULL, '2020-07-17 16:33:19', '2020-07-17 16:33:19');
INSERT INTO `role`(`role_id`, `name`, `status`, `create_time`, `update_time`) VALUES (1, 'viewManager', NULL, '2020-07-20 10:42:36', '2020-07-20 10:42:36');
INSERT INTO `role`(`role_id`, `name`, `status`, `create_time`, `update_time`) VALUES (2, 'roleAddManager', NULL, '2020-07-20 10:43:05', '2020-07-20 10:43:05');
INSERT INTO `role`(`role_id`, `name`, `status`, `create_time`, `update_time`) VALUES (3, 'roleDelManager', NULL, '2020-07-20 10:43:13', '2020-07-20 10:43:13');
INSERT INTO `role`(`role_id`, `name`, `status`, `create_time`, `update_time`) VALUES (4, 'roleEditManager', NULL, '2020-07-20 10:43:20', '2020-07-20 10:43:20');
INSERT INTO `user_role`(`u_r_id`, `u_id`, `role_id`) VALUES (1, 7, 1);
INSERT INTO `user_role`(`u_r_id`, `u_id`, `role_id`) VALUES (2, 7, 2);
INSERT INTO `user_role`(`u_r_id`, `u_id`, `role_id`) VALUES (3, 7, 3);
INSERT INTO `user_role`(`u_r_id`, `u_id`, `role_id`) VALUES (4, 7, 4);
SQL结构:
drop table if exists user;
/*==============================================================*/
/* Table: user */
/*==============================================================*/
create table user
(
u_id int not null auto_increment,
name varchar(32),
passWord varchar(32),
status tinyint,
create_Time timestamp default CURRENT_TIMESTAMP,
update_Time timestamp default CURRENT_TIMESTAMP,
primary key (u_id)
);
alter table user comment '用户表';
drop table if exists role;
/*==============================================================*/
/* Table: role */
/*==============================================================*/
create table role
(
role_id int not null auto_increment,
name varchar(32),
status tinyint,
create_time timestamp default CURRENT_TIMESTAMP,
update_time timestamp default CURRENT_TIMESTAMP,
primary key (role_id)
);
alter table role comment '角色表';
drop table if exists user_role;
/*==============================================================*/
/* Table: user_role */
/*==============================================================*/
create table user_role
(
u_r_id int not null auto_increment,
u_id int,
role_id int,
primary key (u_r_id)
);
alter table user_role add constraint FK_Reference_1 foreign key (u_id)
references user (u_id) on delete restrict on update restrict;
alter table user_role add constraint FK_Reference_2 foreign key (role_id)
references role (role_id) on delete restrict on update restrict;
drop table if exists permission;
/*==============================================================*/
/* Table: permission */
/*==============================================================*/
create table permission
(
permission_id int not null auto_increment,
title varchar(50),
action varchar(50),
status tinyint,
create_time timestamp default CURRENT_TIMESTAMP,
update_time timestamp default CURRENT_TIMESTAMP,
primary key (permission_id)
);
alter table permission comment '权限表';
drop table if exists role_permission;
/*==============================================================*/
/* Table: role_permission */
/*==============================================================*/
create table role_permission
(
r_p_id int not null auto_increment,
role_id int,
permission_id int,
create_time timestamp,
primary key (r_p_id)
);
alter table role_permission add constraint FK_Reference_3 foreign key (role_id)
references role (role_id) on delete restrict on update restrict;
表关系:
Shiro类,ShiroConfig(配置类)CustomReaml(自定义权限验证)
package com.example.config;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.rbac.entity.Role;
import com.example.rbac.entity.User;
import com.example.rbac.entity.UserRole;
import com.example.rbac.service.IUserRoleService;
import com.example.rbac.service.IUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import java.security.Permissions;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class CustomRealm extends AuthorizingRealm {
@Autowired
private IUserService userService;
@Autowired
private IUserRoleService userRoleService;
@Override
public AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//获取登录用户名
String name = (String) principalCollection.getPrimaryPrincipal();
//根据用户名去数据库查询用户信息
QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
userQueryWrapper.eq("name",name);
User user = userService.getOne(userQueryWrapper);
Set<Role> userRoles = userService.getUserRoles(user.getUId());
//添加角色和权限
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
// //角色关联表
for (Role role : userRoles) {
//添加角色
simpleAuthorizationInfo.addRole(role.getName());
//添加权限
// for (Permissions permissions : role.getPermissions()) {
// simpleAuthorizationInfo.addStringPermission(permissions.getPermissionsName());
// }
}
return simpleAuthorizationInfo;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//加这一步的目的是在Post请求的时候会先进认证,然后在到请求
if (authenticationToken.getPrincipal() == null) {
return null;
}
//获取用户信息
String name = authenticationToken.getPrincipal().toString();
QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
userQueryWrapper.eq("name",name);
User user = userService.getOne(userQueryWrapper);
if (user == null) {
//这里返回后会报出对应异常
return null;
} else {
//这里验证authenticationToken和simpleAuthenticationInfo的信息
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(name, user.getPassWord().toString(), getName());
return simpleAuthenticationInfo;
}
}
}
package com.example.config;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class ShiroConfig {
/**
* 解决和Spring注解一起使用使,导致Shiro注解使用时不能被映射
* @return
*/
// @Bean
// @ConditionalOnMissingBean
// public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
// DefaultAdvisorAutoProxyCreator defaultAAP = new DefaultAdvisorAutoProxyCreator();
// defaultAAP.setProxyTargetClass(true);
// return defaultAAP;
// }
//将自己的验证方式加入容器
@Bean
public CustomRealm myShiroRealm() {
CustomRealm customRealm = new CustomRealm();
return customRealm;
}
//权限管理,配置主要是Realm的管理认证
@Bean
public SecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(myShiroRealm());
return securityManager;
}
//Filter工厂,设置对应的过滤条件和跳转条件
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
Map<String, String> map = new HashMap<>();
//登出
map.put("/logout", "logout");
//对所有用户认证
map.put("/**", "authc");
//登录
shiroFilterFactoryBean.setLoginUrl("/rbac/login");
//首页
shiroFilterFactoryBean.setSuccessUrl("/index");
//错误页面,认证不通过跳转
shiroFilterFactoryBean.setUnauthorizedUrl("/error");
shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
return shiroFilterFactoryBean;
}
// /**
// * 支持注解方式需要加入该Bean
// * @param securityManager
// * @return
// */
// @Bean
// public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
// AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
// authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
// return authorizationAttributeSourceAdvisor;
// }
}
配置文件:
server.port=9999
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mgk?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&useTimezone=true
spring.datasource.username=root
spring.datasource.password=123456
手码不易点个赞再走吧谢谢啦