Integrar com ASP.NET Core
Adicione autenticação OIDC à sua aplicação ASP.NET Core em menos de 10 minutos usando Microsoft.AspNetCore.Authentication.OpenIdConnect.
Microsoft.AspNetCore.Authentication.OpenIdConnectInstalar o pacote NuGet
Adicione o pacote Microsoft.AspNetCore.Authentication.OpenIdConnect ao seu projeto via CLI do .NET. Ele inclui o middleware OIDC e as abstrações de autenticação necessárias.
dotnet add package Microsoft.AspNetCore.Authentication.OpenIdConnectConfigurar em Program.cs
Registre os serviços de autenticação no contêiner de dependências. Use AddCookie para manter a sessão do usuário e AddOpenIdConnect para configurar o fluxo Authorization Code com o Sentinel Identity.
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
options.Authority = "https://auth.sentinel-identity.com";
options.ClientId = "<SEU_CLIENT_ID>";
options.ClientSecret = "<SEU_CLIENT_SECRET>";
options.ResponseType = "code";
options.CallbackPath = "/signin-oidc";
options.Scope.Clear();
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("email");
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
});
builder.Services.AddControllersWithViews();
var app = builder.Build();SaveTokens = true persiste o access_token e o id_token na sessão cookie, permitindo que você os recupere posteriormente via HttpContext.
Adicionar middleware ao pipeline
Adicione UseAuthentication e UseAuthorization ao pipeline HTTP, após UseRouting e antes de MapControllerRoute.
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();Proteger controllers com [Authorize]
Aplique o atributo [Authorize] no controller ou na action que deseja proteger. Usuários não autenticados serão redirecionados automaticamente para o fluxo de login do Sentinel.
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
[Authorize]
public class DashboardController : Controller
{
public IActionResult Index()
{
var email = User.FindFirst(ClaimTypes.Email)?.Value;
var name = User.FindFirst(ClaimTypes.Name)?.Value;
ViewBag.Email = email;
ViewBag.Name = name;
return View();
}
}Os claims disponíveis dependem dos escopos solicitados e das informações do usuário retornadas pelo UserInfo endpoint.
Externalizar configurações
Mova as credenciais e a URL da authority para o appsettings.json em vez de deixá-las fixas no código.
{
"Sentinel": {
"Authority": "https://auth.sentinel-identity.com",
"ClientId": "<SEU_CLIENT_ID>",
"ClientSecret": "<SEU_CLIENT_SECRET>",
"CallbackPath": "/signin-oidc"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}Em produção, nunca versione ClientSecret no repositório. Use variáveis de ambiente (Sentinel__ClientSecret) ou Azure Key Vault / AWS Secrets Manager.