我在我的项目中使用 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/