SpringBoot使用AOP实现REST接口简易灵活的安全认证实践

本文将通过AOP的方式实现一个相对更加简易灵活的API安全认证服务。

我们先看实现,然后介绍和分析AOP基本原理和常用术语。

一、Authorized实现

1、定义注解

package com.power.demo.common;

import java.lang.annotation.*;

/*
 * 安全认证
 * */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Authorized {

    String value() default "";

}

这个注解看上去什么都没有,仅仅是一个占位符,用于标志是否需要安全认证。

2、表现层使用注解

@Authorized
    @RequestMapping(value = "/getinfobyid", method = RequestMethod.POST)
    @ApiOperation("根据商品Id查询商品信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "authtoken", required = true, value = "authtoken", dataType =
                    "String"),
    })
    public GetGoodsByGoodsIdResponse getGoodsByGoodsId(@RequestHeader String authtoken, @RequestBody GetGoodsByGoodsIdRequest request) {

        return _goodsApiService.getGoodsByGoodsId(request);

    }

看上去就是在一个方法上加了Authorized注解,其实它也可以作用于类上,也可以类和方法混合使用。

3、请求认证切面

下面的代码是实现灵活的安全认证的关键:

package com.power.demo.controller.tool;

import com.power.demo.common.AppConst;
import com.power.demo.common.Authorized;
import com.power.demo.common.BizResult;
import com.power.demo.service.contract.AuthTokenService;
import com.power.demo.util.PowerLogger;
import com.power.demo.util.SerializeUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;

/**
 * 请求认证切面,验证自定义请求header的authtoken是否合法
 **/
@Aspect
@Component
public class AuthorizedAspect {

    @Autowired
    private AuthTokenService authTokenService;

    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void requestMapping() {
    }

    @Pointcut("execution(* com.power.demo.controller.*Controller.*(..))")
    public void methodPointCut() {
    }

    /**
     * 某个方法执行前进行请求合法性认证 注入Authorized注解 (先)
     */
    @Before("requestMapping() && methodPointCut()&&@annotation(authorized)")
    public void doBefore(JoinPoint joinPoint, Authorized authorized) throws Exception {

        PowerLogger.info("方法认证开始...");

        Class type = joinPoint.getSignature().getDeclaringType();

        Annotation[] annotations = type.getAnnotationsByType(Authorized.class);

        if (annotations != null && annotations.length > 0) {
            PowerLogger.info("直接类认证");
            return;
        }

        //获取当前http请求
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        String token = request.getHeader(AppConst.AUTH_TOKEN);

        BizResult<String> bizResult = authTokenService.powerCheck(token);

        System.out.println(SerializeUtil.Serialize(bizResult));

        if (bizResult.getIsOK() == true) {
            PowerLogger.info("方法认证通过");
        } else {
            throw new Exception(bizResult.getMessage());
        }
    }

    /**
     * 类下面的所有方法执行前进行请求合法性认证 (后)
     */
    @Before("requestMapping() && methodPointCut()")
    public void doBefore(JoinPoint joinPoint) throws Exception {

        PowerLogger.info("类认证开始...");

        Annotation[] annotations = joinPoint.getSignature().getDeclaringType().getAnnotationsByType(Authorized.class);

     
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值