ASP.NET MVC WebApi 2按令牌登录:如何区分返回码?

mar*_*fin 2 c# asp.net-web-api owin asp.net-web-api2

我们在web api 2中遇到了新的OWIN auth的一些问题.我们正在开发连接到API服务的移动应用程序,我们需要在登录阶段区分响应.示例:a)错误请求,b)未找到用户,c)密码错误等.

不幸的是,如果我故意发送错误的密码,/ Token端点会返回"错误请求"HTTP响应,因此我无法区分这些情况.

检查Web代码,我认为这是重点(用户为空),我可以决定返回什么样的响应,但是如何?

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

        var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();


        User user = await userManager.FindAsync(context.UserName, context.Password);

        if (user == null)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }

        ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
           OAuthDefaults.AuthenticationType);
        ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
            CookieAuthenticationDefaults.AuthenticationType);

        AuthenticationProperties properties = CreateProperties(user.UserName, user.ID);
        AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
        context.Validated(ticket);
        context.Request.Context.Authentication.SignIn(cookiesIdentity);
    }
Run Code Online (Sandbox Code Playgroud)

在此先感谢您的帮助;)

Tai*_*deh 7

当用户提供无效的用户名或密码或用户处于活动状态时,返回400错误请求是正确的方法,请在此处查看此帖子.

从安全角度来看我的建议也是如此,一旦用户尝试登录到您的系统,您就不应该返回问题所在的位置,换句话说,您应该返回"用户名或密码不正确".当您登录时很少看到系统返回错误的输入参数,即"密码不正确".

如果您必须实现所要求的要求,您可以构建包含(ErrorCode,ErrorDesc)的简单POCO类,并在响应中将其作为JSON对象返回,同时保持http状态代码400.对于客户端应用程序,您将阅读收到400时,这个JSON对象.

希望这能回答你的问题.