springboot+swagger+shiro+jwt+redis

本文介绍了如何在SpringBoot项目中整合Swagger进行API测试,利用Shiro进行权限控制,结合JWT生成令牌并利用Redis进行令牌存储及验证,同时讨论了配置过程中的关键步骤和可能出现的问题。
摘要由CSDN通过智能技术生成

springboot+swagger+shiro+jwt+redis

主要功能

  1. 登陆认证
  2. 权限控制
  3. 自动延长token过期时间

实现步骤

1,集成swagger,这个方便测试,所以第一个先把他搞定

1.1,导入依赖,下面是代码
 <!--swagger-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
1.2,配置swagger属性,创建一个类作为swagger的配置类,下面开始配置属性

代码如下

@Configuration
public class SwaggerConfig {
    //是否开启swagger,根据环境来选择
    @Value(value = "${swagger.enabled}")
    Boolean swaggerEnabled;

    @Bean
    public Docket Lamp() {

        Parameter token = new ParameterBuilder().name("token")  //全局参数
                .description("用户登陆令牌")
                .parameterType("header")
                .modelRef(new ModelRef("String"))
                .required(true)
                .build();
        ArrayList<Parameter> parameters = new ArrayList<>();
        parameters.add(token);
        return new Docket(DocumentationType.SWAGGER_2)
                .globalOperationParameters(parameters)
                .apiInfo(apiInfo())
                .groupName("灯")
              .select()
              .apis(RequestHandlerSelectors.basePackage("com.csdn.swaggershirojwtredis.controller"))
                .paths(Predicates.or(
                        PathSelectors.regex("/lamp.*"),
                        PathSelectors.regex("/lampState.*")
                ))
                .build();
      }
    @Bean
    public Docket LampState() {
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
                .groupName("获取Token")
              .select()
              .apis(RequestHandlerSelectors.basePackage("com.csdn.swaggershirojwtredis.controller"))
                .paths(PathSelectors.ant("/GetToken"))
                .build();
      }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("shiro-jwt-redis")
                .description("api")
                // 作者信息
                .contact(new Contact("张川", "https://blog.csdn.net/qq_41595149", "2256222053@qq.com"))
                .version("1.0.0")
                .build();
    }
}

application.properties文件添加是否开启swaager

#是否开启swagger
swagger.enabled=true
1.3,开启swagger,在启动类上添加@EnableSwagger2注解即可
@EnableSwagger2                 //开启swagger

在这里插入图片描述

2,集成shiro

2.1,添加shiro依赖
在pom文件添加依赖
                     <!--shiro-->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.3.2</version>
        </dependency>
2.2,配置shiro
  1. 配置ShiroConfig
package com.csdn.swaggershirojwtredis.config;

import com.csdn.swaggershirojwtredis.comment.JWTFilter;
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.apache.shiro.mgt.SecurityManager;
import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;
/**
 *@description: Shiro配置类
 *
 * @author: 张川
 * @date: 2019-05-17 19:56
 *
 */
@Configuration
public class ShiroConfig {
    @Bean("securityManager")
    public DefaultWebSecurityManager getManager(MyRealm realm) {
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        /*
         * 关闭shiro自带的session,详情见文档
         * http://shiro.apache.org/session-management.html#SessionManagement-StatelessApplications%28Sessionless%29
         */
        DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
        DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator();
        defaultSessionStorageEvaluator.setSessionStorageEnabled(false);
        subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator);
        manager.setSubjectDAO(subjectDAO);
        // 使用自己的realm
        manager.setRealm(realm);
        return manager;
    }

    @Bean("shiroFilter")
    public ShiroFilterFactoryBean factory(DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        // 添加自己的过滤器并且取名为jwt
        Map<String, Filter> filterMap = new HashMap<>();
        filterMap.put("jwt", new JWTFilter());
        factoryBean.setFilters(filterMap);
        factoryBean.setSecurityManager(securityManager);
        factoryBean.setUnauthorizedUrl("/401");

        /*
         * 自定义url规则
         * http://shiro.apache.org/web.html#urls-
         */
        Map<String, String> filterRuleMap = new HashMap<>();
        // 所有请求通过我们自己的JWT Filter
        filterRuleMap.put("/**", "jwt");
        // 访问401和404页面不通过我们的Filter
        filterRuleMap.put("/401", "anon");
        factoryBean.setFilterChainDefinitionMap(filterRuleMap);
        return factoryBean;
    }

    /**
     * 下面的代码是添加注解支持
     */
    /**
     *  开启shiro aop注解支持.
     *  使用代理方式;所以需要开启代码支持;
     */
    @Bean
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){
        return new LifecycleBeanPostProcessor();
    }

    @Bean
    @DependsOn({"lifecycleBeanPostProcessor"})
    public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator(){
        DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        advisorAutoProxyCreator.setProxyTargetClass(true);
        return advisorAutoProxyCreator;
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
}

这里主要是shiro的常规配置,不一样的就是使用我们的JWT Filter
  1. 配置MyRealn
package com.csdn.swaggershirojwtredis.config;

import com.csdn.swaggershirojwtredis.comment.JWTUtil;
import com.csdn.swaggershirojwtredis.comment.JwtToken;
import com.csdn.swaggershirojwtredis.comment.utils.RedisUtils;
import com.csdn.swaggershirojwtredis.entity.Module;
import com.csdn.swaggershirojwtredis.entity.Role;
import com.csdn.swaggershirojwtredis.entity.User;
import com.csdn.swaggershirojwtredis.service.UserService;
import lombok.extern.slf4j.Slf4j;
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 org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义权限控制类
 *
 * @author keriezhang
 * @Date: 2019-05-18 15:15
 * @Description:
 */
@Slf4j
@Service
public class MyRealm extends AuthorizingRealm{

    private UserService userService;
    private RedisUtils redisUtils;
    @Autowired
    public MyRealm(UserService userService, RedisUtils redisUtils) {
        super();
        this.userService=userService;
        this.redisUtils=redisUtils;
    }

    /**
     * 大坑࿰
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值