I'd like to have the automatically generate output of NSwagStudio to contain an [Authorize] attribute.
I try to program an API with NSwagStudio and to secure it with [Authorize], such that my automatically generated controller code from NSwagStudio looks like this:
/// <summary>
/// Returns a list of Things.
/// </summary>
/// <returns>A JSON array of Things</returns>
[Microsoft.AspNetCore.Mvc.HttpGet, Microsoft.AspNetCore.Mvc.Route("Thing", Name = "Thing"), Authorize(Roles = "User")]
public System.Threading.Tasks.Task<System.Collections.Generic.ICollection<Thing>> Machine()
{
return _implementation.ThingAsync();
}
I added the
[Authorize(Roles = "User")]
attribute manually, which works fine, but what do I have to put in the OpenAPI specification, to write the attribute to a specific API path automatically?
/Thing:
get:
summary: Returns a list of Things.
responses:
"200": # status code
description: A JSON array of Things
content:
application/json:
schema:
type: array
items:
$ref: "#/components/schemas/Thing"
I don't believe that at this point in time (currently using v13.18.2 of NSwag) that it supports this. If you're only looking to decorate the controller, then you can take advantage of the fact that the controller classes are written as partial classes, so you can add your own partial class with the appropriate tag.
(don't forget the file needs to be in the same namespace and same assembly as the generated class). It's manual, but at least when you rebuild the generated classes, your customisation won't get deleted.
If you're wanting to decorate individual classes with attributes set from the OpenAPI spec, then you're in the same boat I am in! I believe the solution is to create a customised Liquid template (for
Controller.Methods.Annotations.liquid). You can follow my progress as such in the GitHub issue #2478.