簡體   English   中英

如何在基於 cookie 身份驗證的 asp.net mvc 項目中向 web api 添加令牌身份驗證

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

我有這個 asp.net mvc 項目,它使用基於 cookie 的身份驗證,我在這個 stackoverflow 線程之后添加了一個 web api 端點。 它就像一個魅力但是當我用[Authorize]裝飾 api controller 時,即使我在 postman 中提供用戶名和密碼,請求也無法驗證。 我希望ApiController允許基於令牌的身份驗證,同時將基於 cookie 的身份驗證保留在 mvc 部分中。 提前感謝您的幫助。

我假設您在 Web API 和 MVC 的應用程序中有單獨的項目。

在Web API項目中,如果你創建一個認證為“個人用戶賬戶”的項目,它會自動將OAuth文件和相關代碼添加到項目中。 如果您創建一個沒有身份驗證的項目,則必須添加 Owin 中間件才能訪問 OAuth 功能。

您將在 Statup.Auth.cs 文件中查看這些設置。 在此處輸入圖像描述

在 MVC 端,默認的身份驗證是基於 cookie 的。 要調用您的 Web API,您必須使用HTTPClient 這應該返回一個令牌,您可以像這樣將其添加到DefaultRequestHeaders中(我正在使用這種方法)。 在此處輸入圖像描述

其他選項是將令牌存儲在會話中或將其添加到身份驗證 Cookie。

我希望你會發現這對你有幫助。:)

在 Visual Studio 2019 中,當您創建 Web API 項目模板和 select 用於您的身份驗證的個人用戶帳戶時,vs 實現了與此非常相似的Article Token-BasedAuthentication 唯一的區別是本文使用舊表來存儲用戶數據,而 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);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM