1. 程式人生 > >利用AOP和自定義註解進行Token校驗

利用AOP和自定義註解進行Token校驗

因為公司業務需要每個訪問的方法校驗token,程式碼比較重複,所以就考慮利用Spring的AOP對每個方法進行token校驗。

運用到了aop和自定義註解的知識。

aop配置檔案

      <!-- 自定義註解 -->
    <bean id="authTokenAOPInterceptor" 
    class="cn.test.inter.authTokenAOPInterceptor"/>
	<aop:config proxy-target-class="true">
   
    <aop:pointcut id="authCheckPointcut" expression="@annotation(authToken)"/>
    <aop:aspect ref="authTokenAOPInterceptor" order="1">
        <aop:before method="before" pointcut-ref="authCheckPointcut"/>
    	</aop:aspect>
	</aop:config>

自定義註解程式碼,checktoken是校驗token的方法,setAttribute是將經校驗token的解碼後的資訊存到req中方便control層取用

 String typeid=tokentools.gettypeid(token);
 request.setAttribute("typeid",typeid);

自定義註解程式碼

/*
 * RUNTIME 保留至執行時。所以我們可以通過反射去獲取註解資訊。
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AuthToken {
	String type() default "" ;


}
public class authTokenAOPInterceptor {
//https://www.cnblogs.com/winner-0715/p/6270513.html
//拿到req和res	
	public void before(JoinPoint joinPoint, AuthToken authToken) {
		HttpServletRequest request=SysContent.getRequest();
		String token = request.getParameter("token");
		HttpServletResponse response = SysContent.getResponse();
		String result;
		try {
			if ("authtoken".equals(authToken.type())) {
				checktoken(token);
				String typeid=tokentools.gettypeid(token);
				String phone=tokentools.getphone(token);
				request.setAttribute("typeid",typeid);
				request.setAttribute("phone",phone);
			}
		} catch (BusinessException e) {
			result="{\"state\":\""+e.getMessage()+"\"}";
			e.printStackTrace();
			System.out.println(result);
			Sys.returnDate(response, result);
		}

SysContent 用來存放request和response ,需要在web.xml先配置過濾器

        <filter-name>InitContent</filter-name>
        <filter-class>cn.test.inter.InitContent</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>InitContent</filter-name>
        <url-pattern>*.html</url-pattern>
    </filter-mapping>

在initContent中拿到req和res 放到SysContent

public class InitContent implements Filter {

	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		SysContent.setRequest((HttpServletRequest) arg0);
		SysContent.setResponse((HttpServletResponse) arg1);
		arg2.doFilter(arg0, arg1);
	}
	public void destroy() {
	}
	public void init(FilterConfig arg0) throws ServletException {
	}

}

SysContent程式碼

public class SysContent {
	private static ThreadLocal<HttpServletRequest> requestLocal = new ThreadLocal<HttpServletRequest>();
    private static ThreadLocal<HttpServletResponse> responseLocal = new ThreadLocal<HttpServletResponse>();

    public static HttpServletRequest getRequest() {
        return (HttpServletRequest) requestLocal.get();
    }

    public static void setRequest(HttpServletRequest request) {
        requestLocal.set(request);
    }

    public static HttpServletResponse getResponse() {
        return (HttpServletResponse) responseLocal.get();
    }

    public static void setResponse(HttpServletResponse response) {
        responseLocal.set    (response);
    }

    public static HttpSession getSession() {
        return (HttpSession) ((HttpServletRequest) requestLocal.get()).getSession();
    }

control層程式碼

     	@AuthToken(type="authtoken")
	@RequestMapping(value = "getrealpay")
	public void getrealpay(HttpServletRequest request,
			HttpServletResponse response) {
		Sys.setEncoding(request, response);
		String result = "";
		billEntity sp = null;
		System.out.println(request.getAttribute("typeid"));
		String orderNumber = request.getParameter("orderNumber");
		try {
			sp = bSer.getrealpay(orderNumber);
			result = "{\"data\":[";
			if(sp != null){
				result += "{\"payAccessType\":\"" + 
				string2Json(sp.payAccessType)
				+ "\",\"pay\":\"" + string2Json(sp.pay)+ "\"}";
			}
			result += "]}";
		} catch (BusinessException e) {
			e.printStackTrace();
		}
		Sys.returnDate(response, result);


	}