【问题标题】:swagger oauth security definitionswagger oauth 安全定义
【发布时间】:2018-06-11 23:08:55
【问题描述】:

在我当前的 webapi 项目中,我设置了一个带有隐式流和授权 url https://login.microsoftonline.com/ + 租户 ID 的 swagger oauth 安全定义。范围与 Swashbuckle.AspNetCore nuget 的 github 示例中的范围相同,这是链接 https://github.com/domaindrivendev/Swashbuckle.AspNetCore。但是,当我尝试在 swagger 在线编辑器(https://editor.swagger.io/)上进行身份验证时,我无法取回令牌并获得 404 异常。我需要在我的 azure 门户注册应用程序中设置什么才能将令牌返回到在线 Swagger 编辑器?

【问题讨论】:

标签: c# azure oauth-2.0 swagger


【解决方案1】:

根据您的描述,我创建了我的 .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 应用的权限,如下所示:

然后,我添加了如下代码 sn-p 用于定义 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参数没有指定。然后,我为ConfigureOAuth2 设置了additionalQueryStringParameters 参数。这是我的代码示例WebAPI-Swagger-NetCore,你可以参考一下。

此外,要向资源应用程序 (Web API) 添加访问范围,您可以按照here 下的向资源应用程序添加访问范围 部分进行操作。此外,我的SecurityRequirementsOperationFilter 没有根据AuthorizeAttribute 提供的here 将范围要求分配给操作。您可以在AddSecurityDefinition 下指定支持的范围,然后对于您的控制器或操作,您可以将其标记为[Authorize(AuthenticationSchemes = "Bearer", Policy = "{scope}")]。详情,你可以关注这个sample

【讨论】:

    猜你喜欢
    • 2020-02-29
    • 1970-01-01
    • 2017-08-06
    • 2021-11-28
    • 1970-01-01
    • 2018-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多