簡體   English   中英

如何在 swagger 中訪問圖形 api?

[英]How to access graph api in swagger?

凈核心項目。 我的要求如下。 我在 .net 核心和 swagger 中有 webapi 項目。 我在 azure 廣告中創建了兩個應用程序。 現在我在 swagger 中有授權按鈕。 我想做如下授權。 如果用戶屬於名稱以 AP 開頭的任何組,我想授權這些用戶。 坦率地說,我在這里有點困惑。 現在我在 azure 中有兩個應用程序。 每當我通過 azure AD 中的 swagger/swagger 應用程序獲取令牌時,可以使用相同的令牌來訪問我的 api 嗎? 我將展示我的實現。

下面是我的appsettings.json

"AzureAd": {
    "Authority": "login.microsoftonline.com/common/v2.0",
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "[Enter the domain of your tenant, e.g. contoso.onmicrosoft.com]",
    "TenantId": "organizations",
    "ClientId": "my web api azure ad app client id",
    "CallbackPath": "/signin-oidc"
  },
  "Swagger": {
    "ClientId": "my swagger app azure ad app client id",
    "ClientSecret": "my secrete",
       "AuthorizationUrl": "https://login.microsoftonline.com/tenantid/oauth2/v2.0/authorize",
    "TokenUrl": "https://login.microsoftonline.com/tenantid/oauth2/v2.0/token"
  }

下面是我的啟動

      services
                       .AddAuthentication(o =>
                       {
                           o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;

                       })
                       .AddJwtBearer(o =>
                       {
                           o.Authority = azureActiveDirectoryOptions.Authority;
                           o.RequireHttpsMetadata = false;
                           o.TokenValidationParameters = new TokenValidationParameters
                           {

                               ValidAudiences = new List<string>
                               {
                                  azureActiveDirectoryOptions.AppIdUri,
                                  azureActiveDirectoryOptions.ClientId
                               },
                               ValidateIssuer = true,
                               ValidateAudience = true,
                               ValidIssuer = "https://myorg.onmicrosoft.com/oauth2/default",
                               RoleClaimType = ClaimTypes.Role,


                           };
                       });
      services.AddSwaggerGen(c =>
                {
                    c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });

                    c.AddSecurityDefinition("oauth2", new OAuth2Scheme
                    {
                        Type = "oauth2",
                        Flow = "implicit",
                        AuthorizationUrl = swaggerUIOptions.AuthorizationUrl,
                        TokenUrl = swaggerUIOptions.TokenUrl,
                        Scopes = new Dictionary<string, string>
                        {
                              {"User.read", "https://graph.microsoft.com/User.read" }
                        }
                    });
                    c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
                    {
                            { "oauth2", new[] { "readAccess", "writeAccess" } }
                    });
  services.AddAuthorization(options =>
            {
                options.AddPolicy("APGroupsOnly", policy =>
                       policy.Requirements.Add(new GroupsCheckRequirement("YourGroupID")));
            });

下面是配置方法。

 app.UseSwaggerUI(c =>
            {
                c.RoutePrefix = "swagger";
                c.OAuthClientId(swaggerUIOptions.ClientId);
                c.OAuthClientSecret(swaggerUIOptions.ClientSecret);
                c.OAuthRealm(azureActiveDirectoryOptions.ClientId);
                c.OAuthAppName("Swagger");
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });

這是我對要求的實現。 每當我運行 swagger 時,我都會得到令牌。 現在我想用這個令牌來調用圖 api。 獲得組詳細信息后,我想打我的 api。 現在我的困惑是,我在 swagger/swagger 應用程序中獲取令牌,所以相同的令牌可以用於獲取組詳細信息和授權 api 嗎? 有人可以指導我嗎? 任何幫助,將不勝感激。 謝謝

根據我的理解,目前您有:

  1. Swagger/Swagger 應用程序,我認為您的客戶將使用它來訪問您的 API。 我將其稱為客戶端應用程序。 在您的 AAD 中注冊了一個應用程序(APP-Client),用戶將獲得該應用程序的訪問令牌。

  2. 您的 Web API 服務器,受 AAD(APP-Server)保護並接受用戶請求。


工作流程是:

1)。 用戶在 Swagger 應用程序(使用 APP-Client)中獲取令牌(Token-For-API)。

2)。 用戶使用令牌 (Token-For-API) 調用您的應用程序。

3)。 您的 API 將為用戶調用 Graph API,並返回結果。


目前,您對步驟 1) 和 2) 沒有任何問題。 所以,接下來,我可能會給你一些關於3)的建議。

基於 Azure AD 開發者文檔,您可以使用代流。 您的 web API 服務器(守護程序應用程序)可以使用第一個令牌獲取新令牌以訪問 Microsoft Graph API 或其他 ZDB9742387184A。

以下是步驟:

A. 您需要在 AAD (APP-Server) 中為您的 API 添加 Graph API 的權限。

在此處輸入圖像描述

B.獲取一個新的token,用新的token調用graph API:

[HttpGet]
public IActionResult Get()
{
    // Web API app info
    string aadInstance = "https://login.microsoftonline.com/{0}";
    string tenant = "your tenant name or id, for example: hanxia.onmicrosoft.com";
    string clientId = "The app for your web API: 01801a37-****-****-****-baf08b61c63f";
    string clientSecret = "The secret of the app, OKg1UY/**********u@oao91P.p/";

    // Get the token which a user uses to access your API
    var token = _httpContextAccessor.HttpContext.GetTokenAsync("access_token").Result;

    // Get current user info
    var current = _httpContextAccessor.HttpContext.User;
    string userName = current.FindFirst(ClaimTypes.Upn) != null ? current.FindFirst(ClaimTypes.Upn).Value : current.FindFirst(ClaimTypes.Email).Value;

    // Create user assertion
    UserAssertion userAssertion = new UserAssertion(token, "urn:ietf:params:oauth:grant-type:jwt-bearer",userName);

    // Acquire a token of the user for graph
    string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
    AuthenticationContext authContext = new AuthenticationContext(authority);
    var graph_token = authContext.AcquireTokenAsync("https://graph.microsoft.com", new ClientCredential(clientId,clientSecret), userAssertion).Result.AccessToken;

    // Call graph
    string graphUrl = "https://graph.microsoft.com/v1.0/groups";

    HttpClient hc = new HttpClient();
    hc.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", graph_token);
    hc.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    hc.DefaultRequestHeaders.TryAddWithoutValidation("Cache-Control", "no-cache");

    var result = hc.GetAsync(graphUrl).Result.Content.ReadAsStringAsync().Result;
    hc.Dispose();

    return Ok(result);
}

最后,如果你想調用更多的圖API,你只需要在AAD中為你的Web API app(APP-Server)添加必要的權限。 要知道需要哪個權限,您可以參考具體的 API 文檔 例如,在這種情況下,您想獲取用戶的組信息,那么您可以調用List groups 然后,您需要至少添加以下權限之一:

在此處輸入圖像描述

暫無
暫無

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

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