使用SimpleMembershipProvider的应用程序中基于令牌的Web API身份验证

时间:2018-02-08 14:12:35

标签: asp.net asp.net-mvc authentication asp.net-web-api asp.net-web-api2

我有一个 ASP.NET Web API MVC 5.0 应用程序。我已将ASP.NET Web API配置为此应用程序的一部分(包含在同一项目中)。

我目前正在尝试向我的Web API添加基于令牌的身份验证。我使用的指南一直使用 Microsoft.AspNet.Identity 与Owin编码。

但是,我的MVC项目仍在使用System.Web.Security SimpleMembershipProvider - 因此,使用WebSecurity类初始化成员资格表和管理帐户。

所以,看起来我有两个选择可以向前推进:

  1. 更新我的MVC应用程序以切换到使用Microsoft.AspNet.Identity,以便它可以与我的Web API令牌身份验证一起使用。
  2. 更改我的Web API身份验证代码以使用SimpleMembershipProvider
  3. 首先,是否几乎可以使我的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方法来管理帐户。

    谢谢。

1 个答案:

答案 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还提供了一些优势:

  • 支持Web窗体,MVC,Web API,SignalR和网页。不需要拥有会员系统的不同实现。
  • 基于声明的身份验证现在是基于角色的身份验证的一种选择。
  • 通过Facebook,Google,Twitter或Microsoft Live轻松启用社交登录。
  • 支持OWIN。
  • 无需为帐户确认,密码重置等功能编写代码 - 这些都是Asp.Net Identity的开箱即用功能。