c# - token 授权 web api 2 不返回用户名

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

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

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

没有参数 UserName =( 并且当我使用 Authorize ActionResult 上的 token 向服务器发送请求时,一切正常,但 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());

        }

最佳答案

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

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

关于c# - token 授权 web api 2 不返回用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34579860/

相关文章:

python - 如何在 GAE/Python 上进行 'access_type=offline'/server-only OAuth2 操作?

c# - MonoState、Singleton 或派生形式 : Best approach for CRUD app?

c# - 在嵌套异步方法中使用 ConfigureAwait

asp.net-mvc - ASP.NET MVC 模型绑定(bind)子对象

ASP.NET MVC SiteMap 和/或安全修整

javascript - 如何保护 JavaScript/Ajax 客户端 [apigee] 中使用的 API 的安全?

javascript - Passport.js 可选身份验证

c# - 列数导入不一致的 SSIS 任务?

c# - 我可以在收听模式下启动语音识别器并且对用户不可见吗?

c# - MVC 4. ModelState.IsValid 总是返回 true