asp.net-mvc 将 ASP.NET Identity 2.0 UserManagerFactory 与 UseOAuthBearerTokens 方法一起使用的示例?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21519226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Example of using ASP.NET Identity 2.0 UserManagerFactory with UseOAuthBearerTokens method?
提问by BenjiFB
The ASP.NET Identity 2.0 alpha ships with new middleware to manage getting an instance of the UserManager(app.UseUserManagerFactoryto set this up) and getting an instance of the DbContext(app.UseDbContextFactoryto set this up). There is an example showing how to get this working with an MVC app, but there is no documentation on how to get this working from the SPA template which uses OAuthBearerTokens, unlike the sample.
在ASP.NET 2.0身份阿尔法附带了新的中间件来管理获得实例UserManager(app.UseUserManagerFactory设置此)和获得的一个实例DbContext(app.UseDbContextFactory设置此)。有一个示例展示了如何在 MVC 应用程序中实现此功能,但OAuthBearerTokens与示例不同,没有关于如何从使用 的 SPA 模板实现此功能的文档。
I currently am stuck with:
我目前坚持:
UserManagerFactory = () => new DerivedUserManager(new CustomUserStore(new CustomDbContext()));
OAuthOptions = new Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new MyApp.Web.Api.Providers.ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true
};
app.UseOAuthBearerTokens(OAuthOptions);
and have no idea how to replace the UserManagerFactoryabove with calls like these from the 2.0 alpha samples while still working with the OAuthBearerTokensobjects used in the SPA template:
并且不知道如何UserManagerFactory在仍然OAuthBearerTokens使用 SPA 模板中使用的对象的同时使用来自 2.0 alpha 示例的这些调用替换上述内容:
app.UseDbContextFactory(ApplicationDbContext.Create);
// Configure the UserManager
app.UseUserManagerFactory(new IdentityFactoryOptions<ApplicationUserManager>()
{
DataProtectionProvider = app.GetDataProtectionProvider(),
Provider = new IdentityFactoryProvider<ApplicationUserManager>()
{
OnCreate = ApplicationUserManager.Create
}
});
Thanks... -Ben
谢谢... -本
回答by pranav rastogi
I am adding stubs here which show you how you can use OAuthBearerTokens... You do not have to use the UserManagerFactory that you were using in SPA. You can switch that to use the PerOWINContext pattern.
我在这里添加存根,向您展示如何使用 OAuthBearerTokens...您不必使用您在 SPA 中使用的 UserManagerFactory。您可以将其切换为使用 PerOWINContext 模式。
Startup.Auth.cs
启动.Auth.cs
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true
};
ApplicationOAuthProvider.cs
ApplicationOAuthProvider.cs
public ApplicationOAuthProvider(string publicClientId)
{
if (publicClientId == null)
{
throw new ArgumentNullException("publicClientId");
}
_publicClientId = publicClientId;
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
OAuthDefaults.AuthenticationType);
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
?
?
// namespace below needed to enable GetUserManager extension of the OwinContext
using Microsoft.AspNet.Identity.Owin;
回答by hylander0
Some New Patterns with ASP.NET Identity 2.0
ASP.NET Identity 2.0 的一些新模式
The ASP.NET Identity includes support for creating a single instance of a the UserManagerand the identity DBContextper application request. To support this pattern use the following extension methods per the IAppBuilderobject:
ASP.NET 标识支持为每个应用程序请求创建UserManager和标识的单个实例DBContext。要支持此模式,请为每个IAppBuilder对象使用以下扩展方法:
app.CreatePerOwinContext<AppUserIdentityDbContext>(AppUserIdentityDbContext.Create);
app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);
You can find a great example implementing this very pattern below:
你可以在下面找到一个很好的例子来实现这个模式:
ASP.NET Identity 2.0 Cookie & Token Authentication including a sample project.
ASP.NET Identity 2.0 Cookie 和令牌身份验证,包括一个示例项目。
Here is the AppManager Class:
这是 AppManager 类:
public class AppUserManager : UserManager<AppUserIdentity>
{
public AppUserManager(IUserStore<AppUserIdentity> store)
: base(store) { }
public static AppUserManager Create(IdentityFactoryOptions<AppUserManager> options, IOwinContext context)
{
var manager = new AppUserManager(new UserStore<AppUserIdentity>(context.Get<AppUserIdentityDbContext>()));
return manager;
}
}
This acticle uses the OWIN Middleware components UseOAuthBearerAuthenticationand UseCookieAuthenticationto support browser based authentication along with single Owin context IdentityDb Objects and a single AppManager.
此操作使用 OWIN 中间件组件UseOAuthBearerAuthentication并UseCookieAuthentication支持基于浏览器的身份验证以及单个 Owin 上下文 IdentityDb 对象和单个 AppManager。
Setup Bearer Tokens
设置承载令牌
Startup.Auth.cs
启动.Auth.cs
OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
//This will used the HTTP header: "Authorization" Value: "Bearer 1234123412341234asdfasdfasdfasdf"
app.UseOAuthBearerAuthentication(OAuthBearerOptions);
// Enable the application to use a cookie to store information for the signed in user
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});
HostAuthenticationFilter represents an authentication filter that authenticates via OWIN middleware:
HostAuthenticationFilter 表示通过 OWIN 中间件进行身份验证的身份验证过滤器:
WebApiConfig.cs
WebApiConfig.cs
config.SuppressDefaultHostAuthentication();
//This will used the HTTP header: "Authorization" Value: "Bearer 1234123412341234asdfasdfasdfasdf"
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
To Generate a Token:
生成令牌:
var identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, user));
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userIdentity.Id));
AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
var currentUtc = new SystemClock().UtcNow;
ticket.Properties.IssuedUtc = currentUtc;
ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
string AccessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);
return AccessToken;
回答by Vesselin Obreshkov
Ben, some of these things have changed from the alpha1 to beta1 builds (currently available on the ASP.NET Nightly NuGet Repo at https://aspnetwebstack.codeplex.com/wikipage?title=Use%20Nightly%20Builds). If you upgrade to the latest beta bits, you will not be using this syntax anymore but this instead:
Ben,其中一些内容已从 alpha1 更改为 beta1 版本(目前可在 ASP.NET Nightly NuGet Repo 上获取,网址为https://aspnetwebstack.codeplex.com/wikipage?title=Use%20Nightly%20Builds)。如果您升级到最新的 beta 位,您将不再使用此语法,而是使用以下语法:
// Configure the db context and user manager to use per request
app.CreatePerOwinContext(ApplicationIdentityContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
Also, notice that HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>is now moved to Microsoft.AspNet.Identity.Owin.
另外,请注意,HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>现在已移至Microsoft.AspNet.Identity.Owin.
You can install the `Microsoft.AspNet.Identity.Samples' package (preferably in a new MVC project because it might overwrite files). It helped me learn how they do certain things considering documentation for 2.0 is non-existent at the moment besides a few blog posts (all of which written for the alpha1 builds).
您可以安装“Microsoft.AspNet.Identity.Samples”包(最好在新的 MVC 项目中,因为它可能会覆盖文件)。它帮助我了解了他们如何做某些事情,因为 2.0 的文档目前不存在,除了一些博客文章(所有这些都是为 alpha1 版本编写的)。

