问题
I have a Dart client and a Java backend. I'm trying to add security around my application, so the Java server requires the user to be authenticated before accessing data. If a webservice call comes in and the user is not authenticated the backend services send a redirect with a HttpResponseCode (401) back to the client call. I have it now that the client can parse the request.status and see the 401 but it doesn't handle the redirect.
Dart Code
HttpRequest request=new HttpRequest();
request.onReadyStateChange.listen((_) {
if (request.readyState == HttpRequest.DONE &&
(request.status == 200 || request.status == 0)) {
onHistoryLoaded(request.responseText);
}
});
request.open("GET", url);
request.send();
request.onLoadEnd.listen((e) => processRequest(request));
request.onError.listen((Object error)=>handleError(error));
void processRequest(HttpRequest request) {
var status = request.status;
print("status $status"); //401
}
void handleTheError(Error e){
print("handleTheError Request error: $e");
}
Java Server
//Tried both of these
// response.setStatus(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED);
// response.sendRedirect(LOGIN_PAGE);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader("Location", LOGIN_PAGE);
Any suggestions would be great. Thanks
回答1:
First of all, the Location header is only allowed with HTTP status codes 201 and some 3xx codes. Instead, in a valid HTTP response, status code 401 requires to send the "WWW-Authenticate" header field - which is probably not what you want. That's the reason your redirect isn't followed automatically.
If your client is the only one to connect to the server and you don't care about the malformed response, you can read the headers on your client with getResponseHeader("Location")
Or you could just use HTTP status 307 instead.
来源:https://stackoverflow.com/questions/18519413/dart-client-httprequest-error-authentication-handling