使用 ASP.NET Identity 2.0 UserManagerFactory 和 UseOAuthBearerT



ASP.NET Identity 2.0 alpha 附带了新的中间件来管理获取UserManager的实例(app.UseUserManagerFactory设置它)和获取DbContext的实例(app.UseDbContextFactory设置这个)。有一个示例显示了如何使用 MVC 应用程序使其工作,但没有有关如何从使用OAuthBearerTokens的 SPA 模板使其工作的文档,这与示例不同。

我目前被困在:

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);

并且不知道如何将上述UserManagerFactory替换为来自 2.0 alpha 示例的此类调用,同时仍在使用 SPA 模板中使用的OAuthBearerTokens对象:

app.UseDbContextFactory(ApplicationDbContext.Create);
// Configure the UserManager
app.UseUserManagerFactory(new IdentityFactoryOptions<ApplicationUserManager>()
{
DataProtectionProvider = app.GetDataProtectionProvider(),
Provider = new IdentityFactoryProvider<ApplicationUserManager>()
{
OnCreate = ApplicationUserManager.Create
}
});

谢谢。。。 -本

我在这里添加存根,向您展示如何使用 OAuthBearerTokens...您不必使用在 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
};

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;

ASP.NET 身份2.0的一些新模式

ASP.NET 标识包括对创建UserManager单个实例的支持,以及每个应用程序请求的标识DBContext。若要支持此模式,请对IAppBuilder对象使用以下扩展方法:

app.CreatePerOwinContext<AppUserIdentityDbContext>(AppUserIdentityDbContext.Create);
app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);

您可以在下面找到一个实现此模式的很好示例:

ASP.NET Identity 2.0 Cookie & Token 身份验证,包括一个示例项目。

下面是 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;
}
}

该组件使用 OWIN 中间件组件UseOAuthBearerAuthenticationUseCookieAuthentication来支持基于浏览器的身份验证以及单个 Owin 上下文 IdentityDb 对象和单个 AppManager。

设置持有者令牌

Startup.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 表示通过 OWIN 中间件进行身份验证的身份验证筛选器:

WebApiConfig.cs

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;

Ben,其中一些东西已经从alpha1更改为beta1版本(目前在 https://aspnetwebstack.codeplex.com/wikipage?title=Use%20Nightly%20Builds 的 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);

另请注意,HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>现在已移至Microsoft.AspNet.Identity.Owin

您可以安装"Microsoft.AspNet.Identity.Samples"包(最好在新的 MVC 项目中安装,因为它可能会覆盖文件)。它帮助我了解了他们如何做某些事情,考虑到 2.0 的文档目前不存在,除了一些博客文章(所有这些都是为 alpha1 构建编写

的)。

相关内容

  • 没有找到相关文章

最新更新