com.wuxiansen.beehive.core.security.SecurityAspect.java Source code

Java tutorial

Introduction

Here is the source code for com.wuxiansen.beehive.core.security.SecurityAspect.java

Source

/**
 * Copyright (c) 1996, 2016, WUXIANSEN and/or its affiliates. All rights reserved. WUXIANSEN
 * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */
package com.wuxiansen.beehive.core.security;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

import com.wuxiansen.beehive.core.context.WebContext;
import com.wuxiansen.beehive.core.exception.TokenException;
import com.wuxiansen.beehive.common.util.StringUtil;

/**
 *  token 
 * 
 * @author <a href="mailto:dayanwp@163.com">peng.wu</a>
 * @see com.wuxiansen.beehive.core.security
 * @since 1.0
 */
public class SecurityAspect {

    private static final String DEFAULT_TOKEN_NAME = "X-Token";

    private TokenManager tokenManager;
    private String tokenName;

    public void setTokenManager(TokenManager tokenManager) {
        this.tokenManager = tokenManager;
    }

    public void setTokenName(String tokenName) {
        if (StringUtil.isEmpty(tokenName)) {
            tokenName = DEFAULT_TOKEN_NAME;
        }
        this.tokenName = tokenName;
    }

    public Object execute(ProceedingJoinPoint pjp) throws Throwable {
        // ?
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        Method method = methodSignature.getMethod();
        // 
        if (method.isAnnotationPresent(IgnoreSecurity.class)) {
            return pjp.proceed();
        }

        //  request header ?? token
        String token = WebContext.getRequest().getHeader(tokenName);
        //  token 
        if (!tokenManager.checkToken(token)) {
            String message = String.format("token [%s] is invalid", token);
            throw new TokenException(message);
        }
        // 
        return pjp.proceed();
    }
}