2016-08-05 54 views
10

Tôi đang tạo một REST api trong ASP.NET Core 1.0. Tôi đã sử dụng Swagger để kiểm tra nhưng bây giờ tôi đã thêm ủy quyền JWT cho một số tuyến đường. (với UseJwtBearerAuthentication)Sử dụng JWT (Authorization: Bearer) trong Swagger trong ASP.NET Core 1.0

Có thể sửa đổi tiêu đề của yêu cầu Swagger để các tuyến đường có thuộc tính [Authorize] có thể được kiểm tra không?

Trả lời

16

tôi phải vật lộn với vấn đề tương tự và tìm thấy một giải pháp làm việc trong bài đăng trên blog này: http://blog.sluijsveld.com/28/01/2016/CustomSwaggerUIField

Nó đi xuống đến thêm này trong configurationoptions bạn

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

và mã cho operationfilter

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" 
     }); 
     } 
    } 
} 

Sau đó, bạn sẽ thấy một Hộp văn bản ủy quyền bổ sung trong thanh công cụ của bạn, nơi bạn có thể thêm toke của mình n trong định dạng 'Bearer {jwttoken}' và bạn nên được ủy quyền trong yêu cầu của bạn.

+0

nơi bạn lấy mã thông báo mang để đưa vào trường jwttoken khi sử dụng chức năng thử trong ui vênh? – emseetea

+0

Chỉ cần trợ giúp nhanh; sử dụng Microsoft.AspNetCore.Mvc.Authorization; sử dụng Swashbuckle.AspNetCore.Swagger; sử dụng Swashbuckle.AspNetCore.SwaggerGen; bằng System.Collections.Generic; bằng System.Linq; – statler

2

Để mở rộng câu trả lời của HansVG phù hợp với tôi (cảm ơn) và vì tôi không có đủ điểm đóng góp, tôi không thể trả lời trực tiếp câu hỏi emseetea. Một khi bạn có hộp văn bản ủy quyền, bạn sẽ cần phải gọi điểm cuối tạo ra mã thông báo mà sẽ nằm ngoài khu vực [Authorize] phải của thiết bị đầu cuối của bạn.

Khi bạn đã gọi điểm cuối đó để tạo mã thông báo từ điểm cuối, bạn có thể sao chép mã đó ra khỏi kết quả cho điểm cuối đó. Sau đó, bạn có mã thông báo để sử dụng trong các khu vực khác của bạn mà phải [Ủy quyền]. Chỉ cần dán nó vào hộp văn bản. Hãy chắc chắn rằng, như HansVG đã đề cập, để thêm nó vào đúng định dạng, cần phải bao gồm "bearer". Định dạng = "bearer {token}".

1

Hiện tại Swagger có chức năng xác thực với JWT-token và có thể tự động thêm mã thông báo vào tiêu đề (Tôi đang sử dụng Swashbuckle.AspNetCore 1.1.0).

enter image description here

Mã sau đây sẽ giúp đạt được điều này.

Trong 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" }, 
     //} 
    }); 
}); 

Kiểm tra và cấu hình TokenUrl nếu thiết bị đầu cuối của bạn là khác nhau.

Trong Startup.Configure():

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"); 
}); 

Nếu thiết bị đầu cuối của bạn để xác thực bằng thẻ theo tiêu chuẩn OAuth2, tất cả phải làm việc. Nhưng chỉ trong trường hợp, tôi đã thêm mẫu của điểm cuối này:

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

Tính năng này hoạt động, ngoại trừ khi UserId/Mật khẩu/Khách hàng/Bí mật không thành công, nó chỉ thất bại trong nền và vẫn hiển thị đăng nhập. – Whoever

+0

Vui lòng kiểm tra xem bạn có trả về mã trạng thái HTTP 400 không, nếu ủy quyền không thành công. Đó là yêu cầu từ RFC 6749 và Swagger cũng xử lý nó. Tôi đã cập nhật câu trả lời. –

+0

Có, tôi sử dụng IdentityServer 4 và nó trả về 400. Nhưng swagger UI hiển thị nút Logout như thể người dùng đã đăng nhập thành công. Tôi không chắc chắn làm thế nào để cấu hình mà swagger popup màn hình để hiển thị xác thực thất bại. – Whoever

Các vấn đề liên quan