您需要編寫一個過濾器。一個zuul pre過濾器是你需要的。您可以在過濾器中訪問您的auth服務器,如果令牌無效,則不要調用您的微服務並立即返回響應。如果它是有效的,則讓請求轉到微服務。
一個例子過濾器類:
public class AuthFilter extends ZuulFilter {
@Autowired
RestTemplate restTemplate;
@Override
public String filterType() {
return "pre";
}
@Override
public int filterOrder() {
return 1;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() {
RequestContext ctx = RequestContext.getCurrentContext();
//get your token from request context and send it to auth service via rest template
boolean validToken = restTemplate.exchange(or getForObject or other methods of restTemplate which you find suitable for method and return type of your auth service controller method)
if(!validToken) {
ctx.setSendZuulResponse(false); //This makes request not forwarding to micro services
ctx.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
ValidationResponse validationResponse = new ValidationResponse();
validationResponse.setSuccess(false);
validationResponse.setMessage("Invalid Access...");
ObjectMapper mapper = new ObjectMapper();
String responseBody = mapper.writeValueAsString(validationResponse);
ctx.setResponseBody(validationResponse);
ctx.getResponse().setContentType("application/json");
//If you want to do any thing else like logging etc, you can do it.
}
return null;
}
}
是不是你的accessToken一個簽名令牌可以信任? –
彈簧安全是正確做到這一點的方法。如果您知道調用方無法繞過代理並直接訪問微服務,則只能這樣做。 –
@安迪布朗,能否請您詳細提供一些鏈接或進行檢查? – Krish