基于API KEY的访问权限控制

APK KEY存储

@Entity
@Data
@Table(name = "authorization_key")
public class AuthorizationKey {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    int id;

    @Column(name = "key_value", length = 64)
    String keyValue;

    @Column(name = "ctime", updatable = false)
    @CreationTimestamp
    Timestamp ctime;

    @Column(name = "mtime")
    @UpdateTimestamp
    Timestamp mtime;
}

切面定义

@Slf4j
@Component
@Aspect
@Order(2)
public class AuthenticationAspect {

    @Pointcut("@annotation(com.xx.xxx.annotation.AuthenticationRequired)")
    public void authenticationPointcut() {
        // 切点定义
    }

    @Autowired
    AuthorizationKeyDAO authorizationKeyDAO;

    public String getAuthorizationKeyFromDatabase() {
        List<AuthorizationKey> lists = authorizationKeyDAO.findAll();
        if (lists.size() > 0) {
            return lists.get(0).getKeyValue();
        }
        return "";
    }

    @Before("authenticationPointcut()")
    public void authentication() throws PermissionDenyException {
        final HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
        String authorization = request.getHeader("Authorization");
        if (!getAuthorizationKeyFromDatabase().equals(authorization)) {
            throw new PermissionDenyException();
        }
    }
}

注解定义

@Target(value = ElementType.METHOD)
public @interface AuthenticationRequired {
}

使用


    @AuthenticationRequired
    @GetMapping("/test")
    public void test() {

    }

测试

Google Chrome 下载 ModHeader 插件进行测试。

猜你喜欢

转载自blog.csdn.net/wuzhong8809/article/details/106083192