简体   繁体   English

如何在基于 cookie 身份验证的 asp.net mvc 项目中向 web api 添加令牌身份验证

[英]How to Add token authentication to web api in cookie authentication based asp.net mvc project

I have this asp.net mvc project that uses cookie based authentication and i added a web api endpoint to it following this stackoverflow thread .我有这个 asp.net mvc 项目,它使用基于 cookie 的身份验证,我在这个 stackoverflow 线程之后添加了一个 web api 端点。 It worked like a charm but when i decorate the api controller with an [Authorize] , the requests fail to authenticate even when I provide username and password in postman.它就像一个魅力但是当我用[Authorize]装饰 api controller 时,即使我在 postman 中提供用户名和密码,请求也无法验证。 I would like the ApiController to allow token based authentication while keeping the cookie based authentication in the mvc part.我希望ApiController允许基于令牌的身份验证,同时将基于 cookie 的身份验证保留在 mvc 部分中。 Thanks in advance for any help.提前感谢您的帮助。

I am assuming you have separate projects in your applications for Web API and MVC.我假设您在 Web API 和 MVC 的应用程序中有单独的项目。

In the Web API project, if you create a project with authentication as 'Individual User Accounts', it automatically adds OAuth files and related code to the project.在Web API项目中,如果你创建一个认证为“个人用户账户”的项目,它会自动将OAuth文件和相关代码添加到项目中。 If you create a project with No Authentication, you have to add the Owin Middleware to access OAuth feature.如果您创建一个没有身份验证的项目,则必须添加 Owin 中间件才能访问 OAuth 功能。

You will be looking at these settings in Statup.Auth.cs file.您将在 Statup.Auth.cs 文件中查看这些设置。 在此处输入图像描述

On the MVC side, the default authentication is cookie based.在 MVC 端,默认的身份验证是基于 cookie 的。 To call your Web APIs, you have to use HTTPClient .要调用您的 Web API,您必须使用HTTPClient This should return a token which you can add to your DefaultRequestHeaders like this (I am using this approach).这应该返回一个令牌,您可以像这样将其添加到DefaultRequestHeaders中(我正在使用这种方法)。 在此处输入图像描述

Other option is to store the token in Sessions or add it to the Authentication Cookie.其他选项是将令牌存储在会话中或将其添加到身份验证 Cookie。

I hope you will find this helpful.:)我希望你会发现这对你有帮助。:)

In Visual Studio 2019 when you create a Web API project template and select Individual User Accounts for Authentication, the vs implement a Token-Based Authentication for you very similar to this Article .在 Visual Studio 2019 中,当您创建 Web API 项目模板和 select 用于您的身份验证的个人用户帐户时,vs 实现了与此非常相似的Article Token-BasedAuthentication the only difference is that the article uses a legacy table for storing user data and Microsoft's code uses the famous AspNetUsers table.唯一的区别是本文使用旧表来存储用户数据,而 Microsoft 的代码使用著名的 AspNetUsers 表。 I strongly recommend you to follow the article and at the end replace the GrantResourceOwnerCredentials method in the ApplicationOAuthProvider file with the following code:我强烈建议您按照这篇文章,最后将 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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM