登录鉴权

Meteor 2024-01-09 09:49:10
Categories: Tags:

本篇文章的目的是利用注解和AOP实现简单的登录鉴权,先简述整个流程:使用的方式就是在Controller中的方法上添加 @Auth 注解,
注解中用type属性标明是哪种鉴权方式,目前只支持比较简单数据库用户名和密码校验

首先定义注解

Auth


@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Auth {
int type() default 0;
}

type表示需不需要登录,0表示不需要,1表示需要,为了统一这种状态码,创建一个通用类

CommonConstants


public class CommonConstants {
public static final int NEED_LOGIN = 1;
public static final int NONE = 0;
}

接下来定义切面


@Component
@Aspect
public class AuthorityAspect {
@Around("@annotation(auth)")
public Object around(ProceedingJoinPoint pjp, Auth auth) throws Throwable {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
String userName = request.getHeader("userName");
String password = request.getHeader("password");
AuthEnum check = authCheck(auth.type(), userName, password);
if(check.getCode()==1001){
return pjp.proceed();
}
return "登录失败";
}
private AuthEnum authCheck(int type, String userName, String password){
if(type==CommonConstants.NONE){
return AuthEnum.LOGIN_SUCCESS;
}
if(Strings.isEmpty(userName) || Strings.isEmpty(password)){
return AuthEnum.LOGIN_FAILED;
}
if(type==CommonConstants.NEED_LOGIN){
//此处调用对应的service检查用户名和密码是否正确
// userService.login(userName, password);
System.out.println("登录成功");
return AuthEnum.LOGIN_SUCCESS;
}
return AuthEnum.LOGIN_FAILED;
}
}

过程中简化了用户名和密码的验证,同时使用了下面的枚举类来统一返回验证结果

public enum AuthEnum {
LOGIN_SUCCESS(1001, "登录成功"),
LOGIN_FAILED(1002,"登录失败");
@Getter
private int code;
@Getter
private String msg;
AuthEnum(int code, String msg){
this.code = code;
this.msg = msg;
}
}

以下是其使用方法,只需要在方法上加上注解即可生效

@RestController
public class LoginController {

@PostMapping("/login")
@Auth(type = CommonConstants.NEED_LOGIN)
public boolean getResult(){
return true;
}
}