欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用AOP进行权限验证

程序员文章站 2022-12-09 18:08:59
首先我们定义一个切入点(匹配com.ed.controller.Seller开头的controller的所有public方法) 然后在进入这些方法之前进行token校验 抛出的异常可定义一个handler进行拦截,并返回自定义的对象给前端 CookieUtil方法 ......

首先我们定义一个切入点(匹配com.ed.controller.seller开头的controller的所有public方法)

@pointcut("execution(public * com.ed.controller.seller*.*(..))")
    public void checktoken() {}

然后在进入这些方法之前进行token校验

@before("checktoken()")
    public void check() {
        servletrequestattributes attributes = (servletrequestattributes) requestcontextholder.getrequestattributes();
        httpservletrequest request = attributes.getrequest();

        //查询cookie
        cookie cookie = cookieutil.get(request, cookieconstant.token);
        if (cookie == null) {
            log.warn("【token校验】cookie中查不到token");
            throw new sellerauthorizeexception(resultenum.token_error);
        }

        //去redis里查询
        string tokenvalue = redistemplate.opsforvalue().get(string.format(redisconstant.token_prefix, cookie.getvalue()));
        if (stringutils.isempty(tokenvalue)) {
            log.warn("【token校验】redis中查不到token");
            throw new sellerauthorizeexception(resultenum.token_error);
        }
    }

抛出的异常可定义一个handler进行拦截,并返回自定义的对象给前端

@controlleradvice
public class sellexceptionhandler {
@exceptionhandler(value = sellerauthorizeexception.class) @responsebody public resultvo handlersellerexception(sellerauthorizeexceptione) { return resultvoutil.error(e.getcode(), e.getmessage()); } }

cookieutil方法

/**
     * 获取cookie
     * @param request
     * @param name
     * @return
     */
    public static cookie get(httpservletrequest request,
                           string name) {
        map<string, cookie> cookiemap = readcookiemap(request);
        if (cookiemap.containskey(name)) {
            return cookiemap.get(name);
        }else {
            return null;
        }
    }

    /**
     * 将cookie封装成map
     * @param request
     * @return
     */
    private static map<string, cookie> readcookiemap(httpservletrequest request) {
        map<string, cookie> cookiemap = new hashmap<>();
        cookie[] cookies = request.getcookies();
        if (cookies != null) {
            for (cookie cookie: cookies) {
                cookiemap.put(cookie.getname(), cookie);
            }
        }
        return cookiemap;
    }