【发布时间】:2014-12-09 00:36:23
【问题描述】:
我创建了一个 WebApi 和一个 Cordova 应用程序。 我正在使用 HTTP 请求在 Cordova 应用程序和 WebAPI 之间进行通信。 在 WebAPI 中,我实现了 OAuth Bearer Token Generation。
public void ConfigureOAuth(IAppBuilder app)
{
var oAuthServerOptions = new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new SimpleAuthorizationServerProvider(new UserService(new Repository<User>(new RabbitApiObjectContext()), new EncryptionService()))
};
// Token Generation
app.UseOAuthAuthorizationServer(oAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
这是在SimpleAuthorizationServerProvider 实现中
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
// A little hack. context.UserName contains the email
var user = await _userService.GetUserByEmailAndPassword(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "Wrong email or password.");
return;
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim("role", "user"));
context.Validated(identity);
}
从 Cordova 应用成功登录 API 请求后,我收到以下 JSON
{"access_token":"some token","token_type":"bearer","expires_in":86399}
问题是,我需要有关用户的更多信息。例如,我在数据库中有一个 UserGuid 字段,我想在登录成功时将其发送到 Cordova 应用程序,并稍后在其他请求中使用它。除了"access_token", "token_type" 和"expires_in" 之外,我可以包含其他信息以返回给客户吗?如果没有,如何根据access_token在API中获取用户?
编辑:
我认为我找到了解决方法。
我在GrantResourceOwnerCredentials中添加了以下代码
identity.AddClaim(new Claim(ClaimTypes.Name, user.UserGuid.ToString()));
然后,我访问控制器内的 GUID,如下所示:User.Identity.Name
我还可以添加自定义名称 identity.AddClaim(new Claim("guid", user.UserGuid.ToString())); 的 guid
我仍然很想知道是否有办法使用不记名令牌 JSON 向客户端返回更多数据。
【问题讨论】:
标签: c# authentication owin asp.net-web-api2 bearer-token