• Springboot整合shiro安全框架+swagger


    1.创建项目

    2.加入依赖

    1. <dependencies>
    2. <dependency>
    3. <groupId>org.apache.shirogroupId>
    4. <artifactId>shiro-spring-boot-starterartifactId>
    5. <version>1.7.0version>
    6. dependency>
    7. <dependency>
    8. <groupId>com.spring4allgroupId>
    9. <artifactId>swagger-spring-boot-starterartifactId>
    10. <version>1.9.1.RELEASEversion>
    11. dependency>
    12. <dependency>
    13. <groupId>com.github.xiaoymingroupId>
    14. <artifactId>swagger-bootstrap-uiartifactId>
    15. <version>1.7.8version>
    16. dependency>
    17. <dependency>
    18. <groupId>org.springframework.bootgroupId>
    19. <artifactId>spring-boot-starter-webartifactId>
    20. dependency>
    21. <dependency>
    22. <groupId>mysqlgroupId>
    23. <artifactId>mysql-connector-javaartifactId>
    24. dependency>
    25. <dependency>
    26. <groupId>org.projectlombokgroupId>
    27. <artifactId>lombokartifactId>
    28. <optional>trueoptional>
    29. dependency>
    30. <dependency>
    31. <groupId>com.baomidougroupId>
    32. <artifactId>mybatis-plus-boot-starterartifactId>
    33. <version>3.5.1version>
    34. dependency>
    35. <dependency>
    36. <groupId>org.springframework.bootgroupId>
    37. <artifactId>spring-boot-starter-testartifactId>
    38. <scope>testscope>
    39. dependency>
    40. dependencies>

    3.application配置文件

    1. #配置数据源
    2. spring.datasource.url=jdbc:mysql://localhost:3306/shiro?serverTimezone=Asia/Shanghai
    3. spring.datasource.username=root
    4. spring.datasource.password=123456
    5. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    6. #端口号
    7. server.port=8081
    8. #sql日志 属于mybatis-plus的
    9. mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
    10. #如果你的springboot 是 2.6.x上的版本得加 2.3.12不需要
    11. #spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER

    4.创建ShiroProperties实体类

    1. package com.wzh.entity;
    2. import io.swagger.annotations.ApiModelProperty;
    3. import lombok.AllArgsConstructor;
    4. import lombok.Data;
    5. import lombok.NoArgsConstructor;
    6. import org.springframework.boot.context.properties.ConfigurationProperties;
    7. import org.springframework.stereotype.Component;
    8. /**
    9. * @ProjectName: springboot
    10. * @Package: com.wzh.entity
    11. * @ClassName: ShiroProperties
    12. * @Author: 王振华
    13. * @Description:
    14. * @Date: 2022/8/6 17:40
    15. * @Version: 1.0
    16. */
    17. @Data
    18. @Component
    19. @ConfigurationProperties(prefix = "shiro")//使用配置文件的内容
    20. public class ShiroProperties {
    21. private String hashAlgorithmName="md5";
    22. private Integer hashIterations=2;
    23. private String loginUrl;
    24. private String unauthorizedUrl;
    25. private String [] anonUrls;
    26. private String logoutUrl;
    27. private String [] authcUrls;
    28. }

    5.修改application配置文件

    1. #shiro的配置
    2. shiro.hash-algorithm-name:MD5
    3. shiro.hash-iterations=1024
    4. shiro.login-url=/index.html
    5. shiro.unauthorized-url=/unauthorized.html
    6. shiro.anon-urls[0]=/login/*
    7. shiro.anon-urls[1]=/doc.html
    8. shiro.anon-urls[2]=/swagger-ui.html
    9. shiro.anon-urls[3]=/webjars/**
    10. shiro.anon-urls[4]=/swagger/**
    11. shiro.anon-urls[5]=/swagger-resources/**
    12. shiro.anon-urls[6]=/v2/**
    13. shiro.anon-urls[7]=/static/**
    14. shiro.logout-url=/login/logout*
    15. shiro.authc-urls[0]=/**

    6.创建shiro配置类

    1. package com.wzh.config;
    2. import com.wzh.entity.ShiroProperties;
    3. import com.wzh.filter.LoginFilter;
    4. import com.wzh.realm.UserRealm;
    5. import org.apache.shiro.authc.credential.CredentialsMatcher;
    6. import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
    7. import org.apache.shiro.mgt.SecurityManager;
    8. import org.apache.shiro.realm.Realm;
    9. import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
    10. import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
    11. import org.springframework.beans.factory.annotation.Autowired;
    12. import org.springframework.boot.web.servlet.FilterRegistrationBean;
    13. import org.springframework.context.annotation.Bean;
    14. import org.springframework.context.annotation.Configuration;
    15. import org.springframework.web.filter.DelegatingFilterProxy;
    16. import javax.servlet.Filter;
    17. import java.util.HashMap;
    18. import java.util.Map;
    19. /**
    20. * @ProjectName: springboot
    21. * @Package: com.wzh.config
    22. * @ClassName: ShiroAutoConfiguration
    23. * @Author: 王振华
    24. * @Description: shiro配置类
    25. * @Date: 2022/8/6 17:37
    26. * @Version: 1.0
    27. */
    28. @Configuration
    29. public class ShiroAutoConfiguration {
    30. @Autowired
    31. private ShiroProperties shiroProperties;
    32. /**
    33. * 声明安全管理器
    34. * @return
    35. */
    36. @Bean
    37. public DefaultWebSecurityManager securityManager(){
    38. DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
    39. securityManager.setRealm(realm());
    40. return securityManager;
    41. }
    42. /**
    43. * 创建realm
    44. */
    45. @Bean
    46. public Realm realm(){
    47. UserRealm myRealm=new UserRealm();
    48. //注入凭证匹配器
    49. myRealm.setCredentialsMatcher(credentialsMatcher());
    50. return myRealm;
    51. }
    52. /**
    53. * 创建凭证匹配器
    54. */
    55. @Bean
    56. public HashedCredentialsMatcher credentialsMatcher(){
    57. HashedCredentialsMatcher credentialsMatcher=new HashedCredentialsMatcher();
    58. credentialsMatcher.setHashAlgorithmName(shiroProperties.getHashAlgorithmName());
    59. credentialsMatcher.setHashIterations(shiroProperties.getHashIterations());
    60. return credentialsMatcher;
    61. }
    62. /**
    63. * 配置过滤器 Shiro 的Web过滤器 必须和下面的注册过滤器名称一样
    64. */
    65. @Bean(value = "shiroFilter")
    66. public ShiroFilterFactoryBean filterFactoryBean(){
    67. ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
    68. //注入安全管理器
    69. factoryBean.setSecurityManager(securityManager());
    70. //注入登陆页面
    71. factoryBean.setLoginUrl(shiroProperties.getLoginUrl());
    72. //注入未授权的页面地址
    73. factoryBean.setUnauthorizedUrl(shiroProperties.getUnauthorizedUrl());
    74. //注入过滤器
    75. Map filterChainDefinition=new HashMap<>();
    76. //注入放行地址
    77. if(shiroProperties.getAnonUrls()!=null&&shiroProperties.getAnonUrls().length>0){
    78. String[] anonUrls = shiroProperties.getAnonUrls();
    79. for (String anonUrl : anonUrls) {
    80. filterChainDefinition.put(anonUrl,"anon");
    81. }
    82. }
    83. //注入登出的地址
    84. if(shiroProperties.getLogoutUrl()!=null){
    85. filterChainDefinition.put(shiroProperties.getLogoutUrl(),"logout");
    86. }
    87. //注入拦截的地址
    88. String[] authcUrls = shiroProperties.getAuthcUrls();
    89. if(authcUrls!=null&&authcUrls.length>0){
    90. for (String authcUrl : authcUrls) {
    91. filterChainDefinition.put(authcUrl,"authc");
    92. }
    93. }
    94. factoryBean.setFilterChainDefinitionMap(filterChainDefinition);
    95. //设置自定义认证过滤器
    96. HashMap filterMap=new HashMap();
    97. filterMap.put("authc",new LoginFilter());
    98. factoryBean.setFilters(filterMap);
    99. return factoryBean;
    100. }
    101. /**
    102. * 注册过滤器
    103. */
    104. @Bean //注册filter
    105. public FilterRegistrationBean filterRegistrationBean(){
    106. FilterRegistrationBean filterRegistrationBean=new FilterRegistrationBean<>();
    107. filterRegistrationBean.setName("shiroFilter");
    108. filterRegistrationBean.setFilter(new DelegatingFilterProxy());
    109. filterRegistrationBean.addUrlPatterns("/*");
    110. return filterRegistrationBean;
    111. }
    112. }

    7.创建controller service mapper entity

    config:

    ShiroAutoConfigurtion:就上面的

    SwaggerConfig:

    1. package com.wzh.config;
    2. import org.springframework.context.annotation.Bean;
    3. import org.springframework.context.annotation.Configuration;
    4. import springfox.documentation.builders.RequestHandlerSelectors;
    5. import springfox.documentation.service.ApiInfo;
    6. import springfox.documentation.service.Contact;
    7. import springfox.documentation.service.VendorExtension;
    8. import springfox.documentation.spi.DocumentationType;
    9. import springfox.documentation.spring.web.plugins.Docket;
    10. import java.util.ArrayList;
    11. /**
    12. * @ProjectName: springboot-shiro-swagger
    13. * @Package: com.wzh.config
    14. * @ClassName: SwaggerConfig
    15. * @Author: 王振华
    16. * @Description:
    17. * @Date: 2022/8/5 19:54
    18. * @Version: 1.0
    19. */
    20. @Configuration
    21. public class SwaggerConfig {
    22. @Bean //swagger中所有的功能都封装在Docket类中。
    23. public Docket docket(){
    24. Docket docket = new Docket(DocumentationType.SWAGGER_2)
    25. .apiInfo(apiInfo()) //设置api文档信息
    26. .select()
    27. .apis(RequestHandlerSelectors.basePackage("com.wzh.controller")) //指定为哪些包下的类生成接口文档
    28. .build()
    29. ;
    30. return docket;
    31. }
    32. //定义自己接口文档信息
    33. private ApiInfo apiInfo(){
    34. Contact DEFAULT_CONTACT = new Contact("王振华", "http://www/baidu.com", "13234@qq.com");
    35. ApiInfo apiInfo = new ApiInfo("在线文档", "世界上最牛的一个文档", "V1.0", "http://www/jd.com",
    36. DEFAULT_CONTACT, "xx科技有限公司", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList());
    37. return apiInfo;
    38. }
    39. }

    controller:

    LoginController:

    1. package com.wzh.controller;
    2. import com.wzh.util.CommonResult;
    3. import io.swagger.annotations.Api;
    4. import io.swagger.annotations.ApiImplicitParam;
    5. import io.swagger.annotations.ApiImplicitParams;
    6. import io.swagger.annotations.ApiOperation;
    7. import org.apache.shiro.SecurityUtils;
    8. import org.apache.shiro.authc.UsernamePasswordToken;
    9. import org.apache.shiro.subject.Subject;
    10. import org.springframework.web.bind.annotation.*;
    11. /**
    12. * @ProjectName: springboot-shiro-swagger
    13. * @Package: com.wzh.controller
    14. * @ClassName: LoginController
    15. * @Author: 王振华
    16. * @Description:
    17. * @Date: 2022/8/5 17:51
    18. * @Version: 1.0
    19. */
    20. @RestController
    21. @RequestMapping("/login")
    22. @Api(tags = "登录的接口")
    23. public class LoginController {
    24. @GetMapping("/toLogin")
    25. @ApiOperation(value = "登录方法")
    26. @ApiImplicitParams(
    27. {
    28. @ApiImplicitParam(value = "用户名",name = "username"),
    29. @ApiImplicitParam(value = "密码",name = "password")
    30. }
    31. )
    32. public CommonResult login( String username, String password){
    33. System.out.println(username+password);
    34. //获取主体对象
    35. Subject subject = SecurityUtils.getSubject();
    36. UsernamePasswordToken token = new UsernamePasswordToken(username,password);
    37. try {
    38. subject.login(token);
    39. System.out.println("-------------");
    40. return CommonResult.LOGIN_SUCCESS;
    41. }catch(Exception e){
    42. e.printStackTrace();
    43. return CommonResult.LOGIN_ERROR;
    44. }
    45. }
    46. @PostMapping("logout")
    47. @ApiOperation(value = "退出方法")
    48. public CommonResult logout(){
    49. //获取主体对象
    50. Subject subject = SecurityUtils.getSubject();
    51. subject.logout();
    52. return new CommonResult(200,"退出成功",null);
    53. }
    54. }

    PermissionController:

    1. package com.wzh.controller;
    2. import io.swagger.annotations.Api;
    3. import io.swagger.annotations.ApiOperation;
    4. import org.apache.shiro.authz.annotation.Logical;
    5. import org.apache.shiro.authz.annotation.RequiresPermissions;
    6. import org.springframework.web.bind.annotation.PostMapping;
    7. import org.springframework.web.bind.annotation.RestController;
    8. /**
    9. * @ProjectName: shiro-ssm0805
    10. * @Package: com.wzh.controller
    11. * @ClassName: PermissionController
    12. * @Author: 王振华
    13. * @Description:
    14. * @Date: 2022/8/5 19:57
    15. * @Version: 1.0
    16. */
    17. @RestController
    18. @Api(tags = "权限接口")
    19. public class PermissionController {
    20. @PostMapping("/query")
    21. @ApiOperation(value = "查询方法")
    22. //使用shiro注解
    23. @RequiresPermissions(value = {"user:query","user:aaa"},logical = Logical.OR)
    24. public String query(){
    25. return "query";
    26. }
    27. @ApiOperation(value = "添加方法")
    28. @PostMapping("/add")
    29. @RequiresPermissions(value = {"user:add"})
    30. public String add(){
    31. return "add";
    32. }
    33. @ApiOperation(value = "删除方法")
    34. @PostMapping("/delete")
    35. @RequiresPermissions(value = {"user:delete"})
    36. public String delete(){
    37. return "delete";
    38. }
    39. @ApiOperation(value = "修改方法")
    40. @PostMapping("/update")
    41. @RequiresPermissions(value = {"user:update"})
    42. public String update(){
    43. return "update";
    44. }
    45. @ApiOperation(value = "导出方法")
    46. @PostMapping("/export")
    47. @RequiresPermissions(value = {"user:export"})
    48. public String export(){
    49. return "export";
    50. }
    51. }

    Service:

    PermissionService:

    1. package com.wzh.Service;
    2. import java.util.List;
    3. /**
    4. * @ProjectName: ssm-shiro
    5. * @Package: com.wzh.service
    6. * @ClassName: PermissionService
    7. * @Author: 王振华
    8. * @Description:
    9. * @Date: 2022/8/4 22:27
    10. * @Version: 1.0
    11. */
    12. public interface PermissionService {
    13. List findPermissionById(Integer userid);
    14. }

    RoleService:

    1. package com.wzh.Service;
    2. import java.util.List;
    3. /**
    4. * @ProjectName: ssm-shiro
    5. * @Package: com.wzh.service
    6. * @ClassName: RoleService
    7. * @Author: 王振华
    8. * @Description:
    9. * @Date: 2022/8/4 22:27
    10. * @Version: 1.0
    11. */
    12. public interface RoleService {
    13. List findRolesById(Integer userid);
    14. }

    UserService:

    1. package com.wzh.Service;
    2. import com.wzh.entity.User;
    3. /**
    4. * @ProjectName: springboot-shiro-swagger
    5. * @Package: com.wzh.Service
    6. * @ClassName: UserService
    7. * @Author: 王振华
    8. * @Description:
    9. * @Date: 2022/8/5 17:51
    10. * @Version: 1.0
    11. */
    12. public interface UserService {
    13. User findByUsername(String username);
    14. }

    PermissionServiceImpl:

    1. package com.wzh.Service.impl;
    2. import com.wzh.Service.PermissionService;
    3. import com.wzh.mapper.PermissionMapper;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.stereotype.Service;
    6. import java.util.List;
    7. /**
    8. * @ProjectName: ssm-shiro
    9. * @Package: com.wzh.service.impl
    10. * @ClassName: PermissionServiceImpl
    11. * @Author: 王振华
    12. * @Description:
    13. * @Date: 2022/8/4 22:28
    14. * @Version: 1.0
    15. */
    16. @Service
    17. public class PermissionServiceImpl implements PermissionService {
    18. @Autowired
    19. private PermissionMapper permissionMapper;
    20. @Override
    21. public List findPermissionById(Integer userid) {
    22. List list = permissionMapper.selectPercodeByUserId(userid);
    23. return list;
    24. }
    25. }

    RoleServiceImpl:

    1. package com.wzh.Service.impl;
    2. import com.wzh.Service.RoleService;
    3. import com.wzh.mapper.RoleMapper;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.stereotype.Service;
    6. import java.util.List;
    7. /**
    8. * @ProjectName: ssm-shiro
    9. * @Package: com.wzh.service.impl
    10. * @ClassName: RoleServiceImpl
    11. * @Author: 王振华
    12. * @Description:
    13. * @Date: 2022/8/4 22:28
    14. * @Version: 1.0
    15. */
    16. @Service
    17. public class RoleServiceImpl implements RoleService {
    18. @Autowired
    19. private RoleMapper roleMapper;
    20. @Override
    21. public List findRolesById(Integer userid) {
    22. List list = roleMapper.selectRolenameByUserId(userid);
    23. return list;
    24. }
    25. }

    UserServiceImpl:

    1. package com.wzh.Service.impl;
    2. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
    3. import com.wzh.Service.UserService;
    4. import com.wzh.entity.User;
    5. import com.wzh.mapper.UserMapper;
    6. import org.springframework.beans.factory.annotation.Autowired;
    7. import org.springframework.stereotype.Service;
    8. /**
    9. * @ProjectName: springboot-shiro-swagger
    10. * @Package: com.wzh.Service.impl
    11. * @ClassName: UserServiceImpl
    12. * @Author: 王振华
    13. * @Description:
    14. * @Date: 2022/8/5 17:52
    15. * @Version: 1.0
    16. */
    17. @Service
    18. public class UserServiceImpl implements UserService {
    19. @Autowired
    20. private UserMapper userMapper;
    21. @Override
    22. public User findByUsername(String username) {
    23. QueryWrapper queryWrapper = new QueryWrapper<>();
    24. queryWrapper.eq("username",username);
    25. User user = userMapper.selectOne(queryWrapper);
    26. return user;
    27. }
    28. }

    mapper:

    PermissionMapper:

    1. package com.wzh.mapper;
    2. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
    3. import com.wzh.entity.Permission;
    4. import org.apache.ibatis.annotations.Select;
    5. import java.util.List;
    6. /**
    7. @ProjectName: ssm-shiro
    8. @Package: com.wzh.mapper
    9. @ClassName: PermissionMapper
    10. @Author: 王振华
    11. @Description:
    12. @Date: 2022/8/4 22:21
    13. @Version: 1.0
    14. */
    15. public interface PermissionMapper extends BaseMapper {
    16. @Select("select percode from user_role ur" +
    17. " join role_permission rp on ur.roleid=rp.roleid" +
    18. " join permission p on p.perid=rp.perid" +
    19. " where ur.userid = #{userid}")
    20. List selectPercodeByUserId(Integer userid);
    21. }

    RoleMapper:

    1. package com.wzh.mapper;
    2. import org.apache.ibatis.annotations.Select;
    3. import java.util.List;
    4. /**
    5. * @ProjectName: ssm-shiro
    6. * @Package: com.wzh.mapper
    7. * @ClassName: RoleMapper
    8. * @Author: 王振华
    9. * @Description:
    10. * @Date: 2022/8/4 22:21
    11. * @Version: 1.0
    12. */
    13. public interface RoleMapper {
    14. @Select("select rolename from user_role ur" +
    15. " join role r on ur.roleid=r.roleid" +
    16. " where ur.userid = #{userid}")
    17. List selectRolenameByUserId(Integer userid);
    18. }

    UserMapper:

    1. package com.wzh.mapper;
    2. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
    3. import com.wzh.entity.User;
    4. /**
    5. * @ProjectName: springboot-shiro-swagger
    6. * @Package: com.wzh.mapper
    7. * @ClassName: UserMapper
    8. * @Author: 王振华
    9. * @Description:
    10. * @Date: 2022/8/5 17:52
    11. * @Version: 1.0
    12. */
    13. public interface UserMapper extends BaseMapper {
    14. }

    entity:

    Permission:

    1. package com.wzh.entity;
    2. import io.swagger.annotations.ApiModel;
    3. import io.swagger.annotations.ApiModelProperty;
    4. import lombok.AllArgsConstructor;
    5. import lombok.Data;
    6. import lombok.NoArgsConstructor;
    7. /**
    8. * @ProjectName: ssm-shiro
    9. * @Package: com.wzh.entity
    10. * @ClassName: Permission
    11. * @Author: 王振华
    12. * @Description:
    13. * @Date: 2022/8/4 22:22
    14. * @Version: 1.0
    15. */
    16. @Data
    17. @NoArgsConstructor
    18. @AllArgsConstructor
    19. @ApiModel("权限实体类")
    20. public class Permission {
    21. @ApiModelProperty(value = "id属性")
    22. private Integer perid;
    23. @ApiModelProperty(value = "权限名")
    24. private String pername;
    25. @ApiModelProperty(value = "权限码")
    26. private String percode;
    27. }

    Role:

    1. package com.wzh.entity;
    2. import lombok.AllArgsConstructor;
    3. import lombok.Data;
    4. import lombok.NoArgsConstructor;
    5. /**
    6. * @ProjectName: ssm-shiro
    7. * @Package: com.wzh.entity
    8. * @ClassName: Role
    9. * @Author: 王振华
    10. * @Description:
    11. * @Date: 2022/8/4 22:22
    12. * @Version: 1.0
    13. */
    14. @Data
    15. @NoArgsConstructor
    16. @AllArgsConstructor
    17. public class Role {
    18. private Integer roleid;
    19. private String rolename;
    20. }

    User:

    1. package com.wzh.entity;
    2. import lombok.AllArgsConstructor;
    3. import lombok.Data;
    4. import lombok.NoArgsConstructor;
    5. /**
    6. * @ProjectName: ssm-shiro
    7. * @Package: com.wzh.entity
    8. * @ClassName: User
    9. * @Author: 王振华
    10. * @Description:
    11. * @Date: 2022/8/4 22:19
    12. * @Version: 1.0
    13. */
    14. @Data
    15. @NoArgsConstructor
    16. @AllArgsConstructor
    17. public class User {
    18. private Integer userid;
    19. private String username;
    20. private String userpwd;
    21. private String sex;
    22. private String address;
    23. private String salt;
    24. }

    filter:

    LoginFilter:

    1. package com.wzh.filter;
    2. import com.fasterxml.jackson.databind.ObjectMapper;
    3. import com.wzh.util.CommonResult;
    4. import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
    5. import javax.servlet.ServletRequest;
    6. import javax.servlet.ServletResponse;
    7. import java.io.PrintWriter;
    8. /**
    9. * @ProjectName: springboot-shiro-swagger
    10. * @Package: com.wzh.filter
    11. * @ClassName: LoginFilter
    12. * @Author: 王振华
    13. * @Description:
    14. * @Date: 2022/8/5 17:47
    15. * @Version: 1.0
    16. */
    17. public class LoginFilter extends FormAuthenticationFilter {
    18. @Override
    19. protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
    20. response.setContentType("application/json;charset=utf-8");
    21. PrintWriter writer = response.getWriter();
    22. CommonResult commonResult = CommonResult.UNLOGIN;
    23. ObjectMapper objectMapper = new ObjectMapper();
    24. String json = objectMapper.writeValueAsString(commonResult);
    25. writer.print(json);
    26. writer.flush();
    27. writer.close();
    28. return false;
    29. }
    30. }

    handler:

    MyException:

    1. package com.wzh.handler;
    2. import com.wzh.util.CommonResult;
    3. import org.apache.shiro.authz.UnauthorizedException;
    4. import org.springframework.web.bind.annotation.ControllerAdvice;
    5. import org.springframework.web.bind.annotation.ExceptionHandler;
    6. import org.springframework.web.bind.annotation.ResponseBody;
    7. /**
    8. * @ProjectName: springboot-shiro-swagger
    9. * @Package: com.wzh.handler
    10. * @ClassName: MyException
    11. * @Author: 王振华
    12. * @Description:
    13. * @Date: 2022/8/5 19:02
    14. * @Version: 1.0
    15. */
    16. @ControllerAdvice
    17. public class MyException {
    18. @ExceptionHandler(value = UnauthorizedException.class)
    19. @ResponseBody
    20. public CommonResult Unauth(UnauthorizedException e){
    21. e.printStackTrace();
    22. return CommonResult.UNAUTHORIZED;
    23. }
    24. }

    util:

    CommonResult:

    1. package com.wzh.util;
    2. import io.swagger.annotations.ApiModel;
    3. import io.swagger.annotations.ApiModelProperty;
    4. import lombok.AllArgsConstructor;
    5. import lombok.Data;
    6. import lombok.NoArgsConstructor;
    7. /**
    8. * @ProjectName: springboot-shiro-swagger
    9. * @Package: com.wzh.util
    10. * @ClassName: CommonResult
    11. * @Author: 王振华
    12. * @Description:
    13. * @Date: 2022/8/5 18:03
    14. * @Version: 1.0
    15. */
    16. @Data
    17. @NoArgsConstructor
    18. @AllArgsConstructor
    19. @ApiModel("统一返回json对象")
    20. public class CommonResult {
    21. @ApiModelProperty("状态码")
    22. private Integer code;
    23. @ApiModelProperty("响应的信息内容")
    24. private String msg;
    25. @ApiModelProperty("响应的数据")
    26. private Object data;
    27. public static final CommonResult UNLOGIN = new CommonResult(403,"未登录",null);
    28. public static final CommonResult UNAUTHORIZED = new CommonResult(405,"未授权",null);
    29. public static final CommonResult LOGIN_SUCCESS = new CommonResult(200,"登录成功",null);
    30. public static final CommonResult LOGIN_ERROR = new CommonResult(-1,"登录失败",null);
    31. }

    8.创建realm

    1. package com.wzh.realm;
    2. import com.wzh.Service.PermissionService;
    3. import com.wzh.Service.RoleService;
    4. import com.wzh.Service.UserService;
    5. import com.wzh.entity.User;
    6. import org.apache.shiro.authc.AuthenticationException;
    7. import org.apache.shiro.authc.AuthenticationInfo;
    8. import org.apache.shiro.authc.AuthenticationToken;
    9. import org.apache.shiro.authc.SimpleAuthenticationInfo;
    10. import org.apache.shiro.authz.AuthorizationInfo;
    11. import org.apache.shiro.authz.SimpleAuthorizationInfo;
    12. import org.apache.shiro.realm.AuthorizingRealm;
    13. import org.apache.shiro.subject.PrincipalCollection;
    14. import org.apache.shiro.util.ByteSource;
    15. import org.springframework.beans.factory.annotation.Autowired;
    16. import java.util.List;
    17. /**
    18. * @ProjectName: springboot
    19. * @Package: com.wzh.realm
    20. * @ClassName: UserRealm
    21. * @Author: 王振华
    22. * @Description: 自定义realm
    23. * @Date: 2022/8/6 17:50
    24. * @Version: 1.0
    25. */
    26. public class UserRealm extends AuthorizingRealm {
    27. @Autowired
    28. private UserService userService;
    29. @Autowired
    30. private PermissionService permissionService;
    31. @Autowired
    32. private RoleService roleService;
    33. //当你进行权限校验时会执行该方法
    34. @Override
    35. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    36. User user = (User) principals.getPrimaryPrincipal();
    37. SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    38. //根据账号查找该用户具有哪些权限
    39. List list = permissionService.findPermissionById(user.getUserid());
    40. if(list!=null&&list.size()>0){
    41. info.addStringPermissions(list);
    42. }
    43. List roles = roleService.findRolesById(user.getUserid());
    44. if(roles!=null&&roles.size()>0){
    45. info.addRoles(roles);
    46. }
    47. return info;
    48. }
    49. //该方法用于完成认证的功能
    50. @Override
    51. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    52. //1.根据token获取账号
    53. String username = (String) token.getPrincipal();
    54. /**
    55. * 以前登陆的逻辑是 把用户和密码全部发到数据库 去匹配
    56. * 在shrio里面是先根据用户名把用户对象查询出来,再来做密码匹配
    57. */
    58. //2.根据账号查询用户信息
    59. User user = userService.findByUsername(username);
    60. //表示该用户名在数据库中存在
    61. if(user!=null){
    62. /**
    63. * 参数说明
    64. * 参数1:可以传到任意对象
    65. * 参数2:从数据库里面查询出来的密码
    66. * 参数3:盐
    67. * 参数4:当前类名
    68. */
    69. ByteSource credentialsSalt = ByteSource.Util.bytes(user.getSalt());
    70. SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getUserpwd(),credentialsSalt,this.getName());
    71. return info;
    72. }
    73. return null;
    74. }
    75. }

     

     运行程序如果报404,看是否开启shiro注解

    1. //开始shiro注解
    2. @Bean
    3. public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
    4. AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
    5. authorizationAttributeSourceAdvisor.setSecurityManager(securityManager());
    6. return authorizationAttributeSourceAdvisor;
    7. }
    8. @Bean
    9. public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() {
    10. DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator=new DefaultAdvisorAutoProxyCreator();
    11. advisorAutoProxyCreator.setProxyTargetClass(true);
    12. return advisorAutoProxyCreator;
    13. }

    使用swagger doc.html无法访问以及样式无效。 shiro拦截规则拦截了  记得在配置文件中放行

     

  • 相关阅读:
    算法与数据结构(第二周)——排序基础:插入排序法
    文件加密,数据防泄密软件
    基于python的pdf2word(可以批量转换)
    搜维尔科技:Xsens在现实生活中实时控制虚幻人形机器人
    最近公共祖先(lca)
    JVM虚拟机:Java对象的头信息有什么?
    【职场必备知识】毕业留蓉政策与发展前景分析
    Spring MVC——Rest风格
    计算机视觉的应用16-基于pytorch框架搭建的注意力机制,在汽车品牌与型号分类识别的应用
    【OpenCV-Python】教程:3-11 图像变换(频域变换)
  • 原文地址:https://blog.csdn.net/weixin_68509156/article/details/126198065