【问题标题】:How to Add token authentication to web api in cookie authentication based asp.net mvc project如何在基于 cookie 身份验证的 asp.net mvc 项目中向 web api 添加令牌身份验证
【发布时间】:2020-01-23 19:23:33
【问题描述】:

我有这个 asp.net mvc 项目,它使用基于 cookie 的身份验证,我在 this stackoverflow thread 之后添加了一个 web api 端点。它就像一个魅力,但是当我用[Authorize] 装饰 api 控制器时,即使我在邮递员中提供用户名和密码,请求也无法验证。我希望ApiController 允许基于令牌的身份验证,同时将基于 cookie 的身份验证保留在 mvc 部分中。提前感谢您的帮助。

【问题讨论】:

  • 基于令牌的身份验证 -> JWT 还是 OAuth?
  • 基于 OAuth 令牌的身份验证

标签: c# asp.net asp.net-mvc authentication asp.net-web-api


【解决方案1】:

我假设您的应用程序中有单独的项目用于 Web API 和 MVC。

在 Web API 项目中,如果您创建一个身份验证为“个人用户帐户”的项目,它会自动将 OAuth 文件和相关代码添加到项目中。如果您创建一个没有身份验证的项目,您必须添加 Owin 中间件才能访问 OAuth 功能。

您将在 Statup.Auth.cs 文件中查看这些设置。

在 MVC 方面,默认身份验证是基于 cookie 的。要调用您的 Web API,您必须使用 HTTPClient。这应该返回一个令牌,您可以像这样将其添加到您的 DefaultRequestHeaders 中(我正在使用这种方法)。

其他选项是将令牌存储在 Sessions 中或将其添加到身份验证 Cookie。

希望对您有所帮助。:)

【讨论】:

    【解决方案2】:

    在 Visual Studio 2019 中,当您创建 Web API 项目模板并选择个人用户帐户进行身份验证时,vs 会为您实施基于令牌的身份验证,与Article 非常相似。唯一的区别是本文使用旧表来存储用户数据,而 Microsoft 的代码使用著名的 AspNetUsers 表。我强烈建议您按照文章,最后将 ApplicationOAuthProvider 文件中的 GrantResourceOwnerCredentials 方法替换为以下代码:

    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,
                CookieAuthenticationDefaults.AuthenticationType);
    
            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
    

    【讨论】:

      猜你喜欢
      • 2016-06-09
      • 2017-04-19
      • 1970-01-01
      • 1970-01-01
      • 2015-11-18
      • 2014-04-29
      • 2016-07-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多