Home  >  Article  >  Java  >  Three ways to implement interface verification in Java

Three ways to implement interface verification in Java

黄舟
黄舟Original
2017-10-19 09:29:081915browse

This article mainly introduces the three ways to implement interface verification in Java. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor and take a look.

This article introduces three ways to implement interface verification in Java, mainly including AOP and MVC interceptors. I share them with you. The details are as follows:

Method 1: AOP

The code defines a permission annotation as follows


package com.thinkgem.jeesite.common.annotation; 
 
import java.lang.annotation.ElementType; 
import java.lang.annotation.Retention; 
import java.lang.annotation.RetentionPolicy; 
import java.lang.annotation.Target; 
 
/** 
 * 权限注解 
 * Created by Hamming on 2016/12/ 
 */ 
@Target(ElementType.METHOD)//这个注解是应用在方法上 
@Retention(RetentionPolicy.RUNTIME) 
public @interface AccessToken { 
/*  String userId(); 
  String token();*/ 
}

Get the ID in the page request token


@Aspect 
@Component 
public class AccessTokenAspect { 
 
  @Autowired 
  private ApiService apiService; 
 
  @Around("@annotation(com.thinkgem.jeesite.common.annotation.AccessToken)") 
  public Object doAccessCheck(ProceedingJoinPoint pjp) 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){ 
      Object object = pjp.proceed(); //执行连接点方法 
      //获取执行方法的参数 
 
      return object; 
    }else { 
      return ResultApp.error(3,"token失效"); 
    } 
  } 
}

token verification class storage uses redis


package com.thinkgem.jeesite.common.service; 
 
import com.thinkgem.jeesite.common.utils.JedisUtils; 
import io.jsonwebtoken.Jwts; 
import io.jsonwebtoken.SignatureAlgorithm; 
import io.jsonwebtoken.impl.crypto.MacProvider; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Service; 
import org.springframework.transaction.annotation.Transactional; 
import redis.clients.jedis.Jedis; 
 
import java.io.*; 
import java.security.Key; 
import java.util.Date; 
 
/** 
 *token登陆验证 
 * Created by Hamming on 2016/12/ 
 */ 
@Service 
public class ApiService { 
  private static final String at="accessToken"; 
 
  public static Key key; 
 
//  private Logger logger = LoggerFactorygetLogger(getClass()); 
  /** 
   * 生成token 
   * Key以字节流形式存入redis 
   * 
   * @param date 失效时间 
   * @param appId AppId 
   * @return 
   */ 
  public String generateToken(Date date, String appId){ 
    Jedis jedis = null; 
    try { 
      jedis = JedisUtils.getResource(); 
      byte[] buf = jedis.get("api:key".getBytes()); 
      if (buf == null) { // 建新的key 
        key = MacProvider.generateKey(); 
        ByteArrayOutputStream bao = new ByteArrayOutputStream(); 
        ObjectOutputStream oos = new ObjectOutputStream(bao); 
        oos.writeObject(key); 
        buf = bao.toByteArray(); 
        jedis.set("api:key".getBytes(), buf); 
      } else { // 重用老key 
        key = (Key) new ObjectInputStream(new ByteArrayInputStream(buf)).readObject(); 
      } 
 
    }catch (IOException io){ 
//      System.out.println(io); 
    }catch (ClassNotFoundException c){ 
//      System.out.println(c); 
    }catch (Exception e) { 
//      logger.error("ApiService", "generateToken", key, e); 
    } finally { 
      JedisUtils.returnResource(jedis); 
    } 
 
    String token = Jwts.builder() 
        .setSubject(appId) 
        .signWith(SignatureAlgorithm.HS512, key) 
        .setExpiration(date) 
        .compact(); 
    // 计算失效秒,7889400秒三个月 
    Date temp = new Date(); 
    long interval = (date.getTime() - temp.getTime())/1000; 
    JedisUtils.set(at+appId ,token,(int)interval); 
    return token; 
  } 
 
