为什么缺少授权标题?

时间:2018-11-17 12:15:17

标签: java authentication jwt microservices

我有Eureka和相关服务 Zuul:8090 AuthService:[any_port]

我向他发送给AuthSercice的Zuul发送了 ../ login 请求。然后将AuthSerice放入Header JWT Authentication中。

@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
    String token = Jwts.builder()
            .setSubject( ((User) authResult.getPrincipal()).getUsername())
            .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
            .signWith(SignatureAlgorithm.HS512, SECRET)
            .compact();

    response.addHeader("Authorization", "Bearer "+ token); // this is missing
    response.addHeader("Authorization2", "Bearer " + token); // ok
}

我确实要求邮递员。 Request result

首先,我尝试在Monoliths中使用JWT。没问题,可以添加授权令牌。

为什么缺少授权标题?

2 个答案:

答案 0 :(得分:0)

您需要在Eureka中设置转发标题的选项。 对于登录,我建议使用自定义的ZuulFilter。

public abstract class AuthenticationZuulFilter extends ZuulFilter {

private static final Log logger = getLog(AuthenticationZuulFilter.class);

private static final String BEARER_TOKEN_TYPE = "Bearer ";
private static final String PRE_ZUUL_FILTER_TYPE = "pre";

private AuthTokenProvider tokenProvider;

public AuthenticationZuulFilter(AuthTokenProvider tokenProvider) {
    this.tokenProvider = tokenProvider;
}

@Override
public Object run() {
    RequestContext ctx = getCurrentContext();
    ctx.addZuulRequestHeader(X_USER_INFO_HEADER_NAME, buildUserInfoHeaderFromAuthentication());
    ctx.addZuulRequestHeader(AUTHORIZATION, BEARER_TOKEN_TYPE + tokenProvider.getToken());
    return null;
}

@Override
public String filterType() {
    return PRE_ZUUL_FILTER_TYPE;
}

@Override
public int filterOrder() {
    return 1;
}

这是它的实现,可以像这样。

@Component
public class UserAuthenticationZuulFilter extends AuthenticationZuulFilter {

@Value("#{'${user.allowed.paths}'.split(',')}")
private List<String> allowedPathAntPatterns;

private PathMatcher pathMatcher = new AntPathMatcher();

@Autowired
public UserAuthenticationZuulFilter (AuthTokenProvider tokenProvider) {
    super(tokenProvider);
}

@Override
public boolean shouldFilter() {
    Authentication auth = getContext().getAuthentication();
    HttpServletRequest request = getCurrentContext().getRequest();
    String requestUri = request.getRequestURI();
    String requestMethod = request.getMethod();
    return auth instanceof UserAuthenticationZuulFilter && GET.matches(requestMethod) && isAllowedPath(requestUri);
}

}

答案 1 :(得分:0)

这是因为Zuul中的内置机制-它自动过滤掉敏感的标头,例如AuthorizationCookies,以保护敏感信息不被转发到下游服务。   这就是为什么您无法获得名称为Authorization的标头的原因。

如果您仍然希望下游服务接收它们,则只需在Zuul配置文件中自己定义过滤器,而不要使用默认值。

 zuul:
  routes:
    users:
      path: your url pattern
      sensitiveHeaders: //put nothing here!! leave it blank, the filter will be off
      url: downstream url

这是春季官方对敏感标题的解释:document