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 "測試權限注解成功";
    }

會返回 沒有登錄

需要登錄之后,才能請求成功

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM