Asp.net core 如何在swagger中访问图形api?
net核心项目。我的要求如下。我在.NETCore和swagger中有webapi项目。我在azure广告中创建了两个应用程序。现在我在swagger中有了授权按钮。我想做如下授权。如果用户属于名称以AP开头的任何组,我想授权这些用户。坦率地说,我有点困惑。现在我在azure中有两个应用程序。每当我通过azure广告中的swagger/swagger应用程序获得令牌时,相同的令牌可以用来攻击我的API?我将展示我的实现 下面是我的appsettings.jsonAsp.net core 如何在swagger中访问图形api?,asp.net-core,jwt,azure-active-directory,swagger,Asp.net Core,Jwt,Azure Active Directory,Swagger,net核心项目。我的要求如下。我在.NETCore和swagger中有webapi项目。我在azure广告中创建了两个应用程序。现在我在swagger中有了授权按钮。我想做如下授权。如果用户属于名称以AP开头的任何组,我想授权这些用户。坦率地说,我有点困惑。现在我在azure中有两个应用程序。每当我通过azure广告中的swagger/swagger应用程序获得令牌时,相同的令牌可以用来攻击我的API?我将展示我的实现 下面是我的appsettings.json "AzureAd": {
"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")));
});
这是我的需求实现。每当我大摇大摆地跑的时候,我都会得到令牌。现在我想使用这个令牌来调用graph api。在获得组详细信息后,我想点击我的api。现在我的困惑是,我在swagger/swagger应用程序中获得了令牌,所以相同的令牌可以用于获取组详细信息和授权API吗?有人能在这方面指导我吗?任何帮助都将不胜感激。谢谢根据我的理解,目前您有:
工作流程是: 1) 。用户在Swagger应用程序(使用应用程序客户端)中获得令牌(API令牌) 2) 。用户使用令牌(API令牌)调用您的应用程序 3) 。您的API将为用户调用Graph API,并返回结果
目前,步骤1)和2)没有问题。所以,接下来,我可以给你一些关于3)的建议 基于Azure AD developer文档,您可以代表flow使用。您的web API服务器(守护程序应用程序)可以使用第一个令牌获取用于访问Microsoft Graph API或其他API的新令牌 以下是步骤: A.您需要为AAD(应用服务器)中的API添加Graph API权限 B.获取新令牌,并使用新令牌调用图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应用程序(应用程序服务器)添加必要的权限即可。要了解需要哪些权限,您可以参考特定的。例如,在这种情况下,您希望获取用户的组信息,然后可以调用。然后,您需要至少添加以下权限之一:
你能简化这个问题吗?您是否希望使用相同的令牌从两个应用程序调用Graph API?嗨,Prashant。我想使用组来实施授权。我的委托人大摇大摆。我在azure广告中有两个应用程序用于swagger和we 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);
}