asia.gkc.vneedu.authorization.interceptor.AuthorizationInterceptor.java Source code

Java tutorial

Introduction

Here is the source code for asia.gkc.vneedu.authorization.interceptor.AuthorizationInterceptor.java

Source

/*
 * Copyright 2016 Jakes Lee
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package asia.gkc.vneedu.authorization.interceptor;

import asia.gkc.vneedu.authorization.annotation.RequireLogin;
import asia.gkc.vneedu.common.Constants;
import asia.gkc.vneedu.common.ResultModel;
import asia.gkc.vneedu.common.ResultStatus;
import asia.gkc.vneedu.utils.IdentityUtil;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.ExpiredJwtException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * File Name: AuthorizationInterceptor.java
 * Function:
 *
 * @author jakes.
 * @version 1.0
 * @DateTime 4/5/16 3:56 PM
 */

public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
    private final Log logger = LogFactory.getLog(this.getClass());

    /**
     * This implementation always returns {@code true}.
     *
     * @param request
     * @param response
     * @param handler
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // ?
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        // ???
        if (method.getAnnotation(RequireLogin.class) == null) {
            return true;
        }

        // ??
        String authorization = request.getHeader(Constants.AUTHORIZATION);

        // ?
        if (authorization == null) {
            return exitWithHeaderError(response);
        }

        String[] auths = authorization.split(" ");
        if (!auths[0].equals("token") || (auths.length > 1 && StringUtils.isEmpty(auths[1]))) {
            return exitWithHeaderError(response);
        }

        // ?Token
        try {
            logger.debug(auths[1]);
            String uuid = IdentityUtil.verifyToken(auths[1]);
            logger.debug(uuid);

            request.setAttribute(Constants.USER_ID_IN_REQUEST, uuid);
        } catch (ExpiredJwtException e) {
            return exitWithExpiredAuth(response);
        } catch (Exception e) {
            return exitWithTokenError(response);
        }

        return true;
    }

    /**
     * 
     * @param response - ?
     * @param resultStatus ?
     * @return
     * @throws Exception
     */
    private boolean exitWithError(HttpServletResponse response, ResultStatus resultStatus) throws Exception {
        ResultModel resultModel = ResultModel.ERROR(resultStatus);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(resultModel));
        return false;
    }

    /**
     * 
     * @param response - ?
     * @return
     * @throws Exception
     */
    private boolean exitWithHeaderError(HttpServletResponse response) throws Exception {
        return exitWithError(response, ResultStatus.AUTHORIZATION_HEADER_ERROR);
    }

    /**
     * ?
     * @param response - ?
     * @return
     * @throws Exception
     */
    private boolean exitWithExpiredAuth(HttpServletResponse response) throws Exception {
        return exitWithError(response, ResultStatus.AUTHORIZATION_TIMEOUT);
    }

    /**
     * Token
     * @param response - ?
     * @return
     * @throws Exception
     */
    private boolean exitWithTokenError(HttpServletResponse response) throws Exception {
        return exitWithError(response, ResultStatus.AUTHORIZATION_TOKEN_ERROR);
    }
}