Поставщик услуг OAuth возвращает 400/Неверный запрос на неверное имя пользователя/пароль

#jquery #ajax #asp.net-mvc #authentication #oauth-2.0

Вопрос:

Я использую систему аутентификации OAuth с ASP.NET Проект веб-api MVC с Visual Studio 2019.

Ниже приведен класс поставщика авторизации.

 public class MyAuthorizationServerProvider:OAuthAuthorizationServerProvider
{
    DBContext db = new DBContext ();
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        string traderid = string.Empty;
        string password = string.Empty;
        if(!context.TryGetBasicCredentials(out traderid,out password))
        {
            context.SetError("invalid_client", "Client credentials could not be retrieved");
            context.Rejected();
            return;
        }
        var trader=db.TRADERS.Where(t => t.CODE == traderid amp;amp; t.PASSWORD == password).FirstOrDefault();
        if (trader != null)
        {
            context.OwinContext.Set<TRADER>("oauth:client", trader);
            context.Validated(traderid);
        }
        else
        {
            context.SetError("invalid_client", "Client credentials are invalid");
            context.Rejected();
        }
        context.Validated();
    }
    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var trader = db.TRADERS.Where(t => t.CODE == context.UserName amp;amp; t.PASSWORD == context.Password amp;amp; t.ISENABLED==true).FirstOrDefault();
        if (trader == null)
        {
            context.SetError("invalid_grant", "Provided username and password incorrect");
            return;
        }
        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        identity.AddClaim(new Claim(ClaimTypes.Role, "USER"));
        identity.AddClaim(new Claim(ClaimTypes.Name, trader.CODE));
        context.Validated(identity);
    }
}
 

Я звоню и проверяю имя пользователя/пароль с html-страницы с помощью вызова jquery ajax.

     $(document).ready(function () {
        var btnLogin = $("#btnLogin");
        var txtUsername = $("#txtUsername");
        var txtPassword = $("#txtPassword");
        
        
        btnLogin.click(function () {
            var encodedData = btoa(txtUsername.val()   ":"   txtPassword.val())
            
            $.ajax(
                {
                    url: "http://192.168.0.3/miniapi/token",
                    type: "POST",
                    dataType: "json",
                    crossDomain:true,
                    data: { grant_type: 'password', username: txtUsername.val(), password: txtPassword.val() },
                    headers: {
                        Accept: "*/*",
                        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
                        Authorization: "Basic "   encodedData,
                    },
                    success: function (r) {
                        console.log(r)
                    },
                    error: function () {
                        $("#msg").text("Authentication failed");
                    }
                })
        });
    })
 

Когда имя пользователя/пароль указаны правильно, вкладка «Сеть браузера» показывает правильный ответ(200/OK), и я могу видеть ответ console.log внутри success() вместе с токеном и другими значениями.

But when I type wrong password and login, I receive error message with description, but with (400/Bad Request) in browser network tab. So success() function is not run and I can’t display the error message.

What is wrong with my coding?