生成token和验证token机制

1.生成token是一个spring控制器
 基于项目和项目之间的调用秘钥生成之后放redis,两小时后失效

package com.csair.openapi.controller.basic;

import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.csair.openapi.basic.annotation.WEBApi;
import com.csair.openapi.qo.sub.TokenCredential;
import com.csair.openapi.vo.sub.TokenSuccess;

@RestController
@RequestMapping("/credential")
public class TokenCredentialController {

	
	@Autowired
	private RedisTemplate redisTemplate;


	private Map key = new HashMap();

	
	@PostConstruct
	public void init() {
		key.put("lps", "lrKvmMg3h9c8UQsvzDn0S4X");
		
	}

	 @RequestMapping(value = "/getToken")
	 @ResponseBody
	 @WEBApi
	 public Object export(HttpServletRequest request,HttpServletResponse response,@RequestBody TokenCredential limitsAuthority) throws Exception {
		 TokenSuccess tokenSuccess   =  new TokenSuccess();
		 if (limitsAuthority!=null&&limitsAuthority.getAppid()!=null&&limitsAuthority.getSecret()!=null) {//校验用户是否有权限
			 String appid= limitsAuthority.getAppid();
			 String secretPass =(String) key.get(appid);
			 String secret = limitsAuthority.getSecret();
			 if (secret.equals(secretPass)) {
				 String Timestamp= System.currentTimeMillis()+"";
				 String token = md5Password(appid+secretPass+System.currentTimeMillis()+Timestamp);
				 redisTemplate.opsForValue().set(token, Timestamp,7200, TimeUnit.SECONDS);//token和验证码对应的放到redis里面 ,2小时秒过期
				 tokenSuccess.setAccess_token(token);
				 tokenSuccess.setExpires_in("7200");
				 return tokenSuccess;
			 }else{
				 throw new RuntimeException("invalid secret");			
			}
		 }
		 throw new RuntimeException("invalid appid");

	 }

 
	
	/**
     * 生成32位md5码
     * @param password
     * @return
     */
	public static String md5Password(String password) {

		try {
			// 得到一个信息摘要器
			MessageDigest digest = MessageDigest.getInstance("md5");
			byte[] result = digest.digest(password.getBytes());
			StringBuffer buffer = new StringBuffer();
			// 把每一个byte 做一个与运算 0xff;
			for (byte b : result) {
				// 与运算
				int number = b & 0xff;// 加盐
				String str = Integer.toHexString(number);
				if (str.length() == 1) {
					buffer.append("0");
				}
				buffer.append(str);
			}
			// 标准的md5加密后的结果
			return buffer.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return "";
		}
	}
	
}

2.用java自定义注解引入aop来鉴权

package com.csair.openapi.basic.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Inherited
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AuthToken {
	

}

 

package com.csair.openapi.basic.aspect;


import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import com.csair.cocc.basic.constant.EnvironmentEnum;
import com.csair.openapi.basic.annotation.AuthToken;

@Component
@Aspect
public class AuthTokenDecorator implements Ordered {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private RedisTemplate redisTemplate;
	@Value("${environment}")
	private String environment;

	@Around("within(com.csair.**.controller.**.*) && @annotation(authToken)")
	public Object decorate(ProceedingJoinPoint pjp, AuthToken authToken) throws Throwable {
		 
	  if (EnvironmentEnum.DEV.getValue().equals(environment)) {//如果是开发环境
			return pjp.proceed();//这个是可以继续传输对象到Controller的逻辑
	  }
		
	  Object[] obj = pjp.getArgs();
	  HttpServletRequest request = (HttpServletRequest) obj[0];
	  String accessToken = request.getParameter("accessToken");
	  logger.info("accessToken值為:"+accessToken);
	  
	  if (StringUtils.isEmpty(accessToken)) {
			 throw new RuntimeException("token is null");		
		}else {
			String timestamp = redisTemplate.opsForValue().get(accessToken); 
			if (StringUtils.isEmpty(timestamp)) {
			 throw new RuntimeException("Invalid token");		
			}
		}
		return pjp.proceed();
	}

	public int getOrder() {
		return 9;
	}
	
}

引用redis的配置!




	

	
		
		
		
		
		
		
	

	

		
			
				
			
		

		
			
				
					
					
				
				
					
					
				
				
					
					
				
			
		

	

	
		
		
		
	

	
		
		
			
		
		
			
		
		
			
		
		
			
		
	

最重要的是Controller的入参要加上HttpServletRequest request

    @RequestMapping(value = "/saveCargoPlaneUploadLpsInfo", method = RequestMethod.POST)
    @ResponseBody
    @WEBApi
    @AuthToken
    public Object saveCargoPlaneUploadLpsInfo(HttpServletRequest request,@RequestBody CargoPlaneUploadLpsInfoDto param)

 

你可能感兴趣的:(token)