C# 大摇大摆的Azure AD OAuth2令牌不是';不曾

C# 大摇大摆的Azure AD OAuth2令牌不是';不曾,c#,swagger,azure-active-directory,swagger-ui,swashbuckle,C#,Swagger,Azure Active Directory,Swagger Ui,Swashbuckle,我正试图使用AzureAD在swagger中获得一个令牌,并用它测试我的控制器 在这里,我使用swagger ui登录: 就在这之后,不用我的AzureAD个人Id,我已经登录了 但是当我尝试使用我的控制器时,我出现了错误:Unauthorized 我的控制器都继承自baseController。它们都有[Authorize]注释 我真的不知道问题出在哪里。 我使用的是Swashback.AspNetCore v2.5.0 一些配置代码 副学士 公共虚拟void配置服务(IServiceCo

我正试图使用AzureAD在swagger中获得一个令牌,并用它测试我的控制器

在这里,我使用swagger ui登录:

就在这之后,不用我的AzureAD个人Id,我已经登录了

但是当我尝试使用我的控制器时,我出现了错误:
Unauthorized

我的控制器都继承自baseController。它们都有[Authorize]注释

我真的不知道问题出在哪里。 我使用的是Swashback.AspNetCore v2.5.0

一些配置代码

副学士

公共虚拟void配置服务(IServiceCollection服务)
{
服务
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(选项=>
{
options.academy=“{client_id}”;
选项。权限=”https://login.microsoftonline.com/{租户_id}”;
});
services.AddSwaggerGen(选项=>
{
选项。SwaggerDoc(“v2”),新信息
{
Title=“API”,
Version=“v2”,
Description=“Api帮助”,
联系人=新联系人()
{
Name=“John Doe”,
Email=“约翰。doe@somewhere.com"
}
});
var xmlFile=$“{Assembly.getExecutionGassembly().GetName().Name}.xml”;
var xmlPath=Path.Combine(AppContext.BaseDirectory,xmlFile);
选项。includexmlcoments(xmlPath);
options.AddSecurityDefinition(“OAuth2”,新的OAuth2Scheme()
{
Flow=“隐式”,
Type=“oauth2”,
令牌URL=”https://login.microsoftonline.com/{tenant_id}/oauth2/token“,
Description=“OAuth2隐式授权”,
授权URL=”https://login.microsoftonline.com/{tenant_id}/oauth2/authorize“,
范围=新字典()
{
{“用户模拟”,“访问api”}
}
});
options.OperationFilter();
options.descripbeAllenumsasstrings();
});
}
公共无效配置(IApplicationBuilder应用程序,IHostingEnvironment环境)
{
app.UseMiddleware();
//使中间件能够将生成的Swagger作为JSON端点提供服务。
app.UseSwagger();
//允许中间件为swagger ui(HTML、JS、CSS等)提供服务,并指定swagger JSON端点。
app.UseSwaggerUI(c=>
{
c、 SwaggerEndpoint(“../swagger/v2/swagger.json”,“API v2”);
c、 RoutePrefix=“帮助”;
c、 OAuthClientId(“{client_id_swagger_app}”);//swagger
//c、 OAuthClientId(“客户端id\u api\u应用程序”);//api
c、 DisplayRequestDuration();
c、 OAuthClientSecret(“{secret_client_key_swagger}”);//swagger secret
c、 OAuthAppName(“大摇大摆”);
c、 OAuthRealm(“http://localhost:1234/swagger/ui/o2c-html);;
c、 OAuthScope分隔符(“”);
c、 OAuthUseBasicAuthenticationWithAccessCodeGrant();
c、 OAuthAdditionalQueryStringParams(新字典
{
{“资源”,{app_ID_URI}}//api
});
});
app.UseAuthentication();
app.UseMvc();
}

您已将Swagger UI配置为使用资源获取访问令牌:

c.OAuthAdditionalQueryStringParams(new Dictionary<string, string>
    {
        { "resource", "{app_ID_URI}"} //api
    });
使用App ID URI的大摇大摆的UI很好,您可以将API配置为同时接受客户端ID和URI作为访问群体(Azure AD允许同时使用这两个,那么为什么不将您的API配置为这样呢?)

并定义每个操作都需要OAuth作用域的筛选器:

public class AuthenticationOperationFilter : IOperationFilter
{
    public void Apply(Operation operation, OperationFilterContext context)
    {
        operation.Security = new List<IDictionary<string, IEnumerable<string>>>
        {
            new Dictionary<string, IEnumerable<string>>
            {
                //Note "OAuth2" casing here must match the definition you use in Swagger UI config
                ["OAuth2"] = new List<string>{ "user_impersonation" }
            }
        };
    }
}
公共类AuthenticationOperationFilter:IOperationFilter
{
公共无效应用(操作,操作筛选器上下文)
{
operation.Security=新列表
{
新词典
{
//注意:此处的“OAuth2”大小写必须与您在Swagger UI配置中使用的定义相匹配
[“OAuth2”]=新列表{“用户模拟”}
}
};
}
}
您在Swagger UI配置中定义的内容定义了用户在使用UI时可以选择的范围。 请记住,因为您使用的是Azure AD v1端点,所以您选择的作用域并不重要。
令牌将始终包含已同意的作用域,不多不少。

您使用的是Swashback吗?您可以共享指向API的链接吗?它是本地的,我没有。为什么你需要一个链接?如果你提供了正确的{client_id}和{client_key},这应该可以工作,这就是为什么我希望看到你的API在运行。。。当你点击UI中的[Authorize]时会发生什么?一个选项卡会立即打开和关闭,然后“Authorize”按钮会转换为“Logout”,我想这是正常的。斯威格不使用任何东西来连接curl-X GET”“-H”accept:application/json“’这并不能解决我的实际问题,但谢谢,我的端点旁边没有锁,我认为这是我的错误啊,我想它没有添加端点的安全要求?午餐后,我将编辑我的答案以添加一个这样的示例:)我添加了一个我当前使用的操作筛选器的简化示例,以显示如何将要求添加到API操作。是的!就这样!非常感谢!:)
options.Audience = "{client_id}";
options.TokenValidationParameters = new TokenValidationParameters
{
    ValidAudiences = new List<string>{ "client-id", "app-id-uri"}
};
options.OperationFilter<AuthenticationOperationFilter>();
public class AuthenticationOperationFilter : IOperationFilter
{
    public void Apply(Operation operation, OperationFilterContext context)
    {
        operation.Security = new List<IDictionary<string, IEnumerable<string>>>
        {
            new Dictionary<string, IEnumerable<string>>
            {
                //Note "OAuth2" casing here must match the definition you use in Swagger UI config
                ["OAuth2"] = new List<string>{ "user_impersonation" }
            }
        };
    }
}