springboot-vue-自定义注解限制接口调用

新建注解:

/**
 * 想要权限拦截的接口就加上这个注解
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface EnableAuth {
}

编写实现 ApplicationContextAware 的类:

Spring容器已启动就执行 setApplicationContext 方法

/**
 * 项目一启动,就调用这个方法获取所有需要权限拦截的接口,放到checkApis中
 */
@Component
@Configuration
public class ApiAuthDataInit implements ApplicationContextAware {

    /** 存放需要权限拦截的接口uri */
    public static List<String> checkApis = new ArrayList<>();

    /**
     * 获取所有带有@RestController注解的类,
     * 并获取该类下所有带有@EnableAuth注解的方法,
     * 获取该方法@RequestMapping的uri路径,
     * 将uri存入checkApis中
     */
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        Map<String, Object> beanMap = ctx.getBeansWithAnnotation(RestController.class);
        if (beanMap != null) {
            for (Object bean : beanMap.values()) {
                Class<?> clz = bean.getClass();
                Method[] methods = clz.getMethods();
                for (Method method : methods) {
                    if (method.isAnnotationPresent(EnableAuth.class)) {
                        String uri = getApiUri(clz, method);
                        System.err.println(uri);
                        checkApis.add(uri);
                    }
                }
            }
        }
    }

    private String getApiUri(Class<?> clz, Method method) {
        StringBuilder uri = new StringBuilder();
        uri.append(clz.getAnnotation(RequestMapping.class).value()[0]);
        if (method.isAnnotationPresent(GetMapping.class)) {
            uri.append(method.getAnnotation(GetMapping.class).value()[0]);
        } else if (method.isAnnotationPresent(PostMapping.class)) {
            uri.append(method.getAnnotation(PostMapping.class).value()[0]);
        } else if (method.isAnnotationPresent(RequestMapping.class)) {
            uri.append(method.getAnnotation(RequestMapping.class).value()[0]);
        }
        return uri.toString();
    }

}

编写api拦截器:

package com.tangzhe.filter;

import com.alibaba.fastjson.JSONObject;
import com.tangzhe.util.JWTUtils;
import com.tangzhe.util.LoginInfoUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ApiFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {
        
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        String authorization = req.getHeader("Authorization");

        // 判断checkApis中是否包含当前请求的uri
        if (ApiAuthDataInit.checkApis.contains(req.getRequestURI())) {
            // 获取当前登录用户
            String userId = LoginInfoUtils.getLoginUserId(req);
            if (userId == null) {
                PrintWriter writer = resp.getWriter();
                String res = "请先登录";
                writer.write(res);
                writer.flush();
                return;
            }
        }

        // 判断token值是否合法
        if (StringUtils.isNotBlank(authorization)) {
            JWTUtils.JWTResult result = JWTUtils.getInstance().checkToken(authorization);
            if (!result.isStatus()) {
                // 非法请求
                PrintWriter writer = resp.getWriter();
                String res = JSONObject.toJSONString(result);
                writer.write(res);
                writer.flush();
                return;
            }
        }

        chain.doFilter(request, response);
    }

    public void destroy() {
        
    }

}

编写测试@EnableAuth 注解的接口:

  @GetMapping("/testEnableAuth")
    public String testEnableAuth() {
        return "测试权限注解成功";
    }

前端项目页面修改:

        <!-- 测试@EnableAuth注解 -->
        <div>
            <button @click="testEnableAuth">测试EnableAuth注解</button>
        </div>    

...
testEnableAuth: function() {
axios.get('http://localhost:8889/user/testEnableAuth')
.then(function (response) {
alert(response.data);
})
.catch(function (error) {
console.log(error);
});
}

不打@EnableAuth注解测试:

打上@EnableAuth注解测试:

    @EnableAuth
    @GetMapping("/testEnableAuth")
    public String testEnableAuth() {
        return "测试权限注解成功";
    }

会返回 没有登录

需要登录之后,才能请求成功

原文地址:https://www.cnblogs.com/tangzhe/p/9229415.html