Spring AOP自定义注解 身份验证

最近碰到APP开发权限验证的问题 用过滤器不能解决某些无需验证的方法 所以最终选择用AOP 解决

代码如下定义一个权限注解

[java]  view plain  copy
  1. package com.thinkgem.jeesite.common.annotation;  
  2.   
  3. import java.lang.annotation.ElementType;  
  4. import java.lang.annotation.Retention;  
  5. import java.lang.annotation.RetentionPolicy;  
  6. import java.lang.annotation.Target;  
  7.   
  8. /** 
  9.  * 权限注解 
  10.  * Created by Hamming on 2016/12/26. 
  11.  */  
  12. @Target(ElementType.METHOD)//这个注解是应用在方法上  
  13. @Retention(RetentionPolicy.RUNTIME)  
  14. public @interface AccessToken {  
  15. /*    String userId(); 
  16.     String token();*/  
  17. }  
获取页面请求中的ID token
[java]  view plain  copy
  1. package com.thinkgem.jeesite.common.aspect;  
  2.   
  3. import com.alibaba.fastjson.JSON;  
  4. import com.thinkgem.jeesite.common.base.ResultApp;  
  5. import com.thinkgem.jeesite.common.service.ApiService;  
  6. import org.aspectj.lang.JoinPoint;  
  7. import org.aspectj.lang.annotation.Aspect;  
  8. import org.aspectj.lang.annotation.Before;  
  9. import org.aspectj.lang.annotation.Pointcut;  
  10. import org.springframework.beans.factory.annotation.Autowired;  
  11. import org.springframework.stereotype.Component;  
  12. import org.springframework.web.bind.annotation.ResponseBody;  
  13. import org.springframework.web.context.request.RequestContextHolder;  
  14. import org.springframework.web.context.request.ServletRequestAttributes;  
  15. import org.springframework.web.context.request.ServletWebRequest;  
  16.   
  17. import javax.servlet.ServletOutputStream;  
  18. import javax.servlet.http.HttpServletRequest;  
  19. import javax.servlet.http.HttpServletResponse;  
  20. import java.io.IOException;  
  21. import java.io.OutputStreamWriter;  
  22. import java.io.PrintWriter;  
  23. import java.util.HashMap;  
  24. import java.util.Map;  
  25.   
  26. /** 
  27.  * app身份验证 
  28.  * Created by Hamming on 2016/12/23. 
  29.  */  
  30. @Aspect  
  31. @Component  
  32. public class AccessTokenAspect {  
  33.   
  34.     @Autowired  
  35.     private ApiService apiService;  
  36.   
  37.     @Before("@annotation(com.thinkgem.jeesite.common.annotation.AccessToken)")  
  38.     @ResponseBody  
  39.     public Object doAccessCheck()throws Throwable {  
  40.         HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();  
  41.   
  42.         String id = request.getParameter("id");  
  43.         String token = request.getParameter("token");  
  44.   
  45.         boolean verify = apiService.verifyToken(id,token);  
  46.         if(verify){  
  47.             return true;  
  48.         }else {  
  49.             ServletRequestAttributes res = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();  
  50.             if (res == null) {  
  51.                 throw new IllegalStateException("当前线程中不存在 Respnose上下文");  
  52.             }  
  53.             HttpServletResponse response = res.getResponse();  
  54.             response.reset();  
  55.             response.setCharacterEncoding("UTF-8");  
  56.             response.setContentType("application/json; charset=utf-8");  
  57.   
  58.             Map re = new HashMap<>();  
  59.             re.put("result",4);  
  60.             re.put("msg","token失效");  
  61.             String json = JSON.toJSONString(re);  
  62.             ServletOutputStream out = response.getOutputStream();  
  63.             OutputStreamWriter ow = new OutputStreamWriter(out,"UTF-8");  
  64.             try {  
  65.                 ow.write(json);  
  66.             } finally {  
  67.                 ow.flush();  
  68.                 ow.close();  
  69.             }  
  70.             return false;  
  71.         }  
  72.     }  
  73. }  


token验证类  存储用到redis

