.NET OAuth2 Guide
.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 using our OAuth2 Support.
Installation
dotnet add package PropelAuth
Configuration
Let’s start by navigating to our OAuth Configuration page. Head over to the Frontend Integration page, click on Advanced Settings followed by Edit OAuth Config.
Here, we can generate a Client ID and Client Secret (we'll be using these in the next step). We can also set a Redirect URI. In this example, we’ll be using the /auth/callback
path so if you’re testing in localhost, you can enter http://localhost:8000/auth/callback, for example.
Initialize
AddPropelAuthAsync
performs a one-time initialization of the library.
It will verify your apiKey
is correct and fetch the metadata needed to verify access tokens in GetUser which we'll be using later in this guide.
To get your API Key and Auth URL, visit the Backend Integration page in your PropelAuth Dashboard. The Client ID and Client Secret can be found in the previous section of this guide.
If we include the oAuthOptions
parameter, PropelAuth will automatically set up the OAuth2 middleware for us.
using System.Security.Claims;
using PropelAuth;
using PropelAuth.Models;
var builder = WebApplication.CreateBuilder(args);
await builder.Services.AddPropelAuthAsync(new PropelAuthOptions(
apiKey: "YOUR_API_KEY",
authUrl: "YOUR_AUTH_URL",
oAuthOptions: new PropelAuth.Models.OAuthOptions(
clientId: "YOUR_CLIENT_ID",
clientSecret: "YOUR_CLIENT_SECRET",
callbackPath: "/auth/callback",
allowBearerTokenAuth: true // Defaults to false
// Allows your APIs to accept an authorization header
// of Bearer {TOKEN} to protect API routes
)
));
Now all we have to do is require users to be logged in to visit our frontend! If using Blazor, for example, we can add @attribute [Authorize]
to the top of a page.
@page "/"
@attribute [Authorize]
If you were to visit the page, you'll first be redirected to PropelAuth to log in. Once you log in, you'll be redirected back to your site and the Authorize
attribute will allow you to view the page.
Displaying User Information
To display user information in your Blazor app, we can use PropelAuth's .NET User Class in our Razor page. The User Class contains information about the user that is logged in. It also contains additional methods such as GetOrgs()
and HasPermission()
. You must first retrieve the ClaimsPrincipal Class and then convert it to a User Class.
@page "/"
@attribute [Authorize]
@inject AuthenticationStateProvider AuthenticationStateProvider
<PageTitle>Home</PageTitle>
<h2>User Profile</h2>
<div>
<p><strong>Email:</strong> @User.Email</p>
<p><strong>User ID:</strong> @User.UserId</p>
<p><strong>Org:</strong> @User.GetOrgs().First().OrgName</p>
</div>
@code {
private PropelAuth.Models.User? User { get; set; }
protected override async Task OnInitializedAsync()
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var claimsPrincipal = authState.User;
User = claimsPrincipal.GetUser();
}
}
Protect API Routes
If you want to make requests to your API routes with an authorization header instead of OAuth2 (which uses cookies), make sure to set allowBearerTokenAuth
to true
in the oAuthOptions
parameter during the initialization step. The header must be formated Bearer {ACCESS_TOKEN}
. This can be useful for testing via tools like Postman or cURL.
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.
app.MapGet("/", (ClaimsPrincipal claimsPrincipal) =>
{
var user = claimsPrincipal.GetUser();
if (user == null)
{
return Results.Unauthorized();
}
return Results.Ok($"Hello user with ID {user.userId}");
});
For more information on how to protect your API routes, check out our .NET reference docs.
If you have any questions, please do not hesitate to reach out to support@propelauth.com!