首页 > 其他分享 >Swagger添加全局token 验证

Swagger添加全局token 验证

时间:2023-03-08 22:59:01浏览次数:43  
标签:springfox return documentation request token import 全局 Swagger

1.过滤器代码实现

package com.pab.data.datasource.filter;

import com.pab.data.datasource.common.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class LoginCheckFilter implements Filter {
    // 路径匹配器,支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        // 定义不需要处理的请求的路径
        String[] urls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                "/wabjars/**",
                "/swagger-resources/**",
                "/v3/api-docs",
                "/doc.html",
                "/webjars/**",
                "/swagger-ui/**",
        };
        boolean check = check(urls, requestURI);
        // 如果不需要处理,放行
        if (check) {
            log.info("本次请求{}, 不需要处理", request.getRequestURI());
            filterChain.doFilter(request, response);
            return;
        }
        //获取token
        if (request.getHeader("tk") != null){
            String token = request.getHeader("tk");
            BaseContext.setToken(token);
            log.info("用户登录,token: {}", token);
            filterChain.doFilter(request, response);
            return;
        }
        // 4-1.后台判断登录状态,如果已登录,放行
        if (request.getSession().getAttribute("employee") != null) {
            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);
            log.info("用户已登录, id: {}", empId);
            filterChain.doFilter(request, response);
            return;
        }

        // 4-2.移动端判断登录状态,如果已登录,放行
        if (request.getSession().getAttribute("user") != null) {
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            log.info("移动端用户已登录, id: {}", userId);
            filterChain.doFilter(request, response);
            return;
        }
        // 未登录
        log.info("本次请求{} 用户未登录", request.getRequestURI());
        response.getWriter().write("NOTLOGIN");
    }

    /**
     * 路径匹配,检查本次请求是否需要放行
     *
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}

2. swagger配置代码

package com.pab.data.datasource.config;

import com.google.common.collect.Lists;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.schema.ScalarType;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.Collections;
import java.util.List;

/**
 * 注释掉swagger2,升级为swagger3
 */
@Configuration
@EnableOpenApi
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.pab.data.datasource"))
                .paths(PathSelectors.any())
                .build()
                //添加全局token认证
                .globalRequestParameters(Collections.singletonList(new springfox.documentation.builders.RequestParameterBuilder()
                                .name("tk")
                                .description("token")
                                .in(ParameterType.HEADER)
                                .required(true)
                                .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
                                .build()))
               .securitySchemes(securitySchemes())
                .securityContexts(securityContexts());
    }

    /**
     * 配置认证模式
     * @return
     */
    private List<SecurityScheme> securitySchemes() {
        return Lists.newArrayList(new ApiKey("Authorization", "Authorization", "header"));
    }

    /**
     * 配置认证上下文
     */
    private List<SecurityContext> securityContexts() {
        return Lists.newArrayList(SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.any())
                .build());
    }

    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return Lists.newArrayList(new SecurityReference("Authorization", authorizationScopes));
    }

    /**
     * 项目信息
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("数据源管理项目 RESTful APIs")
                .version("1.0")
                .build();
    }
}

 

标签:springfox,return,documentation,request,token,import,全局,Swagger
From: https://www.cnblogs.com/gylhaut/p/17196551.html

相关文章