微服务通过feign调用/oauth/token方法

OAuth2获取token原生方法

微服务通过feign调用/oauth/token方法_第1张图片

服务内部通过feign调用/oauth/token方法

  1. 创建FeignClient接口类
    1. import com.goldnet.core.launch.constant.AppConstant;
      import org.springframework.cloud.openfeign.FeignClient;
      import org.springframework.util.MultiValueMap;
      import org.springframework.web.bind.annotation.RequestBody;
      import org.springframework.web.bind.annotation.RequestMapping;
      import org.springframework.web.bind.annotation.RequestMethod;
      
      /**
       * @Author 
       * @Date 2020/12/9 11:50
       * @Version 1.0
       */
      @FeignClient(
      	value = AppConstant.APPLICATION_AUTH_NAME,
      	fallback = AuthFeignClientFallback.class
      )
      public interface AuthFeignClient {
      	@RequestMapping(method = RequestMethod.POST, value = "/oauth/token")
      	Object postAccessToken(@RequestParam MultiValueMap parameters, @RequestHeader MultiValueMap headers);
      }
      
      import org.springframework.stereotype.Component;
      import org.springframework.util.MultiValueMap;
      
      /**
       * @Author 
       * @Date 2020/12/9 14:45
       * @Version 1.0
       */
      @Component
      public class AuthFeignClientFallback implements AuthFeignClient {
      	@Override
      	public Object postAccessToken(MultiValueMap map) {
      		return "获取token失败";
      	}
      }

      参数解释:

      1. AppConstant.APPLICATION_AUTH_NAME  服务提供者的服务名
      2. "aHg6aHhfc2VjcmV0" 是client_id:client_secret 通过base64编码获得----项目要求,视情况而定
      3. Tenant-Id 租户id----项目要求,视情况而定
  2. 调用方法
    1. HttpServletRequest request = WebUtil.getRequest();
      String tenantId = request.getHeader("Tenant-Id");
      String authorization = request.getHeader("Authorization");
      MultiValueMap headers = new LinkedMultiValueMap<>();
      headers.add("Content-Type","multipart/form-data");
      headers.add("Authorization",authorization);
      headers.add("Tenant-Id",tenantId);
      //body
      MultiValueMap body = new LinkedMultiValueMap<>();
      body.add("username","11");
      body.add("password","11");
      body.add("grant_type","password");
      //调用auth服务
      log.info("[接口名称:调用auth][请求数据body:{}][请求数据headers:{}]",body,headers);
      Object token = oAuthFeignClient.postAccessToken(body, headers);

你可能感兴趣的:(java,oauth2)