3

I'm building an API where I have a couple of endpoints where I need the User ID, so after getting the idea from the most voted answer (not the accepted one) from this post: ASP.NET MVC Pass object from Custom Action Filter to Action.

I created an Action Filter that I can set up just with the [UserIdFromToken] attribute.

So I'm basically getting the User ID through this Action Filter that gets it from the authorization header this way:

[Authorize]
[UserIdFromToken]
public IActionResult Get(Guid userId /* Got from the [UserIdFromToken] filter */)
{
   return Ok(_userService.Get(userId));
}

The only problem is now it's showing the parameter userId as a Required parameter (and I don't want to show it at all) in my Swagger documentation, which is obviously false, since I don't need any input beyond the authorization header.

Is there any way to get my swagger documentation cleaner, without showing this parameter?

Do you think it would be better to try another approach to get the userId such as the accepted option from the post I sent above?

Ferran R.
  • 174
  • 1
  • 12
  • I know nothing of Swagger, but does using `Guid userId = null` fix the problem? I also note that you don't ever _use_ the value of `userId` anywhere, but I assume you just truncated it from your example. – D Stanley May 27 '20 at 19:06
  • @DStanley Sorry, I already edited my question, since I'm actually using the `userId` in the action method. I can't set the `Guid userId = null` since a Guid can't be null, but that would just give a new Guid as a default value, but that just would remove the Required condition in Swagger, not hide it. – Ferran R. May 28 '20 at 06:52
  • But if you're taking the Id from the token. Why are you setting it in the parameter? I always use Ids in tokens. And when I do so, I don't put the Id in the API parameters. – Mohamad Mousheimish May 28 '20 at 07:06
  • @MohamadMousheimish Check the link I provided, I used an `ActionFilterAtribute` to set the `userId` param, so I don't have to get the Id from the token in the action method or the business layer. – Ferran R. May 28 '20 at 07:11

1 Answers1

-1

I realize this is an old post, but if anyone have similar issues you can create your own action filter by extending Swashbuckle.AspNetCore.SwaggerGen.IOperationFilter like this:

public class HideUserIdOperationFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        var scopes = context.MethodInfo
            .GetCustomAttributes(true)
            .OfType<UserIdFromTokenAttribute>()
            .Distinct();

        if (scopes.Any())
        {
            operation.Parameters = operation.Parameters.Where(param => param.Name != "userId").ToList();
        }
    }
}

Remember to add the operation filter to your swagger gen:

c.OperationFilter<HideUserIdOperationFilter>();
Magnus
  • 1
  • 2