繁体   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