Skip to content

Instantly share code, notes, and snippets.

@uzbekdev1
Last active November 19, 2021 12:39
Show Gist options
  • Save uzbekdev1/7ea1ae18d57b49dd7db2534f8c1ea854 to your computer and use it in GitHub Desktop.
Save uzbekdev1/7ea1ae18d57b49dd7db2534f8c1ea854 to your computer and use it in GitHub Desktop.
keycloack auth .net core api
//ConfigureServices
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.MetadataAddress = "https://{host}/auth/realms/{realm}/.well-known/openid-configuration";
options.RequireHttpsMetadata = true;
options.IncludeErrorDetails = true;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = true,
ValidAudiences = new[] { "account" },
ValidateIssuer = true,
ValidIssuers = new[] { "{client}" },
ValidIssuer = "https://{host}/auth/realms",
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
});
services.AddAuthorization();
services.AddCors(options =>
{
options.AddPolicy("AllowAll", builder => builder.SetIsOriginAllowed(a => true).AllowAnyMethod().AllowAnyHeader().AllowCredentials());
});
//Configure
app.UseStaticFiles();
app.UseRouting();
app.UseCors("AllowAll");
app.UseAuthentication();
app.UseAuthorization();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment