Created
February 10, 2025 07:38
-
-
Save mcihad/006025e3b8cd38b5b42e8767de67f5a1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.AspNetCore.Authentication; | |
using Microsoft.AspNetCore.Authentication.Cookies; | |
using Microsoft.AspNetCore.Authentication.OpenIdConnect; | |
using Microsoft.IdentityModel.Protocols.OpenIdConnect; | |
using Microsoft.IdentityModel.Tokens; | |
using System.Reflection; | |
using System.Security.Claims; | |
using Microsoft.EntityFrameworkCore; | |
using Sivasbeltr.WorkCollab.Web.Data; | |
var builder = WebApplication.CreateBuilder(args); | |
// Add services to the container. | |
builder.Services.AddControllersWithViews(); | |
builder.Services.AddControllers(); | |
builder.Services.AddAuthentication(options => | |
{ | |
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; | |
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; | |
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; | |
}) | |
.AddCookie(cookie => | |
{ | |
cookie.Cookie.Name = "randevucookie"; | |
cookie.Cookie.MaxAge = TimeSpan.FromMinutes(60); | |
cookie.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; | |
cookie.SlidingExpiration = true; | |
}) | |
.AddOpenIdConnect(options => | |
{ | |
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; | |
options.Authority = builder.Configuration["Keycloak:ServerRealm"]; | |
options.ClientId = builder.Configuration["Keycloak:ClientId"]; | |
options.ClientSecret = builder.Configuration["Keycloak:ClientSecret"]; | |
options.MetadataAddress = builder.Configuration["Keycloak:Metadata"]; | |
options.RequireHttpsMetadata = false; | |
options.GetClaimsFromUserInfoEndpoint = true; | |
options.Scope.Add("openid"); | |
options.Scope.Add("profile"); | |
options.SaveTokens = true; | |
options.ResponseType = OpenIdConnectResponseType.Code; | |
options.NonceCookie.SameSite = SameSiteMode.Unspecified; | |
options.TokenValidationParameters = new TokenValidationParameters | |
{ | |
NameClaimType = "preferred_username", | |
RoleClaimType = ClaimTypes.Role, | |
ValidateIssuer = true, | |
ValidateLifetime = true, | |
}; | |
}).AddJwtBearer(options => | |
{ | |
options.Authority = builder.Configuration["Keycloak:ServerRealm"]; | |
options.Audience = builder.Configuration["Keycloak:Audience"]; | |
options.MetadataAddress = builder.Configuration["Keycloak:Metadata"]; | |
options.RequireHttpsMetadata = false; | |
options.TokenValidationParameters = new TokenValidationParameters | |
{ | |
NameClaimType = "preferred_username", | |
RoleClaimType = ClaimTypes.Role, | |
ValidateIssuer = true, | |
ValidateAudience = true, | |
ValidateLifetime = true, | |
ClockSkew = TimeSpan.Zero | |
}; | |
}); | |
builder.Services.AddAuthorization(options => | |
{ | |
options.AddPolicy("Admin", policy => policy.RequireRole("Admin")); | |
options.AddPolicy("Users", | |
policy => | |
{ | |
policy.RequireAssertion(context => | |
{ | |
return context.User.HasClaim(c => c.Type == ClaimTypes.Role && c.Value == "User"); | |
}); | |
}); | |
}); | |
builder.Services.AddEndpointsApiExplorer(); | |
builder.Services.AddSwaggerGen(opt => | |
{ | |
opt.SwaggerDoc("v1", new() { Title = "Sivasbeltr.Randevu.API", Version = "v1" }); | |
opt.AddSecurityDefinition("Bearer", new Microsoft.OpenApi.Models.OpenApiSecurityScheme | |
{ | |
Description = "JWT Token ile yetkilendirme. Örnek: \"Bearer {token}\"", | |
Name = "Authorization", | |
In = Microsoft.OpenApi.Models.ParameterLocation.Header, | |
Type = Microsoft.OpenApi.Models.SecuritySchemeType.ApiKey, | |
Scheme = "Bearer" | |
}); | |
opt.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement | |
{ | |
{ | |
new Microsoft.OpenApi.Models.OpenApiSecurityScheme | |
{ | |
Reference = new Microsoft.OpenApi.Models.OpenApiReference | |
{ | |
Type = Microsoft.OpenApi.Models.ReferenceType.SecurityScheme, | |
Id = "Bearer" | |
} | |
}, | |
new string[] { } | |
} | |
}); | |
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; | |
opt.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename)); | |
}); | |
builder.Services.AddDbContext<AppDbContext>(opt => | |
{ | |
opt.UseNpgsql(builder.Configuration["ConnectionStrings:DefaultConnection"]) | |
.UseSnakeCaseNamingConvention(); | |
}); | |
builder.Services.AddHttpContextAccessor(); | |
var app = builder.Build(); | |
// Configure the HTTP request pipeline. | |
if (!app.Environment.IsDevelopment()) | |
{ | |
app.UseExceptionHandler("/Home/Error"); | |
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. | |
app.UseHsts(); | |
} | |
app.UseSwagger(); | |
app.UseSwaggerUI(c => { c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None); }); | |
app.UseHttpsRedirection(); | |
app.UseStaticFiles(); | |
app.UseRouting(); | |
app.UseAuthentication(); | |
app.UseAuthorization(); | |
app.MapControllers(); | |
app.MapControllerRoute( | |
name: "default", | |
pattern: "{controller=Home}/{action=Index}/{id?}"); | |
app.Run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment