簡體   English   中英

在 .NET core 2 MVC 應用程序中配置 JWT 訪問令牌

[英]Configure JWT Access Token in .NET core 2 MVC application

我成功地從控制台應用程序中的 Azure Active Directory 檢索了授權令牌。 我想將此代碼轉換為 .Net Core MVC,但不確定如何在 Startup.cs 中干凈地配置所有內容

我假設鍵/值對將移動到 appsettings.json,但如何在ConfigureServices()下獲取此令牌?

    var client = new HttpClient();

    var uri = "https://login.microsoftonline.com/<tenantid>/oauth2/token";

    var pairs = new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("resource", "{resourceID}"),
        new KeyValuePair<string, string>("client_id", "{clientID}"),
        new KeyValuePair<string, string>("client_secret", "{clientSecret}"),
        new KeyValuePair<string, string>("grant_type", "client_credentials"),
        new KeyValuePair<string, string>("scope", "openid")
     };

    var content = new FormUrlEncodedContent(pairs);
    var response = client.PostAsync(uri, content).Result;

    string result = string.Empty;

    if (response.IsSuccessStatusCode)
    {
        result = response.Content.ReadAsStringAsync().Result;
        JObject jObject = JObject.Parse(result);
        string token = (string)jObject.SelectToken("access_token");
    }

我應該使用以下方法之一來獲取不記名令牌嗎? 我正在控制台應用程序中執行 POST,但這似乎不適合啟動配置。

services.AddAuthentication() 

或者

.AddJwtBearer()

我讓它運行並進行身份驗證,但它不提供身份驗證令牌。

正如 Jean 所說,您可以使用 Microsoft 身份驗證庫 (MSAL),該庫可幫助您開發使用 v2.0 端點的應用程序,在這里您可以使用它來獲取訪問令牌。

此處的范圍是您要附加.default的資源。 參考這篇文章

此請求中為 scope 參數傳遞的值應該是您想要的資源的資源標識符(應用程序 ID URI),並附加.default后綴。 對於 Microsoft Graph 示例,該值為https://graph.microsoft.com/.default 此值通知 v2.0 端點您為應用程序配置的所有直接應用程序權限,它應該為與您要使用的資源關聯的權限發出令牌。

以下是C# MSAL 示例代碼,獲取該應用權限場景的訪問令牌。您需要在您的項目中安裝NuGet 包Microsoft.Identity.Client

ConfidentialClientApplication app = new ConfidentialClientApplication("clientId",
    "https://login.microsoftonline.com/tenantId/v2.0",
    "redirectUrl",
    new ClientCredential("clientSecret"),
    new TokenCache(),null);
AuthenticationResult authResult = app.AcquireTokenForClientAsync(
    new string[] { "https://graph.microsoft.com/.default"}).Result;
var token = authResult.AccessToken;

在這里,您可以將Microsoft Graph API更改為您的 API Application ID URI ,有關添加權限等的更多詳細信息,您可以參考這篇文章

您可以改用 OWIN 啟動類。 請參閱 Microsoft 的此示例

https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-v1-aspnet-webapp

暫無
暫無

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

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