How to do OAuth2 Authorization in ASP.NET Core for Swagger UI using Swashbuckle

·

1 min read

A great article How to do OAuth2 Authorization in ASP.NET Core for Swagger UI using Swashbuckle

Gist

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "My Service API", Version = "v1" });
    var fileName = typeof(Program).Assembly.GetName().Name + ".xml";
    var xmlCommentsFullPath = Path.Combine(AppContext.BaseDirectory, fileName);
    c.IncludeXmlComments(xmlCommentsFullPath);
    c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
    {
        Type = SecuritySchemeType.OAuth2,
        Flows = new OpenApiOAuthFlows()
        {
            Implicit = new OpenApiOAuthFlow()
            {
                AuthorizationUrl = new Uri("https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize"),
                TokenUrl = new Uri("https://login.microsoftonline.com/organizations/oauth2/token"),
                Scopes = new Dictionary<string, string>
                    {
                            { "https://microsoft.onmicrosoft.com/my-service/ReadWrite.All", "Read Write My Service" },
                    },
            },
        },
    });
    c.AddSecurityRequirement(new OpenApiSecurityRequirement()
        {
            {
                new OpenApiSecurityScheme
                {
                    Reference = new OpenApiReference
                    {
                        Type = ReferenceType.SecurityScheme,
                        Id = "oauth2",
                    },
                    Scheme = "oauth2",
                    Name = "oauth2",
                    In = ParameterLocation.Header,
                },
                new List<string>()
            },
        });
});