Skip to content

Instantly share code, notes, and snippets.

@daniaalnadir
Last active February 25, 2022 17:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daniaalnadir/ce7fbd764b345a687d2444d757bda827 to your computer and use it in GitHub Desktop.
Save daniaalnadir/ce7fbd764b345a687d2444d757bda827 to your computer and use it in GitHub Desktop.
Swagger Authentication Setup
public class ApiKeyAuthenticationDefaults
{
public const string AuthenticationScheme = "ApiKey";
public const string HeaderName = "Authorization";
}
public class JwtAuthenticationDefaults
{
public const string AuthenticationScheme = "JWT";
public const string HeaderName = "Authorization";
public const string BearerPrefix = "Bearer";
}
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo {Title = "TestWebApi", Version = "v1"});
c.AddSecurityDefinition(JwtAuthenticationConst.AuthenticationScheme,
new OpenApiSecurityScheme
{
Description = "JWT Authorization header using the Bearer scheme.",
Name = JwtAuthenticationConst.HeaderName,
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
Scheme = "bearer"
});
c.AddSecurityDefinition(ApiKeyAuthenticationConst.AuthenticationScheme,
new OpenApiSecurityScheme
{
Description = "API key used in the Authorization header.",
Name = ApiKeyAuthenticationConst.HeaderName,
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = JwtAuthenticationConst.AuthenticationScheme
}
},
new List<string>()
}
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = ApiKeyAuthenticationConst.AuthenticationScheme
}
},
new List<string>()
}
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment