我正在WebApi系统中实现ASP.Net Identity 2。为了管理新帐户的电子邮件确认,我必须创建一个自定义ApplicationUserManager
并注册它,以便为每个请求创建该自定义:
public class IdentityConfig{
public static void Initialize(IAppBuilder app)
{
[snip]
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
}
它可以在ApiController内正常工作,如下所示:
public class AccountController : ApiController
{
public ApplicationUserManager UserManager
{
get
{
return HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
}
我面临的问题是ApplicationUserManager.Create
在尝试使用OAuth令牌创建方法访问该方法之前未调用该方法:
public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var mgr = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
在上面的代码中,mgr为null,因为GetUserManager检索null
令牌创建方法是否早已在管道中以某种CreatePerOwinContext
方式出现,从而尚未被调用?如果是这样,最好的缓存方式是什么,ApplicationUserManager
以便可以在内部使用GrantResourceOwnerCredentials
?
这个很棘手。事实证明,启动代码必须按一定顺序进行。
此代码将起作用。
public class IdentityConfig{
public static void Initialize(IAppBuilder app)
{
// correct... first create DB context, then user manager, then register OAuth Provider
app.CreatePerOwinContext(AuthContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new SimpleAuthorizationServerProvider()
};
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
如果您更改在应用程序中注册代码的顺序,可能会导致意想不到的后果。此代码导致令牌生成方法GrantResourceOwnerCredentials中的ApplicationUserManager为null
// wrong... these two lines must be after the ApplicationUserManager.Create line
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
[snip]
app.CreatePerOwinContext(AuthContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
当我在这里时,这是另一件事,可能使某人绊倒。这些行导致TokenContext方法GrantResourceOwnerCredentials内部的AuthContext为null
// wrong... The AuthContext must be instantiated before the ApplicationUserManager
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext(AuthContext.Create);
[snip]
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句