
- <dependencies>
- <dependency>
- <groupId>org.apache.shirogroupId>
- <artifactId>shiro-spring-boot-starterartifactId>
- <version>1.7.0version>
- dependency>
- <dependency>
- <groupId>com.spring4allgroupId>
- <artifactId>swagger-spring-boot-starterartifactId>
- <version>1.9.1.RELEASEversion>
- dependency>
- <dependency>
- <groupId>com.github.xiaoymingroupId>
- <artifactId>swagger-bootstrap-uiartifactId>
- <version>1.7.8version>
- dependency>
-
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-webartifactId>
- dependency>
-
- <dependency>
- <groupId>mysqlgroupId>
- <artifactId>mysql-connector-javaartifactId>
- dependency>
-
- <dependency>
- <groupId>org.projectlombokgroupId>
- <artifactId>lombokartifactId>
- <optional>trueoptional>
- dependency>
-
- <dependency>
- <groupId>com.baomidougroupId>
- <artifactId>mybatis-plus-boot-starterartifactId>
- <version>3.5.1version>
- dependency>
-
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-testartifactId>
- <scope>testscope>
- dependency>
- dependencies>
- #配置数据源
- spring.datasource.url=jdbc:mysql://localhost:3306/shiro?serverTimezone=Asia/Shanghai
- spring.datasource.username=root
- spring.datasource.password=123456
- spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
-
- #端口号
- server.port=8081
-
- #sql日志 属于mybatis-plus的
- mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
-
-
- #如果你的springboot 是 2.6.x上的版本得加 2.3.12不需要
- #spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER
- package com.wzh.entity;
-
- import io.swagger.annotations.ApiModelProperty;
- import lombok.AllArgsConstructor;
- import lombok.Data;
- import lombok.NoArgsConstructor;
- import org.springframework.boot.context.properties.ConfigurationProperties;
- import org.springframework.stereotype.Component;
-
- /**
- * @ProjectName: springboot
- * @Package: com.wzh.entity
- * @ClassName: ShiroProperties
- * @Author: 王振华
- * @Description:
- * @Date: 2022/8/6 17:40
- * @Version: 1.0
- */
- @Data
- @Component
- @ConfigurationProperties(prefix = "shiro")//使用配置文件的内容
- public class ShiroProperties {
-
- private String hashAlgorithmName="md5";
-
- private Integer hashIterations=2;
-
- private String loginUrl;
-
- private String unauthorizedUrl;
-
- private String [] anonUrls;
-
- private String logoutUrl;
-
- private String [] authcUrls;
- }
- #shiro的配置
- shiro.hash-algorithm-name:MD5
- shiro.hash-iterations=1024
- shiro.login-url=/index.html
- shiro.unauthorized-url=/unauthorized.html
- shiro.anon-urls[0]=/login/*
- shiro.anon-urls[1]=/doc.html
- shiro.anon-urls[2]=/swagger-ui.html
- shiro.anon-urls[3]=/webjars/**
- shiro.anon-urls[4]=/swagger/**
- shiro.anon-urls[5]=/swagger-resources/**
- shiro.anon-urls[6]=/v2/**
- shiro.anon-urls[7]=/static/**
- shiro.logout-url=/login/logout*
- shiro.authc-urls[0]=/**
- package com.wzh.config;
-
- import com.wzh.entity.ShiroProperties;
- import com.wzh.filter.LoginFilter;
- import com.wzh.realm.UserRealm;
- import org.apache.shiro.authc.credential.CredentialsMatcher;
- import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
- import org.apache.shiro.mgt.SecurityManager;
- import org.apache.shiro.realm.Realm;
- import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
- import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.web.servlet.FilterRegistrationBean;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.web.filter.DelegatingFilterProxy;
-
- import javax.servlet.Filter;
- import java.util.HashMap;
- import java.util.Map;
-
- /**
- * @ProjectName: springboot
- * @Package: com.wzh.config
- * @ClassName: ShiroAutoConfiguration
- * @Author: 王振华
- * @Description: shiro配置类
- * @Date: 2022/8/6 17:37
- * @Version: 1.0
- */
- @Configuration
- public class ShiroAutoConfiguration {
- @Autowired
- private ShiroProperties shiroProperties;
-
- /**
- * 声明安全管理器
- * @return
- */
- @Bean
- public DefaultWebSecurityManager securityManager(){
- DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
- securityManager.setRealm(realm());
- return securityManager;
- }
-
- /**
- * 创建realm
- */
- @Bean
- public Realm realm(){
- UserRealm myRealm=new UserRealm();
- //注入凭证匹配器
- myRealm.setCredentialsMatcher(credentialsMatcher());
- return myRealm;
- }
-
- /**
- * 创建凭证匹配器
- */
- @Bean
- public HashedCredentialsMatcher credentialsMatcher(){
- HashedCredentialsMatcher credentialsMatcher=new HashedCredentialsMatcher();
- credentialsMatcher.setHashAlgorithmName(shiroProperties.getHashAlgorithmName());
- credentialsMatcher.setHashIterations(shiroProperties.getHashIterations());
- return credentialsMatcher;
- }
-
- /**
- * 配置过滤器 Shiro 的Web过滤器 必须和下面的注册过滤器名称一样
- */
- @Bean(value = "shiroFilter")
- public ShiroFilterFactoryBean filterFactoryBean(){
- ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
- //注入安全管理器
- factoryBean.setSecurityManager(securityManager());
- //注入登陆页面
- factoryBean.setLoginUrl(shiroProperties.getLoginUrl());
- //注入未授权的页面地址
- factoryBean.setUnauthorizedUrl(shiroProperties.getUnauthorizedUrl());
-
- //注入过滤器
- Map
filterChainDefinition=new HashMap<>(); - //注入放行地址
- if(shiroProperties.getAnonUrls()!=null&&shiroProperties.getAnonUrls().length>0){
- String[] anonUrls = shiroProperties.getAnonUrls();
- for (String anonUrl : anonUrls) {
- filterChainDefinition.put(anonUrl,"anon");
- }
- }
- //注入登出的地址
- if(shiroProperties.getLogoutUrl()!=null){
- filterChainDefinition.put(shiroProperties.getLogoutUrl(),"logout");
- }
-
- //注入拦截的地址
- String[] authcUrls = shiroProperties.getAuthcUrls();
- if(authcUrls!=null&&authcUrls.length>0){
- for (String authcUrl : authcUrls) {
- filterChainDefinition.put(authcUrl,"authc");
- }
- }
- factoryBean.setFilterChainDefinitionMap(filterChainDefinition);
-
-
- //设置自定义认证过滤器
- HashMap
filterMap=new HashMap(); - filterMap.put("authc",new LoginFilter());
- factoryBean.setFilters(filterMap);
-
- return factoryBean;
- }
-
- /**
- * 注册过滤器
- */
- @Bean //注册filter
- public FilterRegistrationBean
filterRegistrationBean(){ - FilterRegistrationBean
filterRegistrationBean=new FilterRegistrationBean<>(); - filterRegistrationBean.setName("shiroFilter");
- filterRegistrationBean.setFilter(new DelegatingFilterProxy());
- filterRegistrationBean.addUrlPatterns("/*");
- return filterRegistrationBean;
- }
-
- }
config:
ShiroAutoConfigurtion:就上面的
SwaggerConfig:
- package com.wzh.config;
-
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import springfox.documentation.builders.RequestHandlerSelectors;
- import springfox.documentation.service.ApiInfo;
- import springfox.documentation.service.Contact;
- import springfox.documentation.service.VendorExtension;
- import springfox.documentation.spi.DocumentationType;
- import springfox.documentation.spring.web.plugins.Docket;
-
- import java.util.ArrayList;
-
- /**
- * @ProjectName: springboot-shiro-swagger
- * @Package: com.wzh.config
- * @ClassName: SwaggerConfig
- * @Author: 王振华
- * @Description:
- * @Date: 2022/8/5 19:54
- * @Version: 1.0
- */
- @Configuration
- public class SwaggerConfig {
- @Bean //swagger中所有的功能都封装在Docket类中。
- public Docket docket(){
- Docket docket = new Docket(DocumentationType.SWAGGER_2)
- .apiInfo(apiInfo()) //设置api文档信息
- .select()
- .apis(RequestHandlerSelectors.basePackage("com.wzh.controller")) //指定为哪些包下的类生成接口文档
- .build()
- ;
-
- return docket;
- }
-
- //定义自己接口文档信息
- private ApiInfo apiInfo(){
- Contact DEFAULT_CONTACT = new Contact("王振华", "http://www/baidu.com", "13234@qq.com");
- ApiInfo apiInfo = new ApiInfo("在线文档", "世界上最牛的一个文档", "V1.0", "http://www/jd.com",
- DEFAULT_CONTACT, "xx科技有限公司", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList
()); - return apiInfo;
- }
-
- }
controller:
LoginController:
- package com.wzh.controller;
-
- import com.wzh.util.CommonResult;
- import io.swagger.annotations.Api;
- import io.swagger.annotations.ApiImplicitParam;
- import io.swagger.annotations.ApiImplicitParams;
- import io.swagger.annotations.ApiOperation;
- import org.apache.shiro.SecurityUtils;
- import org.apache.shiro.authc.UsernamePasswordToken;
- import org.apache.shiro.subject.Subject;
- import org.springframework.web.bind.annotation.*;
-
- /**
- * @ProjectName: springboot-shiro-swagger
- * @Package: com.wzh.controller
- * @ClassName: LoginController
- * @Author: 王振华
- * @Description:
- * @Date: 2022/8/5 17:51
- * @Version: 1.0
- */
- @RestController
- @RequestMapping("/login")
- @Api(tags = "登录的接口")
- public class LoginController {
-
- @GetMapping("/toLogin")
- @ApiOperation(value = "登录方法")
- @ApiImplicitParams(
- {
- @ApiImplicitParam(value = "用户名",name = "username"),
- @ApiImplicitParam(value = "密码",name = "password")
- }
- )
- public CommonResult login( String username, String password){
- System.out.println(username+password);
- //获取主体对象
- Subject subject = SecurityUtils.getSubject();
- UsernamePasswordToken token = new UsernamePasswordToken(username,password);
- try {
- subject.login(token);
- System.out.println("-------------");
- return CommonResult.LOGIN_SUCCESS;
- }catch(Exception e){
- e.printStackTrace();
- return CommonResult.LOGIN_ERROR;
- }
- }
-
- @PostMapping("logout")
- @ApiOperation(value = "退出方法")
- public CommonResult logout(){
- //获取主体对象
- Subject subject = SecurityUtils.getSubject();
- subject.logout();
- return new CommonResult(200,"退出成功",null);
- }
- }
PermissionController:
- package com.wzh.controller;
-
- import io.swagger.annotations.Api;
- import io.swagger.annotations.ApiOperation;
- import org.apache.shiro.authz.annotation.Logical;
- import org.apache.shiro.authz.annotation.RequiresPermissions;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RestController;
-
- /**
- * @ProjectName: shiro-ssm0805
- * @Package: com.wzh.controller
- * @ClassName: PermissionController
- * @Author: 王振华
- * @Description:
- * @Date: 2022/8/5 19:57
- * @Version: 1.0
- */
- @RestController
- @Api(tags = "权限接口")
- public class PermissionController {
-
- @PostMapping("/query")
- @ApiOperation(value = "查询方法")
- //使用shiro注解
- @RequiresPermissions(value = {"user:query","user:aaa"},logical = Logical.OR)
- public String query(){
- return "query";
- }
-
- @ApiOperation(value = "添加方法")
- @PostMapping("/add")
- @RequiresPermissions(value = {"user:add"})
- public String add(){
- return "add";
- }
-
- @ApiOperation(value = "删除方法")
- @PostMapping("/delete")
- @RequiresPermissions(value = {"user:delete"})
- public String delete(){
- return "delete";
- }
-
- @ApiOperation(value = "修改方法")
- @PostMapping("/update")
- @RequiresPermissions(value = {"user:update"})
- public String update(){
- return "update";
- }
-
- @ApiOperation(value = "导出方法")
- @PostMapping("/export")
- @RequiresPermissions(value = {"user:export"})
- public String export(){
- return "export";
- }
- }
Service:
PermissionService:
- package com.wzh.Service;
-
- import java.util.List;
-
- /**
- * @ProjectName: ssm-shiro
- * @Package: com.wzh.service
- * @ClassName: PermissionService
- * @Author: 王振华
- * @Description:
- * @Date: 2022/8/4 22:27
- * @Version: 1.0
- */
- public interface PermissionService {
- List
findPermissionById(Integer userid); - }
RoleService:
- package com.wzh.Service;
-
- import java.util.List;
-
- /**
- * @ProjectName: ssm-shiro
- * @Package: com.wzh.service
- * @ClassName: RoleService
- * @Author: 王振华
- * @Description:
- * @Date: 2022/8/4 22:27
- * @Version: 1.0
- */
- public interface RoleService {
-
- List
findRolesById(Integer userid); - }
UserService:
- package com.wzh.Service;
-
- import com.wzh.entity.User;
-
- /**
- * @ProjectName: springboot-shiro-swagger
- * @Package: com.wzh.Service
- * @ClassName: UserService
- * @Author: 王振华
- * @Description:
- * @Date: 2022/8/5 17:51
- * @Version: 1.0
- */
- public interface UserService {
- User findByUsername(String username);
- }
PermissionServiceImpl:
- package com.wzh.Service.impl;
-
- import com.wzh.Service.PermissionService;
- import com.wzh.mapper.PermissionMapper;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
-
- import java.util.List;
-
- /**
- * @ProjectName: ssm-shiro
- * @Package: com.wzh.service.impl
- * @ClassName: PermissionServiceImpl
- * @Author: 王振华
- * @Description:
- * @Date: 2022/8/4 22:28
- * @Version: 1.0
- */
- @Service
- public class PermissionServiceImpl implements PermissionService {
- @Autowired
- private PermissionMapper permissionMapper;
-
- @Override
- public List
findPermissionById(Integer userid) { - List
list = permissionMapper.selectPercodeByUserId(userid); - return list;
- }
- }
RoleServiceImpl:
- package com.wzh.Service.impl;
-
- import com.wzh.Service.RoleService;
- import com.wzh.mapper.RoleMapper;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
-
- import java.util.List;
-
- /**
- * @ProjectName: ssm-shiro
- * @Package: com.wzh.service.impl
- * @ClassName: RoleServiceImpl
- * @Author: 王振华
- * @Description:
- * @Date: 2022/8/4 22:28
- * @Version: 1.0
- */
- @Service
- public class RoleServiceImpl implements RoleService {
- @Autowired
- private RoleMapper roleMapper;
- @Override
- public List
findRolesById(Integer userid) { - List
list = roleMapper.selectRolenameByUserId(userid); - return list;
- }
- }
UserServiceImpl:
- package com.wzh.Service.impl;
-
- import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
- import com.wzh.Service.UserService;
- import com.wzh.entity.User;
- import com.wzh.mapper.UserMapper;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
-
- /**
- * @ProjectName: springboot-shiro-swagger
- * @Package: com.wzh.Service.impl
- * @ClassName: UserServiceImpl
- * @Author: 王振华
- * @Description:
- * @Date: 2022/8/5 17:52
- * @Version: 1.0
- */
- @Service
- public class UserServiceImpl implements UserService {
- @Autowired
- private UserMapper userMapper;
-
- @Override
- public User findByUsername(String username) {
- QueryWrapper
queryWrapper = new QueryWrapper<>(); - queryWrapper.eq("username",username);
- User user = userMapper.selectOne(queryWrapper);
- return user;
- }
- }
mapper:
PermissionMapper:
- package com.wzh.mapper;
-
- import com.baomidou.mybatisplus.core.mapper.BaseMapper;
- import com.wzh.entity.Permission;
- import org.apache.ibatis.annotations.Select;
-
-
- import java.util.List;
-
- /**
- @ProjectName: ssm-shiro
- @Package: com.wzh.mapper
- @ClassName: PermissionMapper
- @Author: 王振华
- @Description:
- @Date: 2022/8/4 22:21
- @Version: 1.0
- */
- public interface PermissionMapper extends BaseMapper
{ - @Select("select percode from user_role ur" +
- " join role_permission rp on ur.roleid=rp.roleid" +
- " join permission p on p.perid=rp.perid" +
- " where ur.userid = #{userid}")
- List
selectPercodeByUserId(Integer userid); - }
RoleMapper:
- package com.wzh.mapper;
-
-
-
- import org.apache.ibatis.annotations.Select;
-
- import java.util.List;
-
- /**
- * @ProjectName: ssm-shiro
- * @Package: com.wzh.mapper
- * @ClassName: RoleMapper
- * @Author: 王振华
- * @Description:
- * @Date: 2022/8/4 22:21
- * @Version: 1.0
- */
-
- public interface RoleMapper {
- @Select("select rolename from user_role ur" +
- " join role r on ur.roleid=r.roleid" +
- " where ur.userid = #{userid}")
- List
selectRolenameByUserId(Integer userid); - }
UserMapper:
- package com.wzh.mapper;
-
- import com.baomidou.mybatisplus.core.mapper.BaseMapper;
- import com.wzh.entity.User;
-
- /**
- * @ProjectName: springboot-shiro-swagger
- * @Package: com.wzh.mapper
- * @ClassName: UserMapper
- * @Author: 王振华
- * @Description:
- * @Date: 2022/8/5 17:52
- * @Version: 1.0
- */
- public interface UserMapper extends BaseMapper
{ - }
entity:
Permission:
- package com.wzh.entity;
-
- import io.swagger.annotations.ApiModel;
- import io.swagger.annotations.ApiModelProperty;
- import lombok.AllArgsConstructor;
- import lombok.Data;
- import lombok.NoArgsConstructor;
-
- /**
- * @ProjectName: ssm-shiro
- * @Package: com.wzh.entity
- * @ClassName: Permission
- * @Author: 王振华
- * @Description:
- * @Date: 2022/8/4 22:22
- * @Version: 1.0
- */
- @Data
- @NoArgsConstructor
- @AllArgsConstructor
- @ApiModel("权限实体类")
- public class Permission {
- @ApiModelProperty(value = "id属性")
- private Integer perid;
- @ApiModelProperty(value = "权限名")
- private String pername;
- @ApiModelProperty(value = "权限码")
- private String percode;
- }
Role:
- package com.wzh.entity;
-
- import lombok.AllArgsConstructor;
- import lombok.Data;
- import lombok.NoArgsConstructor;
-
- /**
- * @ProjectName: ssm-shiro
- * @Package: com.wzh.entity
- * @ClassName: Role
- * @Author: 王振华
- * @Description:
- * @Date: 2022/8/4 22:22
- * @Version: 1.0
- */
- @Data
- @NoArgsConstructor
- @AllArgsConstructor
- public class Role {
- private Integer roleid;
-
- private String rolename;
- }
User:
- package com.wzh.entity;
-
- import lombok.AllArgsConstructor;
- import lombok.Data;
- import lombok.NoArgsConstructor;
-
- /**
- * @ProjectName: ssm-shiro
- * @Package: com.wzh.entity
- * @ClassName: User
- * @Author: 王振华
- * @Description:
- * @Date: 2022/8/4 22:19
- * @Version: 1.0
- */
- @Data
- @NoArgsConstructor
- @AllArgsConstructor
- public class User {
- private Integer userid;
-
- private String username;
-
- private String userpwd;
-
- private String sex;
-
- private String address;
-
- private String salt;
-
- }
filter:
LoginFilter:
- package com.wzh.filter;
-
- import com.fasterxml.jackson.databind.ObjectMapper;
-
- import com.wzh.util.CommonResult;
- import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
-
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
- import java.io.PrintWriter;
-
- /**
- * @ProjectName: springboot-shiro-swagger
- * @Package: com.wzh.filter
- * @ClassName: LoginFilter
- * @Author: 王振华
- * @Description:
- * @Date: 2022/8/5 17:47
- * @Version: 1.0
- */
- public class LoginFilter extends FormAuthenticationFilter {
- @Override
- protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
- response.setContentType("application/json;charset=utf-8");
- PrintWriter writer = response.getWriter();
- CommonResult commonResult = CommonResult.UNLOGIN;
- ObjectMapper objectMapper = new ObjectMapper();
- String json = objectMapper.writeValueAsString(commonResult);
- writer.print(json);
- writer.flush();
- writer.close();
- return false;
- }
- }
handler:
MyException:
- package com.wzh.handler;
-
- import com.wzh.util.CommonResult;
- import org.apache.shiro.authz.UnauthorizedException;
- import org.springframework.web.bind.annotation.ControllerAdvice;
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.bind.annotation.ResponseBody;
-
- /**
- * @ProjectName: springboot-shiro-swagger
- * @Package: com.wzh.handler
- * @ClassName: MyException
- * @Author: 王振华
- * @Description:
- * @Date: 2022/8/5 19:02
- * @Version: 1.0
- */
- @ControllerAdvice
- public class MyException {
- @ExceptionHandler(value = UnauthorizedException.class)
- @ResponseBody
- public CommonResult Unauth(UnauthorizedException e){
- e.printStackTrace();
- return CommonResult.UNAUTHORIZED;
- }
- }
util:
CommonResult:
- package com.wzh.util;
-
- import io.swagger.annotations.ApiModel;
- import io.swagger.annotations.ApiModelProperty;
- import lombok.AllArgsConstructor;
- import lombok.Data;
- import lombok.NoArgsConstructor;
-
- /**
- * @ProjectName: springboot-shiro-swagger
- * @Package: com.wzh.util
- * @ClassName: CommonResult
- * @Author: 王振华
- * @Description:
- * @Date: 2022/8/5 18:03
- * @Version: 1.0
- */
- @Data
- @NoArgsConstructor
- @AllArgsConstructor
- @ApiModel("统一返回json对象")
- public class CommonResult {
- @ApiModelProperty("状态码")
- private Integer code;
- @ApiModelProperty("响应的信息内容")
- private String msg;
- @ApiModelProperty("响应的数据")
- private Object data;
-
- public static final CommonResult UNLOGIN = new CommonResult(403,"未登录",null);
- public static final CommonResult UNAUTHORIZED = new CommonResult(405,"未授权",null);
- public static final CommonResult LOGIN_SUCCESS = new CommonResult(200,"登录成功",null);
- public static final CommonResult LOGIN_ERROR = new CommonResult(-1,"登录失败",null);
- }
- package com.wzh.realm;
-
- import com.wzh.Service.PermissionService;
- import com.wzh.Service.RoleService;
- import com.wzh.Service.UserService;
- import com.wzh.entity.User;
- 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.apache.shiro.util.ByteSource;
- import org.springframework.beans.factory.annotation.Autowired;
-
- import java.util.List;
-
- /**
- * @ProjectName: springboot
- * @Package: com.wzh.realm
- * @ClassName: UserRealm
- * @Author: 王振华
- * @Description: 自定义realm
- * @Date: 2022/8/6 17:50
- * @Version: 1.0
- */
- public class UserRealm extends AuthorizingRealm {
- @Autowired
- private UserService userService;
-
- @Autowired
- private PermissionService permissionService;
-
- @Autowired
- private RoleService roleService;
-
- //当你进行权限校验时会执行该方法
- @Override
- protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
- User user = (User) principals.getPrimaryPrincipal();
- SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
- //根据账号查找该用户具有哪些权限
- List
list = permissionService.findPermissionById(user.getUserid()); - if(list!=null&&list.size()>0){
- info.addStringPermissions(list);
- }
- List
roles = roleService.findRolesById(user.getUserid()); - if(roles!=null&&roles.size()>0){
- info.addRoles(roles);
- }
- return info;
- }
-
- //该方法用于完成认证的功能
- @Override
- protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
- //1.根据token获取账号
- String username = (String) token.getPrincipal();
- /**
- * 以前登陆的逻辑是 把用户和密码全部发到数据库 去匹配
- * 在shrio里面是先根据用户名把用户对象查询出来,再来做密码匹配
- */
-
- //2.根据账号查询用户信息
- User user = userService.findByUsername(username);
- //表示该用户名在数据库中存在
- if(user!=null){
- /**
- * 参数说明
- * 参数1:可以传到任意对象
- * 参数2:从数据库里面查询出来的密码
- * 参数3:盐
- * 参数4:当前类名
- */
- ByteSource credentialsSalt = ByteSource.Util.bytes(user.getSalt());
- SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getUserpwd(),credentialsSalt,this.getName());
- return info;
- }
- return null;
- }
- }


运行程序如果报404,看是否开启shiro注解
- //开始shiro注解
- @Bean
- public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
- AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
- authorizationAttributeSourceAdvisor.setSecurityManager(securityManager());
- return authorizationAttributeSourceAdvisor;
- }
- @Bean
- public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() {
- DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator=new DefaultAdvisorAutoProxyCreator();
- advisorAutoProxyCreator.setProxyTargetClass(true);
- return advisorAutoProxyCreator;
- }
使用swagger doc.html无法访问以及样式无效。 shiro拦截规则拦截了 记得在配置文件中放行