【问题标题】:token authorize web api 2 doesn't return userName令牌授权 web api 2 不返回用户名
【发布时间】:2016-04-07 09:34:54
【问题描述】:

我在我的项目中使用 asp.net web api 2,令牌授权,当向 /Token 发送请求时,我收到响应

{ 
access_token: "u3XOCYV91f2P6odbceNIY_BnkfSpN7gQwzknsRi_.......0iRPlHYNMEES9", 
token_type: "bearer", 
expires_in: 1209599,
}

没有参数 UserName =( 当我使用 Authorize ActionResult 上的令牌向服务器发送请求时,一切正常,但 User.Identity.Name 为空,User.Identity.isAuthenticated = true。请帮助。

 public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            using (AuthorizeRepository _repo = new AuthorizeRepository())
            {
                User user = await _repo.FindUser(context.UserName, context.Password);

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

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));

            context.Validated(identity);

        }
    }

 public void ConfigureOAuth(IAppBuilder app)
        {
            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new SimpleAuthorizationServerProvider(),

            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

        }

【问题讨论】:

    标签: c# asp.net-mvc oauth-2.0 asp.net-web-api2


    【解决方案1】:

    要自动填充User.Identity.Name,您必须在访问令牌中添加ClaimTypes.Name 声明:

    identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
    

    【讨论】:

      猜你喜欢
      • 2019-01-09
      • 2014-07-28
      • 2018-07-26
      • 2015-04-24
      • 1970-01-01
      • 2020-05-14
      • 1970-01-01
      • 2019-07-20
      • 2014-09-19
      相关资源
      最近更新 更多