小编S.A*_*nda的帖子

如何设置SwashBuckle.AspNetCore.Swagger以使用授权?

我使用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 });
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

昂首阔步

响应代码是Unauthorized 401,那么如何使用swagger授权呢?

我使用IdentityServer4设置了授权服务器.

授权服务器 - startup.cs

services.AddIdentityServer()
        .AddTemporarySigningCredential()
        .AddInMemoryPersistedGrants()
        .AddInMemoryIdentityResources(Config.GetIdentityResources())
        .AddInMemoryApiResources(Config.GetApiResources())
        .AddInMemoryClients(Config.GetClients())
        .AddAspNetIdentity<ApplicationUser>();
Run Code Online (Sandbox Code Playgroud)

授权服务器 - 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 …
Run Code Online (Sandbox Code Playgroud)

c# swagger swagger-ui asp.net-core identityserver4

12
推荐指数
3
解决办法
7364
查看次数

标签 统计

asp.net-core ×1

c# ×1

identityserver4 ×1

swagger ×1

swagger-ui ×1