Swagger实现登录查看Api

/ SwaggerSpring / 没有评论 / 79浏览

1、登录页面添加Cookie

工具:js-cookie

 Cookies.set('token', data.data.token.token);

2、后端添加过滤器

package filter;

import cn.hutool.core.util.ArrayUtil;

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

public class RequestAuthFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        // 开始进入请求地址拦截
        boolean flag = true;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        Cookie[] cookies = request.getCookies();
        if (ArrayUtil.isNotEmpty(cookies)) {
            int length = cookies.length;
            for (int i = 0; i < length; i++) {
                Cookie cookie = cookies[i];
                String name = cookie.getName();
                // 可在此处作Token校验
                if (name.equals("token")) {
                    flag = false;
                } else {
                    continue;
                }
            }
        }

        if (flag) {
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            String fullUrl = request.getContextPath() + "/user/login";
            response.sendRedirect(fullUrl);
        } else {
            chain.doFilter(servletRequest, servletResponse);
        }
    }
}

3、注册过滤器

@Bean
public FilterRegistrationBean FilterRegistration() {
    FilterRegistrationBean registration = new FilterRegistrationBean();

    registration.setDispatcherTypes(DispatcherType.REQUEST);
    // 注入过滤器
    registration.setFilter(new RequestAuthFilter());
    // 过滤器名称
    registration.setName("RequestAuthFilter");
    // 拦截规则
    List<String> paths = Lists.newArrayList();
    paths.add("/");
    paths.add("/v2/*");
    paths.add("/swagger-ui.html");
    paths.add("/swagger-resources");
    paths.add("/swagger-resources/configuration/ui");
    registration.setUrlPatterns(paths);
    // 是否自动注册 false 取消Filter的自动注册
    registration.setEnabled(true);
    // 过滤器顺序
    registration.setOrder(Integer.MAX_VALUE - 2);

    return registration;
}