Home >Java >javaTutorial >How to use Spring AOP to implement interface authentication in SpringBoot

How to use Spring AOP to implement interface authentication in SpringBoot

WBOY
WBOYforward
2023-05-19 18:13:121297browse

Aspect-oriented programming

Aspect-oriented programming can extract logic that has nothing to do with the business but needs to be called jointly by various business modules, and cut it into the code in the form of aspects, thereby reducing the coupling of the code in the system. degree, reducing duplicate code.

Spring AOP implements aspect-oriented programming through pre-compilation and dynamic proxies during runtime

The underlying principle of AOP is implemented

The underlying use of AOP is dynamic The proxy completes the requirements and generates proxy classes for classes that need to be enhanced. There are two ways to generate proxy classes. For the proxy class (that is, the class that needs to be enhanced), If:

  • If the interface is implemented and JDK dynamic proxy is used, the generated proxy class will use its interface. If the interface is not implemented,

  • If CGlib dynamic proxy is used, the generated proxy class will be Integrated proxied class

AOP related terms

  • Connection point:In the proxied (enhanced) class Method

  • Entry point:Method that actually needs to be enhanced

  • Notification: Logic code to be enhanced

    • Pre-notification: Executed before the execution of the main function

    • Post notification: Executed after the execution of the theme function

    • Surround notification: Executed before and after the execution of the main function

    • Exception notification: Executed when an exception occurs in the execution of the theme function

    • Final notification:The main function will be executed regardless of whether the execution is successful

  • Aspect: The combination of entry point and aspect, that is, the enhanced method and enhanced function form the aspect

Related comments and pointcut expressions

Annotations:

  • @Aspect: Declare that a certain class is an aspect , write notifications and entry points

  • @Before: Corresponding pre-notification

  • @AfterReturning: Corresponding to post notification

  • @Around: Corresponding to surrounding notification

  • @AfterThrowing: Corresponding exception notification

  • @After: Corresponding to final notification

  • @Pointcut: Statement Pointcuts, marking them on a method can make the expression more concise

Use pointcut expressions to declare pointcuts

  • execution([Permission modifier][Return type][Full class path].[Method name][Parameter list type])

execution(* com.xxx.ABC. add()), enhance the method of ABC class

Implement interface authentication

1. Configure yml file

Configure interface authentication account

account:
  infos:
    - account: xinchao
      secret: admin

2. Read the account and password configuration

@Data
public class SecretInfo {
    private String account;
    private String secret;
}

3. Write the interface authentication method

@Configuration
@ConfigurationProperties("account")
public class SecretConfig {
    private List<SecretInfo> infos;

    private Map<String, SecretInfo> map;

    private Map<String, TokenInfo> tokenMap = new HashMap<>();

    public void setInfos(List<SecretInfo> infos) {
        this.infos = infos;
        map = infos.stream().collect(Collectors.toMap(SecretInfo::getAccount, Function.identity()));
    }

    public synchronized String getToken(String account, String secret) {
        SecretInfo info = map.get(account);
        if (info == null) {
            throw new BusinessException("无效账号");
        }
        if (!StringUtils.equals(info.getSecret(), secret)) {
            throw new BusinessException("无效密码");
        }
        TokenInfo tokenInfo = tokenMap.get(account);
        if (tokenInfo != null && tokenInfo.getToken() != null) {
            return tokenInfo.getToken();
        }
        tokenInfo = new TokenInfo();
        String uuid = UUID.randomUUID().toString();
        tokenInfo.setToken(uuid);
        tokenInfo.setCreateDate(LocalDateTime.now());
        tokenInfo.setExpireDate(LocalDateTime.now().plusHours(2));
        tokenMap.put(account,tokenInfo);
        return tokenInfo.getToken();
    }

    public boolean checkCaptcha(String captcha) {
        return tokenMap.values().stream().anyMatch(e->StringUtils.equals(e.getToken(),captcha));
    }
}
@Data
public class TokenInfo {
    private LocalDateTime createDate;
    private LocalDateTime expireDate;
    private String token;

    public String getToken() {
        if (LocalDateTime.now().isBefore(expireDate)) {
            return token;
        }
        return null;
    }

    public boolean verification(String token) {
        return Objects.equals(this.token, token);
    }
}

4. Write the AOP

First , write an annotation to indicate that authentication is not required

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CaptchaIgnoreAop {
}
@Slf4j
@Aspect
@Component
@Order(2)
public class CaptchaAop {

    @Value("${spring.profiles.active:dev}")
    private String env;

    @Autowired
    private SecretConfig config;

    @Pointcut("execution(public * com.herenit.phsswitch.controller.impl..*.*(..))" +
            "&&@annotation(org.springframework.web.bind.annotation.PostMapping)" +
            "&&!@annotation(com.herenit.phsswitch.aop.CaptchaIgnoreAop)")
    public void tokenAop() {
    }

    @Around("tokenAop()")
    public Object doBefore(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        if (args.length == 0 || !(args[0] instanceof RequestWrapper)
                || "test,dev".contains(env)) {
            log.info("当前环境无需校验token");
            return joinPoint.proceed();
        }
        String captcha = ((RequestWrapper) joinPoint.getArgs()[0]).getCaptcha();
        if (!config.checkCaptcha(captcha)) {
            throw new BusinessException("captcha无效");
        }
        return joinPoint.proceed();
    }

}

5. Write an interface test

@PostMapping("/login")
@CaptchaIgnoreAop
public ResponseWrapper login(@RequestBody JSONObject userInfo) {
    String token = config.getToken(userInfo.getString("loginName")
            , userInfo.getString("password"));
    JSONObject result = new JSONObject();
    result.put("platformAccessToken", token);
    return ResponseWrapper.success(result);
}

Use this interface to create a token in memory and return it to the front end . Later, we can pass in this token for authentication when adjusting other interfaces. The location passed in is the captcha field

public class RequestWrapper<T> implements Serializable {

    private static final long serialVersionUID = 8988706670118918321L;
    public RequestWrapper() {
        super();
    }

    private T args;

    private String captcha;

    private String funcode;

    public T getArgs() {
        return args;
    }

    public void setArgs(T args) {
        this.args = args;
    }

    public String getCaptcha() {
        return captcha;
    }

    public void setCaptcha(String captcha) {
        this.captcha = captcha;
    }

    public String getFuncode() {
        return funcode;
    }

    public void setFuncode(String funcode) {
        this.funcode = funcode;
    }
}

The above is the detailed content of How to use Spring AOP to implement interface authentication in SpringBoot. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete