spring boot - 假装客户端发送基本授权头|将jwt令牌从一个微服务传递到另一个微服务

时间:2018-04-03 08:55:19

标签: spring-boot jwt microservices netflix-feign feign

我正在使用spring boot创建一个基于微服务的项目。 我已经使用eureka服务器进行服务发现和注册,也使用JWT进行授权和身份验证的身份验证。 每个微服务都有jwt验证,全局方法安全性在控制器上实现 我正在使用假装客户端进行微服务间调用。

服务 - 1)主要请求服务 2)审批服务;

批准者服务正在调用主服务,以调用只能由ADMIN访问的方法 但是当在主请求服务端处理jwt验证时,我只能看到Headers中的基本授权头。

我从我的审批服务中传递JWT令牌 在批准服务中假设客户



@FeignClient("MAINREQUESTSERVICE")
public interface MainRequestClient {
	
	@RequestMapping(method=RequestMethod.POST, value="/rest/mainrequest/changestatus/{status}/id/{requestid}")
	public String changeRequestStatus(@RequestHeader("Authorization") String token,@PathVariable("requestid")int requestid,@PathVariable("status") String status);

}




从请求中读取标题的代码



@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request=(HttpServletRequest) req;
		HttpServletResponse response=(HttpServletResponse) res;
		String header = request.getHeader("Authorization");
		System.out.println("header is "+header);
		if (header == null || !header.startsWith("Bearer")) {
			chain.doFilter(request, res);
			return;
		}

		UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
		SecurityContextHolder.getContext().setAuthentication(authentication);
		chain.doFilter(request, response);
		
	}




在调试此过滤器时,我已在控制台上打印了令牌 Header when debugged in main request service

那么我可以获得如何将JWT令牌从一个微服务传递到另一个微服务的帮助吗?

1 个答案:

答案 0 :(得分:0)

尝试一下(基于https://medium.com/@IlyasKeser/feignclient-interceptor-for-bearer-token-oauth-f45997673a1的代码)

@Component 公共类FeignClientInterceptor实现RequestInterceptor {

private static final String AUTHORIZATION_HEADER="Authorization";
private static final String TOKEN_TYPE = "Bearer";

@Override
public void apply(RequestTemplate template) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if (authentication != null && authentication instanceof JwtAuthenticationToken) {
        JwtAuthenticationToken token = (JwtAuthenticationToken) authentication;
        template.header(AUTHORIZATION_HEADER, String.format("%s %s", TOKEN_TYPE, token.getToken().getTokenValue()));
    }
}

}

相关问题