簡體   English   中英

在標頭中傳遞令牌以在 MVC 和 Web API 中進行身份驗證

[英]Pass token in header for authentication in MVC and Web API

將 MVC 應用程序與 Web API 集成,Azure 用戶身份驗證是使用 OWIN 完成的,想要刪除身份驗證 cookie 並在標頭中傳遞令牌以進行 api 調用。 怎么做? 我使用 MSAL.cs 文件進行 Azure AD 身份驗證。 想要在 api 調用標頭中傳遞令牌。 首先加載 MVC 應用程序頁面,認證后調用 web api 方法。 我使用以下代碼進行 azure AD autherization,

 private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
            {
                // Extract the code from the response notification
                var code = notification.Code;

                string signedInUserID = notification.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                TokenCache userTokenCache = new MSALSessionCache(signedInUserID, notification.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance();
                ConfidentialClientApplication cca = new ConfidentialClientApplication(ClientId, Authority, RedirectUri, new ClientCredential(ClientSecret), userTokenCache, null);
                try
                {
                    AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, Scopes);
                }
                catch (Exception ex)
                {
                    //TODO: Handle
                    throw;
                }
            }

首次使用 ASP.Net OpenID Connect OWIN 中間件從 azure ad 登錄用戶后,如果要調用 web api,可以將令牌添加到請求標頭:

string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").Value;
string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
string authority = String.Format(CultureInfo.InvariantCulture, Startup.aadInstance, tenantID, string.Empty);
ClientCredential credential = new ClientCredential(Startup.clientSecret);

// Here you ask for a token using the web app's clientId as the scope, since the web app and service share the same clientId.
app = new ConfidentialClientApplication(Startup.clientId, redirectUri, credential, new NaiveSessionCache(userObjectID, this.HttpContext)){};
result = await app.AcquireTokenSilentAsync(new string[] { Startup.clientId });

 HttpClient client = new HttpClient();
 HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, serviceUrl + "/api/todolist");
 request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.Token);

 HttpResponseMessage response = await client.SendAsync(request);

請參閱代碼示例以獲取更多詳細信息。

暫無
暫無

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

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