Iva*_*nov 62 c# authentication owin asp.net-web-api2 bearer-token
我创建了一个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());
}
Run Code Online (Sandbox Code Playgroud)
这是在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);
}
Run Code Online (Sandbox Code Playgroud)
从Cordova应用程序成功登录API后,我收到以下JSON
{"access_token":"some token","token_type":"bearer","expires_in":86399}
Run Code Online (Sandbox Code Playgroud)
问题是,我需要有关用户的更多信息.例如,我在数据库中有一个UserGuid字段,我想在登录成功时将其发送到Cordova应用程序,并在以后的其他请求中使用它.除了"access_token", "token_type"和之外,我可以包含其他信息以返回客户端"expires_in"吗?如果没有,我怎样才能让用户在API中基于access_token?
编辑:
我想我找到了一个解决方法.我在里面添加了以下代码GrantResourceOwnerCredentials
identity.AddClaim(new Claim(ClaimTypes.Name, user.UserGuid.ToString()));
Run Code Online (Sandbox Code Playgroud)
然后,我访问控制器内的GUID,如下所示: User.Identity.Name
我也可以使用自定义名称添加guid identity.AddClaim(new Claim("guid", user.UserGuid.ToString()));
我仍然有兴趣知道是否有办法使用持票人令牌JSON将更多数据返回给客户端.
Lef*_*tyX 91
您可以根据需要添加任意数量的声明.
您可以添加标准的声明集System.Security.Claims或创建自己的声明集.
声明将在您的令牌中加密,因此只能从资源服务器访问它们.
如果您希望您的客户端能够读取令牌的扩展属性,您还有另一种选择:AuthenticationProperties.
假设您要添加一些内容,以便您的客户可以访问.这是要走的路:
var props = new AuthenticationProperties(new Dictionary<string, string>
{
{
"surname", "Smith"
},
{
"age", "20"
},
{
"gender", "Male"
}
});
Run Code Online (Sandbox Code Playgroud)
现在,您可以使用上面添加的属性创建故障单:
var ticket = new AuthenticationTicket(identity, props);
context.Validated(ticket);
Run Code Online (Sandbox Code Playgroud)
这是您的客户将获取的结果:
.expires: "Tue, 14 Oct 2014 20:42:52 GMT"
.issued: "Tue, 14 Oct 2014 20:12:52 GMT"
access_token: "blahblahblah"
expires_in: 1799
age: "20"
gender: "Male"
surname: "Smith"
token_type: "bearer"
Run Code Online (Sandbox Code Playgroud)
另一方面,如果添加声明,您将能够在API控制器的资源服务器中读取它们:
public IHttpActionResult Get()
{
ClaimsPrincipal principal = Request.GetRequestContext().Principal as ClaimsPrincipal;
return Ok();
}
Run Code Online (Sandbox Code Playgroud)
您的ClaimsPrincipal意愿包含您guid在此处添加的新版权声明:
identity.AddClaim(new Claim("guid", user.UserGuid.ToString()));
Run Code Online (Sandbox Code Playgroud)
如果您想了解更多关于owin,承载令牌和网络API有一个很好的教程在这里,这文章将帮助您把握背后的概念授权服务器和资源服务器.
更新:
你可以在这里找到一个有效的例子.这是一个Web Api + Owin自托管.
这里没有涉及数据库.客户端是一个控制台应用程序(也有一个html + JavaScript示例),它调用Web Api传递凭据.
正如Taiseer建议的那样,你需要覆盖TokenEndpoint:
public override Task TokenEndpoint(OAuthTokenEndpointContext context)
{
foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
{
context.AdditionalResponseParameters.Add(property.Key, property.Value);
}
return Task.FromResult<object>(null);
}
Run Code Online (Sandbox Code Playgroud)
从解决方案 - >属性启用"多个启动项目",您可以立即运行它.
Tai*_*deh 44
如果不需要,我建议不要在令牌上添加额外的声明,因为会增加令牌的大小,并且您将继续发送每个请求.由于LeftyX建议将它们添加为属性,但请确保TokenEndPoint在成功获取令牌时覆盖方法以将这些属性作为响应,没有此终点,属性将不会在响应中返回.
public override Task TokenEndpoint(OAuthTokenEndpointContext context)
{
foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
{
context.AdditionalResponseParameters.Add(property.Key, property.Value);
}
return Task.FromResult<object>(null);
}
Run Code Online (Sandbox Code Playgroud)
您可以在此处查看我的回购以获取完整示例.希望它会有所帮助.
| 归档时间: |
|
| 查看次数: |
47335 次 |
| 最近记录: |