【问题标题】:Web API token - Invalid grant by context.Validate()Web API 令牌 - context.Validate() 的授权无效
【发布时间】:2018-08-01 16:01:56
【问题描述】:

通过代码块调试后,用户通过用户非空测试但在 Context.Validate() 它返回无效授权

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userStore = new UserStore<IdentityUser>(new ApplicationDbContext());
            var manager = new UserManager<IdentityUser>(userStore);
            var user = await manager.FindAsync(context.UserName, context.Password);

            if(user !=null)
            {
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim("Username", user.UserName));
                identity.AddClaim(new Claim("Email", user.Email));
                identity.AddClaim(new Claim("LoggedOn", DateTime.Now.ToString()));

                context.Validated();
            }
            else
            {
                return;
            }
        }

【问题讨论】:

    标签: asp.net-mvc asp.net-web-api2 access-token


    【解决方案1】:

    您应该在Validated() 方法中传递身份。如果用户未通过验证,设置上下文错误也是一个好主意。

    所以它应该如下所示:

    if(user !=null)
            {
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim("Username", user.UserName));
                identity.AddClaim(new Claim("Email", user.Email));
                identity.AddClaim(new Claim("LoggedOn", DateTime.Now.ToString()));
    
                context.Validated(identity);
            }
            else
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-24
      • 1970-01-01
      • 2019-01-09
      • 1970-01-01
      • 2021-11-21
      • 2017-12-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多