  /** 
   * 验证token 
   * @param appId AppId 
   * @param token token 
   * @return 
   */ 
  public boolean verifyToken(String appId, String token) { 
    if( appId == null|| token == null){ 
      return false; 
    } 
    Jedis jedis = null; 
    try { 
      jedis = JedisUtils.getResource(); 
      if (key == null) { 
        byte[] buf = jedis.get("api:key".getBytes()); 
        if(buf==null){ 
          return false; 
        } 
        key = (Key) new ObjectInputStream(new ByteArrayInputStream(buf))readObject(); 
      } 
      Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody().getSubject().equals(appId); 
      return true; 
    } catch (Exception e) { 
//      logger.error("ApiService", "verifyToken", key, e); 
      return false; 
    } finally { 
      JedisUtils.returnResource(jedis); 
    } 
  } 
 
  /** 
   * 获取token 
   * @param appId 
   * @return 
   */ 
  public String getToken(String appId) { 
    Jedis jedis = null; 
    try { 
      jedis = JedisUtils.getResource(); 
      return jedis.get(at+appId); 
    } catch (Exception e) { 
//      logger.error("ApiService", "getToken", e); 
      return ""; 
    } finally { 
      JedisUtils.returnResource(jedis); 
    } 
  } 
}

spring aop configuration


 
 
 
 

To verify permissions, just use annotations directly. AccessToken

For example,


package com.thinkgem.jeesite.modules.app.web.pay; 
 
import com.alibaba.fastjson.JSON; 
import com.thinkgem.jeesite.common.annotation.AccessToken; 
import com.thinkgem.jeesite.common.base.ResultApp; 
import com.thinkgem.jeesite.modules.app.service.pay.AppAlipayConfService; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Controller; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.ResponseBody; 
 
import java.util.HashMap; 
import java.util.Map; 
 
/** 
 * 支付接口 
 * Created by Hamming on 2016/12/ 
 */ 
@Controller 
@RequestMapping(value = "/app/pay") 
public class AppPayModule { 
 
  @Autowired 
  private AppAlipayConfService appAlipayConfService; 
 
  @RequestMapping(value = "/alipay", method = RequestMethodPOST, produces="application/json") 
  @AccessToken 
  @ResponseBody 
  public Object alipay(String orderId){ 
    if(orderId ==null){ 
      Map re = new HashMap<>(); 
      re.put("result",3); 
      re.put("msg","参数错误"); 
      String json = JSONtoJSONString(re); 
      return json; 
    }else { 
      return null; 
    } 
  } 
}

method Two: AOP method 2

#1. Define a query parent class, which contains two attributes: authToken and usedId. All query parameters that need to be verified for user requests are inherited. The reason why this query parent class has this userId is because after we verify the user, we need to obtain some user data based on the user ID, so we backfill this parameter at the AOP layer, so that it will not affect the previous Code logic (this may be related to my business requirements)


public class AuthSearchVO {
  
  public String authToken; //校验字符串
  
  public Integer userId; //APP用户Id
  
  public final String getAuthToken() {
    return authToken;
  }

  public final void setAuthToken(String authToken) {
    this.authToken = authToken;
  }

  public final Integer getUserId() {
    return userId;
  }

  public final void setUserId(Integer userId) {
    this.userId = userId;
  }

  @Override
  public String toString() {
    return "SearchVO [authToken=" + authToken + ", userId=" + userId + "]";
  }

}

2. Define a method-level annotation, and add this annotation to all requests that need to be verified. Used for AOP interception (of course you can also intercept requests from all controllers)


@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AuthToken {
String type();
}

3. AOP processing, the reason why annotations are passed in as parameters is because Considering that there may be multiple APP verifications, you can use the type attribute of the annotation to distinguish


