the*_*ing 3 asp.net oauth-2.0 owin asp.net-identity asp.net-web-api2
我在我的WebAPI应用程序中使用带有OAuth的OWIN中间件的asp.net身份提供程序.使用模板和
https://www.nuget.org/packages/Microsoft.AspNet.Identity.Samples
我在WebAPI端点上运行OAuth.但是,我没有看到如何扩展此体系结构以为不同的请求提供不同的令牌生存期.
例如,我的REST API将由Web应用程序和移动应用程序使用.我希望移动应用程序的令牌生命周期比Web应用程序长得多.
在我的Startup.Auth.cs文件中,我看到以下OAuth配置 -
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider<ApplicationUserManager, DirectoryUser, Guid>(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true
});
Run Code Online (Sandbox Code Playgroud)
有没有办法在每个令牌请求中覆盖此行为?例如,我可以公开"/ Token" - > 14天和"/ DeviceToken" - > 60天.这可能吗?
我能够解决这个问题,我将以下内容从示例中插入我的OAuth提供程序(ApplicationOAuthProvider.cs)中 -
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.Get<TUserManager>();
TUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
//if user, expire 60. If Admin, 14 days
if (userManager.IsInRole(user.Id, "Users"))
{
context.Options.AccessTokenExpireTimeSpan = TimeSpan.FromDays(60);
}
else {
context.Options.AccessTokenExpireTimeSpan = TimeSpan.FromDays(14);
}
ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user,
context.Options.AuthenticationType);
ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1339 次 |
| 最近记录: |