I use the mock OAuth2 / OIDC server from here: [navikt/mock-oauth2-server: A scriptable/customizable web server for testing HTTP clients using OAuth2/OpenID Connect or applications with a dependency to a running OAuth2 server (i.e. APIs requiring signed JWTs from a known issuer) (github.com)](https://github.com/navikt/mock-oauth2-server)
```yml
services:
auth:
image: ghcr.io/navikt/mock-oauth2-server:2.1.5
ports:
- 9999:8080
```
Add the `Microsoft.AspNetCore.Authentication.JwtBearer` NuGet.
## Configuring the Auth:
In your `appsettings.Development.json`:
```json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"well-known": "http://localhost:9999/default/.well-known/openid-configuration"
}
```
In `Program.cs`
```csharp
var oidcWellKnownEndpoint = builder.Configuration.GetValue<string>("well-known") ?? throw new Exception("No OIDC Well Known Endpoint");
builder.Services.AddAuthentication().AddJwtBearer(options =>
{
options.MetadataAddress = oidcWellKnownEndpoint;
options.RequireHttpsMetadata = !builder.Environment.IsDevelopment();
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false,
ClockSkew = TimeSpan.Zero,
};
});
builder.Services.AddAuthorization();
```
Example Controller:
```csharp
[HttpGet(Name = "GetWeatherForecast")]
[Authorize]
public ActionResult Get()
{
var wx = Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
var sub = User.Claims.First(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
return Ok(new { For = sub ?? "wha?", Data = wx });
}
```
## Adding To Swagger
A bit yucky, but:
Configure the security block:
```csharp
builder.Services.AddSwaggerGen(options =>
{
options.AddSecurityDefinition("oidc", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OpenIdConnect,
OpenIdConnectUrl = new Uri(oidcWellKnownEndpoint),
In = ParameterLocation.Header,
Name = "Authorization"
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference { Id = "oidc", Type = ReferenceType.SecurityScheme}
},
[]
}
});
```
For Swagger UI, Configure it like this:
> Note: The Client ID and scopes should go in configuration:
```csharp
app.UseSwaggerUI(options =>
{
options.OAuthClientId("default");
options.OAuthScopes("profile", "openid", "api");
options.OAuthUsePkce();
options.EnablePersistAuthorization(); // saves in local storage so they don't have to reauth for each request. Hide behind IsDevelopment if desired.
});
```