Sunday, February 11, 2018

Struggling with Swagger authorization field; ASP.NET Core 2.0 Web API

Alrighty, so my Google-fu is failing me today. I am coming up with many Github conversations that I do not fully understand, and although this question is verbose, it boils down to this:

How can I selectively apply a Swagger IOperationFilter ONLY to chosen Controllers/Action Methods?.

I welcome you to read on:

I've got a new ASP.NET Core 2.0 Web API. Within this API I have 6 API Controllers, 5 of which must have a mandatory header for authorization; e.g. "bearer abcd1234---(elided)"

I've implemented JWT Bearer Token authorization, which happily consumes the auth header and it works as it should.

Where I am struggling is that I've implemented an IOperation filter for the Swagger UI/doc generator:

public class AddAuthHeaderParameter : IOperationFilter { public void Apply(Operation operation, OperationFilterContext context) { if (operation.Parameters == null) { operation.Parameters = new List<IParameter>(); } operation.Parameters.Add(new Parameter { Name = "Authorization", @In = "header", Type = "string", Required = true }); } } 

Which is invoked within Startup.cs as expected:

services.AddSwaggerGen(options => { options.SwaggerDoc(/* elided */); options.OperationFilter<AddAuthHeaderParameter>(); }); 

However, when I am viewing the generated Swagger UI, the (required) Authorization parameter is visible on all Controller Actions. I need for the Controller named Auth to allow for anonymous access.

To be clear, it does, even through Swagger. However the Authorization header is rendering on the Swagger UI, and will not accept a null entry. Meaning that I must enter a value into Auth, even if it's garbage. This obviously isn't how I want to implement my Controller.

Here are the method definitions of my AuthController class, specifically /api/Auth/register and /api/Auth/token which are intended to be accessible anonymously.

Register: accepts a Username, Email, and Password to create a new User.

// POST: api/auth/register [AllowAnonymous] [HttpPost] [Route("register")] public async Task<IActionResult> Register([FromBody] RegisterViewModel model) { 

And CreateToken: accepts a Username, Email, and Password to queries the back end and issues a JWT Bearer Token if applicable.

// POST: api/auth/token [AllowAnonymous] [ValidateForm] [HttpPost] [Route("token")] public async Task<IActionResult> CreateToken([FromBody] LoginViewModel model) { 

I believe that my problem may simply be that I don't know how to use the correct Attributes to apply the Swagger IOperationFilter invocation of AddAuthHeaderParameter selectively to chosen Controllers/Action Methods, versus my current blanket approach.

Can anyone help with this one?

Struggling with Swagger authorization field; ASP.NET Core 2.0 Web API Click here
  • Blogger Comment
  • Facebook Comment

0 comments:

Post a Comment

The webdev Team