Asp.net mvc 将ASP.NET Identity 2.0 UserManagerFactory与UseAuthBealerTokens方法一起使用的示例?
ASP.NET Identity 2.0 alpha附带了新的中间件,用于管理获取Asp.net mvc 将ASP.NET Identity 2.0 UserManagerFactory与UseAuthBealerTokens方法一起使用的示例?,asp.net-mvc,asp.net-mvc-5,asp.net-identity,owin,Asp.net Mvc,Asp.net Mvc 5,Asp.net Identity,Owin,ASP.NET Identity 2.0 alpha附带了新的中间件,用于管理获取UserManager(app.UseUserManagerFactory)的实例,以及获取DbContext(app.UseDbContextFactory)的实例。有一个示例显示了如何使用MVC应用程序来实现这一点,但与示例不同的是,没有关于如何从SPA模板(使用OAuthBealerTokens)实现这一点的文档 目前,我被以下问题困扰: UserManagerFactory = () => new D
UserManager
(app.UseUserManagerFactory
)的实例,以及获取DbContext
(app.UseDbContextFactory
)的实例。有一个示例显示了如何使用MVC应用程序来实现这一点,但与示例不同的是,没有关于如何从SPA模板(使用OAuthBealerTokens
)实现这一点的文档
目前,我被以下问题困扰:
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);
并且不知道如何用2.0 alpha示例中的调用替换上面的UserManagerFactory
,同时仍然使用SPA模板中使用的OAuthBealerTokens
对象:
app.UseDbContextFactory(ApplicationDbContext.Create);
// Configure the UserManager
app.UseUserManagerFactory(new IdentityFactoryOptions<ApplicationUserManager>()
{
DataProtectionProvider = app.GetDataProtectionProvider(),
Provider = new IdentityFactoryProvider<ApplicationUserManager>()
{
OnCreate = ApplicationUserManager.Create
}
});
app.UseDbContextFactory(ApplicationDbContext.Create);
//配置用户管理器
app.UseUserManagerFactory(新标识FactoryOptions()
{
DataProtectionProvider=app.GetDataProtectionProvider(),
Provider=新标识FactoryProvider()
{
OnCreate=ApplicationUserManager.Create
}
});
谢谢。。。
-BenBen,其中一些内容已从alpha1版本更改为beta1版本(目前可在ASP.NET Nightly NuGet Repo上获得)。如果升级到最新的beta版本,您将不再使用此语法,而是使用以下语法:
// Configure the db context and user manager to use per request
app.CreatePerOwinContext(ApplicationIdentityContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
//配置数据库上下文和用户管理器以按请求使用
app.CreatePerOwinContext(ApplicationIdentityContext.Create);
app.CreatePerOwinContext(ApplicationUserManager.Create);
另外,请注意HttpContext.GetOwinContext().GetUserManager
现在被移动到Microsoft.AspNet.Identity.Owin
您可以安装“Microsoft.AspNet.Identity.Samples”包(最好安装在新的MVC项目中,因为它可能会覆盖文件)。它帮助我了解了他们是如何做某些事情的,考虑到2.0的文档目前还不存在,除了一些博客文章(所有这些都是为alpha1版本编写的)。我在这里添加了存根,向您展示了如何使用OAuthBealerTokens。。。您不必使用在SPA中使用的UserManagerFactory。您可以切换到PerOWINContext模式 Startup.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
};
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);
}
使用ASP.NET Identity 2.0的一些新模式
ASP.NET标识包括支持为每个应用程序请求创建一个UserManager
和标识DBContext
的单个实例。要支持此模式,请根据IAppBuilder
对象使用以下扩展方法:
app.CreatePerOwinContext<AppUserIdentityDbContext>(AppUserIdentityDbContext.Create);
app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);
HostAuthenticationFilter表示通过OWIN中间件进行身份验证的身份验证筛选器:
WebApiConfig.cs
要生成令牌,请执行以下操作:
嗨,维塞林,谢谢你的回复(我投了赞成票)。我会尽快升级到beta版。我不知道在哪里可以找到你提到的样品包,但是它和这里的样品一样吗?如果是这样的话,那么它们不像SPA模板那样设置OAuthBeareToken服务器,所以我仍然不确定如何将其连接在一起。在每晚的ASP.NET NuGet Repo中搜索“Microsoft ASP.NET标识示例”。嗨,Vesselin,我刚刚签出了更新的示例。(再次感谢你让我知道他们在那里!)不幸的是,他们似乎没有包括一个使用OAuthBealerTokens的例子……谢谢,这里和你的博客上都有很好的信息。但是我注意到一件事:
config.SuppressDefaultHostAuthentication()必须在我的设置中删除WebApiConfig
中的code>,否则我无法访问令牌声明,cookie auth将被禁用。@BenjaminE。对在WebApi控制器中执行方法时禁用Cookie身份验证,默认使用令牌身份验证。Cookie Auth实际上与API/Rest请求模型无关。您可以通过Microsoft.Owin.Security.OAuth命名空间中的“OAuthDefaults.AuthenticationType”更改“Bearer”字符串
app.CreatePerOwinContext<AppUserIdentityDbContext>(AppUserIdentityDbContext.Create);
app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);
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;
}
}
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")
});
config.SuppressDefaultHostAuthentication();
//This will used the HTTP header: "Authorization" Value: "Bearer 1234123412341234asdfasdfasdfasdf"
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
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;