2016-08-05 1 views

답변

16

나는 같은 문제로 고생이 블로그 게시물에서 작동하는 솔루션을 발견 : 당신의 configurationoptions

services.ConfigureSwaggerGen(options => 
{ 
    options.OperationFilter<AuthorizationHeaderParameterOperationFilter>(); 
}); 

과 operationfilter

의 코드이 추가로 내려 http://blog.sluijsveld.com/28/01/2016/CustomSwaggerUIField

그것은 온다

public class AuthorizationHeaderParameterOperationFilter : IOperationFilter 
{ 
    public void Apply(Operation operation, OperationFilterContext context) 
    { 
     var filterPipeline = context.ApiDescription.ActionDescriptor.FilterDescriptors; 
     var isAuthorized = filterPipeline.Select(filterInfo => filterInfo.Filter).Any(filter => filter is AuthorizeFilter); 
     var allowAnonymous = filterPipeline.Select(filterInfo => filterInfo.Filter).Any(filter => filter is IAllowAnonymousFilter); 

     if (isAuthorized && !allowAnonymous) 
     { 
      if (operation.Parameters == null) 
      operation.Parameters = new List<IParameter>(); 

      operation.Parameters.Add(new NonBodyParameter 
      {      
      Name = "Authorization", 
      In = "header", 
      Description = "access token", 
      Required = true, 
      Type = "string" 
     }); 
     } 
    } 
} 

그런 다음 토큰을 추가 할 수있는 권한 부여 텍스트 상자가 배지에 표시됩니다 n을 'Bearer {jwttoken}'형식으로 입력해야합니다. 그러면 위조 된 요청으로 승인을 받아야합니다.

+0

여기서 swagger UI에서 tryout 기능을 사용할 때 jwttoken 필드에 넣을 베어러 토큰을 구합니까? – emseetea

+0

그냥 빠른 도우미. Microsoft.AspNetCore.Mvc.Authorization을 (를) 사용합니다. using Swashbuckle.AspNetCore.Swagger; Swashbuckle.AspNetCore를 사용 중입니다.허풍 지옥; using System.Collections.Generic; using System.Linq; – statler

2

나를 위해 일한 HansVG 응답을 확장하려면 (감사합니다) 충분한 공헌 포인트가 없기 때문에 직접 emseetea 질문에 대답 할 수 없습니다. 권한 부여 텍스트 상자가 있으면 엔드 포인트의 [인증] 영역 외부에있을 토큰을 생성하는 엔드 포인트를 호출해야합니다.

엔드 포인트에서 토큰을 생성하도록 엔드 포인트를 호출했으면 해당 엔드 포인트에 대한 결과에서 해당 엔드 포인트를 복사 할 수 있습니다. 그런 다음 [승인]해야하는 다른 영역에서 사용할 토큰이 있습니다. 텍스트 상자에 붙여 넣기 만하면됩니다. HansVG에서 언급했듯이 올바른 형식으로 추가하려면 "무기명"을 포함시켜야합니다. Format = "무기명 {토큰}".

1

현재 Swagger는 JWT-token으로 인증 할 수있는 기능을 가지고 있으며 (Swashbuckle.AspNetCore 1.1.0을 사용하고 있습니다.) 헤더에 토큰을 자동으로 추가 할 수 있습니다.

enter image description here

다음 코드는이를 달성하는 데 도움이됩니다. Startup.ConfigureServices()에서

:

services.AddSwaggerGen(c => 
{ 
    // Your custom configuration 
    c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); 
    c.DescribeAllEnumsAsStrings(); 
    // JWT-token authentication by password 
    c.AddSecurityDefinition("oauth2", new OAuth2Scheme 
    { 
     Type = "oauth2", 
     Flow = "password", 
     TokenUrl = Path.Combine(HostingEnvironment.WebRootPath, "/token"), 
     // Optional scopes 
     //Scopes = new Dictionary<string, string> 
     //{ 
     // { "api-name", "my api" }, 
     //} 
    }); 
}); 

확인하고 엔드 포인트가 다른 경우 TokenUrl를 구성합니다. Startup.Configure()에서

: 토큰 인증을위한 엔드 포인트가 OAuth2를 표준을 따르는 경우

app.UseSwagger(); 
app.UseSwaggerUI(c => 
{ 
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "API V1"); 
    // Provide client ID, client secret, realm and application name (if need) 
    c.ConfigureOAuth2("swagger-ui", "swagger-ui-secret", "swagger-ui-realm", "Swagger UI"); 
}); 

, 모든 작동합니다. 그러나이 경우,이 엔드 포인트의 샘플을 추가했습니다.

public class AccountController : Controller 
{ 
    [ProducesResponseType(typeof(AccessTokens), (int)HttpStatusCode.OK)] 
    [ProducesResponseType((int)HttpStatusCode.BadRequest)] 
    [ProducesResponseType((int)HttpStatusCode.Unauthorized)] 
    [HttpPost("/token")] 
    public async Task<IActionResult> Token([FromForm] LoginModel loginModel) 
    { 
     switch (loginModel.grant_type) 
     { 
      case "password": 
       var accessTokens = // Authentication logic 
       if (accessTokens == null) 
        return BadRequest("Invalid user name or password."); 
       return new ObjectResult(accessTokens); 

      case "refresh_token": 
       var accessTokens = // Refresh token logic 
       if (accessTokens == null) 
        return Unauthorized(); 
       return new ObjectResult(accessTokens); 

      default: 
       return BadRequest("Unsupported grant type"); 
     } 
    } 
} 

public class LoginModel 
{ 
    [Required] 
    public string grant_type { get; set; } 

    public string username { get; set; } 
    public string password { get; set; } 
    public string refresh_token { get; set; } 
    // Optional 
    //public string scope { get; set; } 
} 

public class AccessTokens 
{ 
    public string access_token { get; set; } 
    public string refresh_token { get; set; } 
    public string token_type { get; set; } 
    public int expires_in { get; set; } 
} 
+0

UserId/Password/Client/Secret이 실패한 경우를 제외하고이 작업은 백그라운드에서 조용히 실패하고 로그인 한 상태로 표시됩니다. – Whoever

+0

인증에 실패하면 HTTP 상태 코드 400이 반환되는지 확인하십시오. RFC 6749의 요구 사항이며 Swagger도 처리합니다. 답변을 업데이트했습니다. –

+0

예, IdentityServer 4를 사용하고 400을 반환합니다.하지만 사용자가 성공적으로 로그인 한 것처럼 Swagger UI에 로그 아웃 버튼이 표시됩니다. 인증을 보여주기 위해 위풍 당당한 팝업 화면을 구성하는 방법을 모르겠습니다. – Whoever