在我目前的webapi项目中,我设置了一个带有隐式流的swagger oauth安全定义,并授权url https://login.microsoftonline.com/ + tenant Id。范围与Swashbuckle.AspNetCore nuget的github exapmle中的相同,这是链接https://github.com/domaindrivendev/Swashbuckle.AspNetCore。但是当我尝试在swagger在线编辑器上进行身份验证时,这个https://editor.swagger.io/,我无法获得令牌并获得404异常。我需要在我的Azure门户注册应用程序中设置什么才能将令牌返回给在线招摇编辑器?
根据您的描述,我创建了我的.Net Core 2.0 Web API应用程序并在Azure门户上创建了AAD应用程序。 ConfigureServices下的配置如下所示:
services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
// Configure the app to use Jwt Bearer Authentication
.AddJwtBearer(jwtOptions =>
{
jwtOptions.Authority = string.Format(CultureInfo.InvariantCulture, "https://sts.windows.net/{0}/", Configuration["AzureAd:TenantId"]);
jwtOptions.Audience = Configuration["AzureAd:WebApiApp:ClientId"];
});
对于Swagger UI,我还在Azure门户上创建了一个新的AAD应用程序,并添加了访问Web API应用程序的权限,如下所示:
然后,我添加了以下代码片段来定义OAuth2.0方案,如下所示:
// Define the OAuth2.0 scheme that's in use (i.e. Implicit Flow)
c.AddSecurityDefinition("oauth2", new OAuth2Scheme
{
Type = "oauth2",
Flow = "implicit",
AuthorizationUrl = string.Format(CultureInfo.InvariantCulture, "https://login.microsoftonline.com/{0}/oauth2/authorize", Configuration["AzureAd:TenantId"]),
Scopes = new Dictionary<string, string>
{
{ "user_impersonation", "Access Bruce-WebAPI-NetCore" }
}
});
// Enable operation filter based on AuthorizeAttribute
c.OperationFilter<SecurityRequirementsOperationFilter>();
并使用以下代码初始化中间件以提供swagger-ui。
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
c.ConfigureOAuth2(
Configuration["AzureAd:SwaggerApp:ClientId"],
Configuration["AzureAd:SwaggerApp:ClientSecret"],
Configuration["AzureAd:SwaggerApp:RedirectUri"], //http://localhost:30504/swagger/o2c.html
"Bruce-WebAPI-NetCore-Swagger",
additionalQueryStringParameters: new Dictionary<string, string>(){
{ "resource",Configuration["AzureAd:WebApiApp:ClientId"]}
});
});
测试:
但它仍然返回AADSTS50001未提供资源标识符
在我处理过程中,我遇到了类似的问题。最后,我发现没有指定resource
参数。然后,我为additionalQueryStringParameters
设置了ConfigureOAuth2
参数。这是我的代码示例WebAPI-Swagger-NetCore,你可以参考它。
此外,要将访问范围添加到资源应用程序(Web API),可以按照here下的“将访问范围添加到资源应用程序”部分进行操作。此外,我的SecurityRequirementsOperationFilter
没有将范围要求分配给基于AuthorizeAttribute
提供here的操作。您可以在AddSecurityDefinition
下指定支持的范围,然后对于您的控制器或操作,您可以将其标记为[Authorize(AuthenticationSchemes = "Bearer", Policy = "{scope}")]
。细节,你可以按照这个sample。