Swashbuckle.aspnetcore: Does not use DataType.Password

Created on 25 Oct 2017  路  3Comments  路  Source: domaindrivendev/Swashbuckle.AspNetCore

Swashbuckle does not set the input type to password when the property is decorated using the [DataType(DataType.Password)] property decorator.

    public class Model
    {
        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }
    }

Most helpful comment

Addressed by 07fbdeb187f558dad7e0e4afb9512ff5ccf98d6e.

All 3 comments

As you figured out, Swashbuckle doesn't use the DataType attributes. @domaindrivendev is there a need / wish to support this?

You could use a custom IOperationFilter to get what you want, something like this:

public class PasswordOperationFilter : IOperationFilter
{
    private static Type _modelType = typeof(Address);

    public void Apply(Operation operation, OperationFilterContext context)
    {
        if(context.ApiDescription.ActionDescriptor.Parameters.Any(x => x.ParameterType == _modelType))
        {
            var password = operation.Parameters.OfType<NonBodyParameter>()
                                               .SingleOrDefault(x => x.Name == nameof(Model.Password));
            if (password != null)
            {
                // sets the format to password, which is supported by the OpenAPI spec
                // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types
                // this triggers swagger-ui to mask the input field
                password.Format = "password";
            }
        }
    }
}

Of course, you can make this more generic and have it work on the DataType attribute.

It would be nice if Swashbuckle did this out-of-the-box.

Addressed by 07fbdeb187f558dad7e0e4afb9512ff5ccf98d6e.

Was this page helpful?
0 / 5 - 0 ratings