【发布时间】:2018-06-11 17:51:14
【问题描述】:
我正在尝试使用 AzureAD 在 swagger 中获取令牌并用它测试我的控制器。
这里我用 swagger-ui 登录:
在这之后没有使用我的个人 AzureAD ID,我已经登录了。
但是当我尝试使用我的控制器时,出现错误:Unauthorized
我的控制器都继承自 baseController。它们都有 [Authorize] 注释。
我真的不知道问题出在哪里。 我正在使用 Swashbuckle.AspNetCore v2.5.0
一些配置代码。
Statup.cs
public virtual void ConfigureServices(IServiceCollection services)
{
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Audience = "{client_id}";
options.Authority = "https://login.microsoftonline.com/{tenant_id}";
});
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v2", new Info
{
Title = "API",
Version = "v2",
Description = "Api Help",
Contact = new Contact()
{
Name = "John Doe",
Email = "john.doe@somewhere.com"
}
});
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
options.IncludeXmlComments(xmlPath);
options.AddSecurityDefinition("OAuth2", new OAuth2Scheme()
{
Flow = "implicit",
Type = "oauth2",
TokenUrl = "https://login.microsoftonline.com/{tenant_id}/oauth2/token",
Description = "OAuth2 Implicit Grant",
AuthorizationUrl = "https://login.microsoftonline.com/{tenant_id}/oauth2/authorize",
Scopes = new Dictionary<string, string>()
{
{ "user_impersonation", "Access api" }
}
});
options.OperationFilter<FileOperation>();
options.DescribeAllEnumsAsStrings();
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMiddleware<ExceptionHandlerMiddleware>();
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("../swagger/v2/swagger.json", "API V2");
c.RoutePrefix = "Help";
c.OAuthClientId("{client_id_swagger_app}"); //Swagger
//c.OAuthClientId("client_id_api_app"); //api
c.DisplayRequestDuration();
c.OAuthClientSecret("{secret_client_key_swagger}"); //swagger secret
c.OAuthAppName("Swagger");
c.OAuthRealm("http://localhost:1234/swagger/ui/o2c-html");
c.OAuthScopeSeparator(" ");
c.OAuthUseBasicAuthenticationWithAccessCodeGrant();
c.OAuthAdditionalQueryStringParams(new Dictionary<string, string>
{
{ "resource", "{app_ID_URI}"} //api
});
});
app.UseAuthentication();
app.UseMvc();
}
【问题讨论】:
-
你在使用 Swashbuckle 吗?
-
您能分享一个指向您的 API 的链接吗?
-
这是本地的,我没有。为什么需要链接?
-
如果您提供了正确的 {client_id} 和 {client_key} 这应该可以工作,这就是为什么我希望看到您的 API 正在运行...当您单击 UI 中的 [Authorize] 时会发生什么?
-
一个选项卡会立即打开和关闭,然后“授权”按钮会在“注销”中转换,我猜这是正常的。 Swagger 不使用任何东西进行连接。 'curl -X GET "localhost:1234/Account" -H "accept: application/json" '
标签: c# swagger azure-active-directory swagger-ui swashbuckle