我创建了一个 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"
?如果没有,我怎样才能在基于 API 的 API 中获取用户access_token
?
编辑:
我认为我找到了解决方法。我在里面添加了以下代码GrantResourceOwnerCredentials
identity.AddClaim(new Claim(ClaimTypes.Name, user.UserGuid.ToString()));
之后,我像这样访问控制器内的 GUID:User.Identity.Name
我还可以使用自定义名称添加 guididentity.AddClaim(new Claim("guid", user.UserGuid.ToString()));
我仍然很想知道是否有办法使用不记名令牌 JSON 向客户端返回更多数据。