.NET Authentication
.NET is a software framework developed by Microsoft that is used for building a wide range of applications, including web applications, mobile apps, desktop applications, cloud services, and more.
However, auth with .NET can be overly complex and difficult to set up. That’s where PropelAuth comes in. This guide will help you install PropelAuth in your .NET application.
Installation and Configuration
Let’s first log into PropelAuth to gather some variables. In your dashboard, navigate to the Backend Integration page in PropelAuth and locate the Public (Verifier) Key. Copy this as a multi-line value and paste it like so in your Program.cs
file:
using System.Security.Cryptography;
var rsa = RSA.Create();
rsa.ImportFromPem(@"-----BEGIN PUBLIC KEY-----
MIIBI...
-----END PUBLIC KEY-----
");
You may have to import RSA by using the System.Security.Cryptography
library.
Initialization
Let’s now set up authentication by adding the following after the code we added above. Make sure to replace YOUR_AUTH_URL
with your Auth URL found in the Frontend Integration page in PropelAuth.
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 = "YOUR_AUTH_URL",
IssuerSigningKey = new RsaSecurityKey(rsa),
};
});
You may need to run the following commands to import the JwtBearer
and Tokens
packages:
dotnet add package System.IdentityModel.Tokens.Jwt
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer`
You can then add your own policies, with RequireLogin
defined like so:
using Microsoft.AspNetCore.Authorization;
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("RequireLogin", policy => policy.Requirements.Add(new RequiredAuthentication()));
});
builder.Services.AddSingleton<IAuthorizationHandler, RequiredAuthenticationHandler>();
// ...
public class RequiredAuthenticationHandler : AuthorizationHandler<RequiredAuthentication>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
RequiredAuthentication requirement)
{
var userId = context.User.FindFirst("user_id");
if (userId != null)
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
public class RequiredAuthentication : IAuthorizationRequirement
{
}
We can then add the following towards the bottom of your Program.cs
:
var app = builder.Build();
//...
app.UseAuthentication();
app.UseAuthorization();
Next, add the RequireLogin
policy to a route handler:
app.MapGet("/", async () =>
{
//...
})
.RequireAuthorization("RequireLogin");
Now when we make a request to that endpoint we’ll receive a 401
error unless we’re logged in with PropelAuth.
We can then use the ClaimsPrincipal
to access information about the user:
app.MapGet("/", async (ClaimsPrincipal user) =>
{
var userId = user.FindFirst("user_id");
return new { UserId = userId.Value };
})
.RequireAuthorization("RequireLogin");
When you make an authorized request to this endpoint using an access token in the request header, you'll then get this response:
{
"userId": "7095f9df-08ae-4f7f-98ea-464eb438cad5"
}
If you have any questions, please do not hesitate to reach out to support@propelauth.com!