public class AuthTokenAOPInterceptor {

@Resource
private AppUserService appUserService;

private static final String authFieldName = "authToken";
private static final String userIdFieldName = "userId";

public void before(JoinPoint joinPoint, AuthToken authToken) throws Throwable{

  Object[] args = joinPoint.getArgs(); //获取拦截方法的参数
  boolean isFound = false;
  for(Object arg : args){
    if(arg != null){
      Class clazz = arg.getClass();//利用反射获取属性值
      Field[] fields = clazz.getDeclaredFields();
      int authIndex = -1;
      int userIdIndex = -1;
      for(int i = 0; i < fields.length; i++){
        Field field = fields[i];
        field.setAccessible(true);
        if(authFieldName.equals(field.getName())){//包含校验Token
          authIndex = i;
        }else if(userIdFieldName.equals(field.getName())){//包含用户Id
          userIdIndex = i;
        }
      }

      if(authIndex >= 0 & userIdIndex >= 0){
        isFound = true;
        authTokenCheck(fields[authIndex], fields[userIdIndex], arg, authToken);//校验用户
        break;
      }
    }
  }
  if(!isFound){
    throw new BizException(ErrorMessage.CHECK_AUTHTOKEN_FAIL);
  }

}

private void authTokenCheck(Field authField, Field userIdField, Object arg, AuthToken authToken) throws Exception{
  if(String.class == authField.getType()){
    String authTokenStr = (String)authField.get(arg);//获取到校验Token
    AppUser user = appUserService.getUserByAuthToken(authTokenStr);
    if(user != null){
      userIdField.set(arg, user.getId());
    }else{
      throw new BizException(ErrorMessage.CHECK_AUTHTOKEN_FAIL);
    }
  }

}
}

4. The last step is to configure this AOP in the configuration file (because Our spring version is slightly different from the aspect version, so the annotation-based method cannot be used)




  
  
    
  

Finally, the test code is given, such code is much more elegant


@RequestMapping(value = "/appointments", method = { RequestMethod.GET })
@ResponseBody
@AuthToken(type="disticntApp")
public List getAppointments(AppointmentSearchVo appointmentSearchVo) {
  List appointments = appointmentService.getAppointment(appointmentSearchVo.getUserId(), appointmentSearchVo);
  return appointments;
}

Method three: MVC interceptor

Server:

Splice everything except token Parameters, finally splice token_key, do MD5, and compare with token parameters

If the token comparison fails, return status code 500


public class APIInterceptor extends HandlerInterceptorAdapter { 
 
  @Override 
  public boolean preHandle(HttpServletRequest request, 
      HttpServletResponse response, Object handler) throws Exception { 
    Log.info(request); 
     
    String token = request.getParameter("token"); 
     
    // token is not needed when debug 
    if(token == null) return true; // !! remember to comment this when deploy on server !! 
     
    Enumeration paraKeys = request.getParameterNames(); 
    String encodeStr = ""; 
    while (paraKeys.hasMoreElements()) { 
      String paraKey = (String) paraKeys.nextElement(); 
      if(paraKey.equals("token"))  
        break; 
      String paraValue = request.getParameter(paraKey); 
      encodeStr += paraValue; 
    } 
    encodeStr += Default.TOKEN_KEY; 
    Log.out(encodeStr); 
     
    if ( ! token.equals(DigestUtils.md5Hex(encodeStr))) { 
      response.setStatus(500); 
      return false; 
    } 
     
    return true; 
  } 
 
  @Override 
  public void postHandle(HttpServletRequest request, 
      HttpServletResponse response, Object handler, 
      ModelAndView modelAndView) throws Exception { 
    Log.info(request); 
  } 
 
  @Override 
  public void afterCompletion(HttpServletRequest request, 
      HttpServletResponse response, Object handler, Exception ex) 
      throws Exception { 
     
  } 
}

spring-config.xml Add


 
   
     
     
   

to the configuration. Client:

Splice all the parameters of the request interface, and finally splice token_key, do MD5, and use it as the token parameter

Request example: http://127.0.0.1:8080/interface/api?key0=param0&key1=param1&token=md5(concat(param0, param1))

api test page, using Bootstrap and AngularJS, There is also a js hex_md5 function


 
 
 
   
  API test 
   
   
   
   

Search:


token_key md5 {{md5(str)}}


{{api.request(api.params, value0, value1, value2, value3, value4, value5, value6, value7, value8, value9)}}
{{concat(value0, value1, value2, value3, value4, value5, value6, value7, value8, value9)}}
{{api.params[0]}} {{api.params[1]}} {{api.params[2]}} {{api.params[3]}} {{api.params[4]}} {{api.params[5]}} {{api.params[6]}} {{api.params[7]}} {{api.params[8]}} {{api.params[9]}} token

The above is the detailed content of Three ways to implement interface verification in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn