【发布时间】:2018-01-28 23:22:14
【问题描述】:
我已经使用 Swashbuckle.AspNetCore.Swagger 记录了我的 api,我想使用 swagger ui 测试一些具有 Authorize 属性的资源。
api
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
namespace Api.Controllers
{
[Route("[controller]")]
[Authorize]
public class IdentityController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
}
}
}
响应码是 Unauthorized 401,那么如何使用 swagger 来授权呢?
我有一个使用 IdentityServer4 的授权服务器设置。
授权服务器 - startup.cs
services.AddIdentityServer()
.AddTemporarySigningCredential()
.AddInMemoryPersistedGrants()
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients())
.AddAspNetIdentity<ApplicationUser>();
授权服务器 - config.cs
public class Config
{
// scopes define the resources in your system
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
};
}
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource("api1", "My API")
};
}
...
...
}
api - 启动.cs
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,
ECommerceDbContext context)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
Authority = "http://localhost:5000/",
RequireHttpsMetadata = false,
AutomaticAuthenticate = true,
ApiName = "api1"
});
// 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/v1/swagger.json", "My API V1");
});
DbInitialiser.Init(context);
app.UseMvc();
}
我想要一个授权按钮,该按钮重定向到登录屏幕,然后授予对用户有权访问的 api 资源的访问权限。 是否可以使用 asp.net core 1.1 Swagger 中间件来做到这一点?或者我是否需要编写一些从 IdentityServer4 授权服务器获取令牌的 javascript? 请帮忙,因为我是身份验证和授权的新手
【问题讨论】:
标签: c# asp.net-core swagger swagger-ui identityserver4