.NET Reference - PropelAuth Docs
.NET Reference
Upgrading from PropelAuth .NET v0.1.0 or earlier? See the guide here for more information.
PropelAuth's .NET integration provides all the building blocks you need to add authentication to your .NET projects. Our goal in building this library was to allow you to set up authentication the way you want to do it. That being said, we also want to get you up and running as quickly as possible. While you can use this library in many different ways, this guide will walk you through the most common use cases and how to implement them.
Installation
dotnet add package PropelAuth
Want to use PropelAuth and .NET to protect your application's frontend? Check out our .NET OAuth2 guide.
Initialize
Begin by navigating to the Backend Integration page of the PropelAuth Dashboard and copying your Auth URL and Public Verifier Key. These values will be used to validate access tokens generated by your frontend. Paste these values into your .NET project.
Program.cs
var AUTH_URL = "https://auth.example.com";
var PUBLIC_KEY = @"-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1DsxqIjXqM0i5PL6kFVa\n280S3gl96n2YlO6l9ss2XD/GOoDM11LxnwlIBWFXeRGhOVi4dp2pefY4Bh2rg4Z8\n/Nq1J..\n-----END PUBLIC KEY-----\n";
We'll be using the System.Security.Cryptography Namespace to import the Public Verifier Key.
Program.cs
using System.Security.Cryptography;
var rsa = RSA.Create();
rsa.ImportFromPem(PUBLIC_KEY);
Next, let's configure our app to use JWT authentication. This will allow us to validate access tokens and retrieve user information from them.
Program.cs
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false,
ValidAlgorithms = new List<string>() {"RS256"},
ValidIssuer = AUTH_URL,
IssuerSigningKey = new RsaSecurityKey(rsa),
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
});
Protect API Routes
The PropelAuth .NET library provides a User Class to validate the access token and provide the user's information if it is valid. To get the User Class, use the GetUser() method on the ClaimsPrincipal Class.
If the access token is not valid, the user's properties will be set to null. If that's the case, you can use .NET's Results Class to return a 401 Unauthorized error.
using PropelAuth.Models;
using System.Security.Claims;
app.MapGet("/", (ClaimsPrincipal claimsPrincipal) =>
{
var user = claimsPrincipal.GetUser();
if (user == null)
{
return Results.Unauthorized();
}
return Results.Ok($