我已经创建了一个WebApi和一个Cordova应用程序。 我正在使用HTTP请求在Cordova应用程序和WebAPI之间进行通信。 在WebAPI中,我已经实现了OAuth Bearer令牌生成。
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
我还可以添加带有自定义名称的guid identity.AddClaim(new Claim("guid", user.UserGuid.ToString()));
我仍然想知道是否有一种方法可以通过Bearer Token JSON向客户端返回更多数据。