在spring项目中 我想用AOP 来进行权限控制
我自定义了注解
public @interface AccessToken
想通过注解 进行AOP权限验证的方法
权限验证用到ID和token
spring AOP 应该用什么注解 验证用户 验证失败 不执行后面的操作
自定义异常吗?
package com.thinkgem.jeesite.common.aspect;
import com.thinkgem.jeesite.common.base.ResultApp;
import com.thinkgem.jeesite.common.service.ApiService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* app身份验证
* Created by Hamming on 2016/12/23.
*/
@Aspect
@Component
public class AccessTokenAspect {
@Autowired
private ApiService apiService;
@Before("@annotation(com.thinkgem.jeesite.common.annotation.AccessToken)")
@ResponseBody
public void doAccessCheck()throws Throwable {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
ServletWebRequest servletWebRequest = new ServletWebRequest(request);
HttpServletResponse response = servletWebRequest.getResponse();
String id = request.getParameter("id");
String token = request.getParameter("token");
boolean verify = apiService.verifyToken(id,token);
if(!verify){
//页面如何跳转 返回json
}
}
}
自定义了注解 但是 身份严重失败 怎么跳转页面 返回json数据 不执行后面的方法呢???
问题已经解决
代码如下
/**
* app身份验证
* Created by Hamming on 2016/12/23.
*/
@Aspect
@Component
public class AccessTokenAspect {
@Autowired
private ApiService apiService;
@Before("@annotation(com.thinkgem.jeesite.common.annotation.AccessToken)")
@ResponseBody
public Object doAccessCheck()throws Throwable {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String id = request.getParameter("id");
String token = request.getParameter("token");
boolean verify = apiService.verifyToken(id,token);
if(verify){
return true;
}else {
ServletRequestAttributes res = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (res == null) {
throw new IllegalStateException("当前线程中不存在 Respnose上下文");
}
HttpServletResponse response = res.getResponse();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
Map re = new HashMap<>();
re.put("result",4);
re.put("msg","token失效");
String json = JSON.toJSONString(re);
response.getWriter().write(json);
return false;
}
}
}
/**
* 权限注解
* Created by Hamming on 2016/12/26.
*/
@Target(ElementType.METHOD)//这个注解是应用在方法上
@Retention(RetentionPolicy.RUNTIME)
public @interface AccessToken {
/* String userId();
String token();*/
}