[java]  view plain  copy
  1. package com.thinkgem.jeesite.common.service;  
  2.   
  3. import com.thinkgem.jeesite.common.utils.JedisUtils;  
  4. import io.jsonwebtoken.Jwts;  
  5. import io.jsonwebtoken.SignatureAlgorithm;  
  6. import io.jsonwebtoken.impl.crypto.MacProvider;  
  7. import org.slf4j.Logger;  
  8. import org.slf4j.LoggerFactory;  
  9. import org.springframework.beans.factory.annotation.Autowired;  
  10. import org.springframework.stereotype.Service;  
  11. import org.springframework.transaction.annotation.Transactional;  
  12. import redis.clients.jedis.Jedis;  
  13.   
  14. import java.io.*;  
  15. import java.security.Key;  
  16. import java.util.Date;  
  17.   
  18. /** 
  19.  *token登陆验证 
  20.  * Created by Hamming on 2016/12/23. 
  21.  */  
  22. @Service  
  23. public class ApiService {  
  24.     private static final String at="accessToken";  
  25.   
  26.     public static Key key;  
  27.   
  28. //    private Logger logger = LoggerFactory.getLogger(getClass());  
  29.     /** 
  30.      * 生成token 
  31.      * Key以字节流形式存入redis 
  32.      * 
  33.      * @param date  失效时间 
  34.      * @param appId AppId 
  35.      * @return 
  36.      */  
  37.     public String generateToken(Date date, String appId){  
  38.         Jedis jedis = null;  
  39.         try {  
  40.             jedis = JedisUtils.getResource();  
  41.             byte[] buf = jedis.get("api:key".getBytes());  
  42.             if (buf == null) { // 建新的key  
  43.                 key = MacProvider.generateKey();  
  44.                 ByteArrayOutputStream bao = new ByteArrayOutputStream();  
  45.                 ObjectOutputStream oos = new ObjectOutputStream(bao);  
  46.                 oos.writeObject(key);  
  47.                 buf = bao.toByteArray();  
  48.                 jedis.set("api:key".getBytes(), buf);  
  49.             } else { // 重用老key  
  50.                 key = (Key) new ObjectInputStream(new ByteArrayInputStream(buf)).readObject();  
  51.             }  
  52.   
  53.         }catch (IOException io){  
  54. //            System.out.println(io);  
  55.         }catch (ClassNotFoundException c){  
  56. //            System.out.println(c);  
  57.         }catch (Exception e) {  
  58. //            logger.error("ApiService", "generateToken", key, e);  
  59.         } finally {  
  60.             JedisUtils.returnResource(jedis);  
  61.         }  
  62.   
  63.         String token = Jwts.builder()  
  64.                 .setSubject(appId)  
  65.                 .signWith(SignatureAlgorithm.HS512, key)  
  66.                 .setExpiration(date)  
  67.                 .compact();  
  68.         // 计算失效秒,7889400秒三个月  
  69.         Date temp = new Date();  
  70.         long interval = (date.getTime() - temp.getTime())/1000;  
  71.         JedisUtils.set(at+appId ,token,(int)interval);  
  72.         return token;  
  73.     }  
  74.   
  75.     /** 
  76.      * 验证token 
  77.      * @param appId AppId 
  78.      * @param token token 
  79.      * @return 
  80.      */  
  81.     public boolean verifyToken(String appId, String token) {  
  82.         if( appId == null|| token == null){  
  83.             return false;  
  84.         }  
  85.         Jedis jedis = null;  
  86.         try {  
  87.             jedis = JedisUtils.getResource();  
  88.             if (key == null) {  
  89.                 byte[] buf = jedis.get("api:key".getBytes());  
  90.                 if(buf==null){  
  91.                     return false;  
  92.                 }  
  93.                 key = (Key) new ObjectInputStream(new ByteArrayInputStream(buf)).readObject();  
  94.             }  
  95.             Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody().getSubject().equals(appId);  
  96.             return true;  
  97.         } catch (Exception e) {  
  98. //            logger.error("ApiService", "verifyToken", key, e);  
  99.             return false;  
  100.         } finally {  
  101.             JedisUtils.returnResource(jedis);  
  102.         }  
  103.     }  
  104.   
  105.     /** 
  106.      * 获取token 
  107.      * @param appId 
  108.      * @return 
  109.      */  
  110.     public String getToken(String appId) {  
  111.         Jedis jedis = null;  
  112.         try {  
  113.             jedis = JedisUtils.getResource();  
  114.             return jedis.get(at+appId);  
  115.         } catch (Exception e) {  
  116. //            logger.error("ApiService", "getToken", e);  
  117.             return "";  
  118.         } finally {  
  119.             JedisUtils.returnResource(jedis);  
  120.         }  
  121.     }  
  122. }  

spring aop配置 
[html]  view plain  copy
  1. <!--aop -->  
  2. <!--      扫描注解bean -->  
  3. <context:component-scan base-package="com.thinkgem.jeesite.common.aspect"/>  
  4. <aop:aspectj-autoproxy proxy-target-class="true"/>  


验证权限方法使用 直接用注解就可以了AccessToken

例如

[java]  view plain  copy
  1. package com.thinkgem.jeesite.modules.app.web.pay;  
  2.   
  3. import com.alibaba.fastjson.JSON;  
  4. import com.thinkgem.jeesite.common.annotation.AccessToken;  
  5. import com.thinkgem.jeesite.common.base.ResultApp;  
  6. import com.thinkgem.jeesite.modules.app.service.pay.AppAlipayConfService;  
  7. import org.springframework.beans.factory.annotation.Autowired;  
  8. import org.springframework.stereotype.Controller;  
  9. import org.springframework.web.bind.annotation.RequestMapping;  
  10. import org.springframework.web.bind.annotation.RequestMethod;  
  11. import org.springframework.web.bind.annotation.ResponseBody;  
  12.   
  13. import java.util.HashMap;  
  14. import java.util.Map;  
  15.   
  16. /** 
  17.  * 支付接口 
  18.  * Created by Hamming on 2016/12/27. 
  19.  */  
  20. @Controller  
  21. @RequestMapping(value = "/app/pay")  
  22. public class AppPayModule {  
  23.   
  24.     @Autowired  
  25.     private AppAlipayConfService appAlipayConfService;  
  26.   
  27.     @RequestMapping(value = "/alipay", method = RequestMethod.POST, produces="application/json")  
  28.     @AccessToken  
  29.     @ResponseBody  
  30.     public Object alipay(String orderId){  
  31.         if(orderId ==null){  
  32.             Map re = new HashMap<>();  
  33.             re.put("result",3);  
  34.             re.put("msg","参数错误");  
  35.             String json = JSON.toJSONString(re);  
  36.             return json;  
  37.         }else {  
  38.             return null;  
  39.         }  
  40.     }  
  41. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值