简体   繁体   中英

MVC5 and Swashbuckle with Basic Authorization Header (.NET 4.6.1 Framework)

Hello I am using Swashbuckle with MVC5, I am able to generate the Swagger UI but I also need the Basic Authorization Header.

I have tried the following code

public class AddAuthorizationHeaderParameterOperationFilter: IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        var filterPipeline = apiDescription.ActionDescriptor.GetFilterPipeline();
        var isAuthorized = filterPipeline
                                         .Select(filterInfo => filterInfo.Instance)
                                         .Any(filter => filter is IAuthorizationFilter);

        var allowAnonymous = apiDescription.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();

        if (isAuthorized && !allowAnonymous)
        {
            operation.parameters.Add(new Parameter {
                name = "Authorization",
                @in = "header",
                description = "access token",
                required = true,
                type = "string"                    
            });
        }
    }
}

and added the following in web.config

<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <dependentAssembly>
            <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
        </dependentAssembly>
        <dependentAssembly>
            <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
           <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
        </dependentAssembly>
    </assemblyBinding>
</runtime>

Getting error for Cannot load System.Web.Http 4.0.0

I doubt that swagger supports this, I came across this https://github.com/swagger-api/swagger-ui/issues/1566 where basic auth with swagger issue has been reported but didn't get resolved to work.

I recommend testing your code with a Rest-client (Advance Rest client or posteman etc.) tool instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM