[英]Spring boot, custom auth handler and Angular 5
I have next problem with my rest application. 我的其余申请存在下一个问题。 I have my backend with an custom auth handler
我的后端带有自定义身份验证处理程序
public class AutorizacionFilter extends OncePerRequestFilter {
@Autowired
UsuariosService usuarioService;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String dominio = ((HttpServletRequest) request).getRequestURI();
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
filterChain.doFilter(request, response);
} else if (dominio.startsWith("/api/login") || dominio.startsWith("/api/usuarios")) {
filterChain.doFilter(request, response);
} else {
String token = request.getHeader ("Authorization");
if (token == null || !usuarioService.validarSesion(token)) {
((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED, "your message goes here");
return;
}
filterChain.doFilter(request, response);
}
}
In my web page made witn Angular 5, I have an interceptor for catch the 401 status code 在我用Angular 5创建的网页中,我有一个拦截器来捕获401状态码
@Injectable()
export class AuthHttpInterceptor implements HttpInterceptor {
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
if (!req.headers.has("Content-Type")) {
req = req.clone({
headers: req.headers.set("Content-Type", "application/json")
});
}
req = req.clone({ headers: req.headers.set("Accept", "application/json") });
console.log(JSON.stringify(req.headers));
return next.handle(req).do(
(event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
console.log("Autorizacion OK!");
console.log("Code: " + event.status);
}
},
(err: HttpErrorResponse) => {
if (err.error instanceof Error) {
console.log("An error occurred:", err.error.message);
} else {
console.log(
`Backend returned code ${err.status}, body was: ${err.message}`
);
}
}
);}}
When the toker expire the interceptor cant parse the answer and give me this error 当代币到期时,拦截器无法解析答案,并给我这个错误
Http failure response for (unknown url): 0 Unknown Error
针对(未知网址)的Http错误响应:0未知错误
I have a lot of reading about the problem of the httpClient with empty responses, but I cant understand how to fixed/find a way around. 我有很多关于httpClient响应为空的问题的阅读资料,但我无法理解如何解决/找到解决方法。
Can anyone give a hand to understand this issue. 任何人都可以伸出援助之手来理解这个问题。
Thanks 谢谢
Thanks to @Asura answer, I set up the response headers and solve the problem. 感谢@Asura的回答,我设置了响应头并解决了问题。 This is the code.
这是代码。
if (token == null || !usuarioService.validarSesion(token)) {
((HttpServletResponse) response).setHeader("Access-Control-Allow-Origin", "*");
((HttpServletResponse) response).setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS, HEAD");
((HttpServletResponse) response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.