问题
Using this aurelia-auth plugin together with .NET Core webAPI, I wish to return a custom error when user tries to log in with incorrect username and/or password.
WebAPI:
public HttpResponseMessage Login()
{
    if (passwordValid)
    {
        return Request.CreateResponse(new LoginResponseViewModel { Token = token });
    }
    else
    {
        return Request.CreateResponse(HttpStatusCode.Unauthorized, "Incorrect username or password!");
    }
}
Script
logIn(email, password) {
    return this.auth.login(email, password)
        .then(response => {
            console.log("success logged " + response);
        })
        .catch(err => {
            console.log("login failure: " + err);
        });
}
- How do I access my unauthorized response custom message "Incorrect username or password" in the login function catch error?
- It seems like the aurelia-auth login function must receive a httpStatusCode.Unauthorizedin order for it to understand that the password/username was incorrect, but that generates a401 (Unauthorized)console error. Can I suppress this console error or perhaps return a json result which aurelia-auth understands?
回答1:
1. How to access custom unauthorized response message
Server response:
return Request.CreateResponse(HttpStatusCode.Unauthorized, "My message");
Client:
return this.auth.login(email, password)
    .then(response => {
        console.log("success logged " + response);
    })
    .catch(error => error.json().then(serverError =>
        console.log(serverError) //My message 
    ));
2. Suppress console error or return a json result which aurelia-auth understands
It is not possible in the current version of aurelia-auth to return a json result that aurelia-auth understand.
I decided to replace my current aurelia-auth package with aurelia-authentication.
Aurelia-authentication is fork of aurelia-auth which itself is a port of the great Satellizer library. With the new package I can now do much more, (refresh token, return custom messages from server etc)..
来源:https://stackoverflow.com/questions/42532109/aurelia-auth-custom-response-message-console-error