我有一个 ASP.NET Web API MVC 5.0 应用程序。我已将ASP.NET Web API配置为此应用程序的一部分(包含在同一项目中)。
我目前正在尝试向我的Web API添加基于令牌的身份验证。我使用的指南一直使用 Microsoft.AspNet.Identity 与Owin编码。
但是,我的MVC项目仍在使用System.Web.Security SimpleMembershipProvider - 因此,使用WebSecurity类初始化成员资格表和管理帐户。
所以,看起来我有两个选择可以向前推进:
首先,是否几乎可以使我的Web API身份验证与SimpleMembershipProvider一起使用?
如果我更新我的项目以使用Microsoft.Asp.Identity,它将涉及一些我确定的工作。我这样做的游戏只是想确保使用SimpleMembershipProvider使我的Web API令牌认证工作变得非常简单。迁移使用Microsoft.Asp.Identity会有任何额外的好处吗?
举一个例子说明我的Web API身份验证:
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
var user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect");
return;
}
var oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType);
var cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType);
var properties = CreateProperties(user.UserName);
var authenticationTicket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(authenticationTicket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
我现有的MVC身份验证代码只使用WebSecurity方法来管理帐户。
谢谢。
答案 0 :(得分:0)
最后,我从使用SimpleMembershipProvider切换到使用Asp.Net.Identity提供程序。迁移实际上非常简单。
在我的Entity Framework数据库上下文中,我简单地继承了#39; IdentityDbContext&#39;等级,例如
public class DataContext : IdentityDbContext<ApplicationUser>
并将其添加到我的OnModelCreating覆盖:
base.OnModelCreating(modelBuilder);
在我管理帐户的服务中,我添加了代码,该代码可以引用新的&#39; ApplicationSignInManager&#39;和&#39; ApplicationUserManager&#39;,例如
public ApplicationSignInManager SignInManager
{
get => _signInManager ?? HttpContext.Current.GetOwinContext().Get<ApplicationSignInManager>();
private set => _signInManager = value;
}
public ApplicationUserManager UserManager
{
get => _userManager ?? HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
private set => _userManager = value;
}
然后每次我的代码引用“WebSecurity”#39;我只是使用我的UserManager或SignInManager将这些调用替换为相关调用。
ASP.NET Identity还提供了一些优势: