Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,26 +8,28 @@

A library to easily integrate Authentication in ASP.NET Core projects. Currently it supports JWT Bearer, API Key and Basic Authentication in both Controller-based and Minimal API projects.

**Installation**
## Installation

The library is available on [NuGet](https://www.nuget.org/packages/SimpleAuthenticationTools). Just search for *SimpleAuthenticationTools* in the **Package Manager GUI** or run the following command in the **.NET CLI**:

dotnet add package SimpleAuthenticationTools

**Usage Video**
## Usage video

Take a look to a quick demo showing how to integrate the library:

[![Simple Authentication for ASP.NET Core](https://raw.githubusercontent.com/marcominerva/SimpleAuthentication/master/Screenshot.jpg)](https://www.youtube.com/watch?v=SVZuaPE2yNc)

**Configuration**
## Configuration

Authentication can be totally configured adding an _Authentication_ section in the _appsettings.json_ file:

"Authentication": {
"DefaultScheme": "Bearer", // Optional
"JwtBearer": {
"SchemeName": "Bearer" // Default: Bearer
//"NameClaimType": "user_name", // Default: http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name
//"RoleClaimType": "role", // Default: http://schemas.microsoft.com/ws/2008/06/identity/claims/role"
"SecurityKey": "supersecretsecuritykey42!", // Required
"Algorithm": "HS256", // Default: HS256
"Issuers": [ "issuer" ], // Optional
Expand Down Expand Up @@ -194,7 +196,7 @@ If you need to implement custom authentication login, for example validating cre
}
}

**Permission-based authorization**
## Permission-based authorization

The library provides services for adding permission-based authorization to an ASP.NET Core project. Just use the following registration at startup:

Expand Down Expand Up @@ -254,12 +256,12 @@ It is also possible to explicitly create a policy that requires the one or more
.RequireAuthorization(policyNames: "UserProfile")


**Samples**
## Samples

- JWT Bearer ([Controller](https://github.com/marcominerva/SimpleAuthentication/tree/master/samples/Controllers/JwtBearerSample) | [Minimal API](https://github.com/marcominerva/SimpleAuthentication/tree/master/samples/MinimalApis/JwtBearerSample))
- API Key ([Controller](https://github.com/marcominerva/SimpleAuthentication/tree/master/samples/Controllers/ApiKeySample) | [Minimal API](https://github.com/marcominerva/SimpleAuthentication/tree/master/samples/MinimalApis/ApiKeySample))
- Basic Authentication ([Controller](https://github.com/marcominerva/SimpleAuthentication/tree/master/samples/Controllers/BasicAuthenticationSample) | [Minimal API](https://github.com/marcominerva/SimpleAuthentication/tree/master/samples/MinimalApis/BasicAuthenticationSample))

**Contribute**
## Contribute

The project is constantly evolving. Contributions are welcome. Feel free to file issues and pull requests on the repo and we'll address them as we can.
2 changes: 2 additions & 0 deletions samples/Controllers/JwtBearerSample/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
"DefaultScheme": "Bearer", // Optional
"JwtBearer": {
"SchemeName": "Bearer", // Default: Bearer
//"NameClaimType": "user_name", // Default: http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name
//"RoleClaimType": "role", // Default: http://schemas.microsoft.com/ws/2008/06/identity/claims/role"
"SecurityKey": "YKgsOiwvDLJe42dyyL3FkhlMAzZZ2Cmr0FTpyLsPE5DA2afd6NbbCV3d5oHDG2rVBaDHH540EUmrzXPPk2LnfanCdERl4apucmu2Ev5oVgN6dGCr8MMxXIIyTaNmmXHSsaONo75UkxQvFtsm9Qsnsz3VxuNzsoqrzqBQdsDvClo1LcrRNNcTdKcvceq1G57PZNxOWFS749wnsqq7r17a9vvinTdYME2umo7DRn8XUiwbdOajCehJfqipIjwbcuoCIrCwwMizKSiidw5KXU7koVvUSV0UH3o4TWHsVBnt5B1os6oPKtCQ63CPqlwHB5Pet4mzA2lhaFROZXbStpigaRJf3J6AOwZurMbo3LhzCpPW6KZwkixMpwCb82ekZvL0tmfQA2LeWDL2esZ9N4N8w8CzxrZt4gyEfywBwsoFohC0ydVznDpwbgCg05ktuczX3FFcsXEErwtY2wu0or0TSrUSnzIrYP26dOOUh4qREPJ7ZnZ5NoQjOMcXkiThdMuy", // Required
"Algorithm": "HS256", // Default: HS256
"Issuers": [ "issuer" ], // Optional
Expand Down
4 changes: 3 additions & 1 deletion samples/MinimalApis/JwtBearerSample/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
"Authentication": {
"DefaultScheme": "Bearer", // Optional
"JwtBearer": {
"SchemeName": "Bearer", // Default: Bearer
"SchemeName": "Bearer", // Default: Bearer
//"NameClaimType": "user_name", // Default: http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name
//"RoleClaimType": "role", // Default: http://schemas.microsoft.com/ws/2008/06/identity/claims/role"
"SecurityKey": "YKgsOiwvDLJe42dyyL3FkhlMAzZZ2Cmr0FTpyLsPE5DA2afd6NbbCV3d5oHDG2rVBaDHH540EUmrzXPPk2LnfanCdERl4apucmu2Ev5oVgN6dGCr8MMxXIIyTaNmmXHSsaONo75UkxQvFtsm9Qsnsz3VxuNzsoqrzqBQdsDvClo1LcrRNNcTdKcvceq1G57PZNxOWFS749wnsqq7r17a9vvinTdYME2umo7DRn8XUiwbdOajCehJfqipIjwbcuoCIrCwwMizKSiidw5KXU7koVvUSV0UH3o4TWHsVBnt5B1os6oPKtCQ63CPqlwHB5Pet4mzA2lhaFROZXbStpigaRJf3J6AOwZurMbo3LhzCpPW6KZwkixMpwCb82ekZvL0tmfQA2LeWDL2esZ9N4N8w8CzxrZt4gyEfywBwsoFohC0ydVznDpwbgCg05ktuczX3FFcsXEErwtY2wu0or0TSrUSnzIrYP26dOOUh4qREPJ7ZnZ5NoQjOMcXkiThdMuy", // Required
"Algorithm": "HS256", // Default: HS256
"Issuers": [ "issuer" ], // Optional
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;

Expand Down Expand Up @@ -48,6 +49,25 @@ public class JwtBearerSettings
/// <seealso cref="TokenValidationParameters.ClockSkew"/>
public TimeSpan ClockSkew { get; set; } = TokenValidationParameters.DefaultClockSkew;

/// <summary>
/// Gets or sets a <see cref="string"/> that defines the <see cref="ClaimsIdentity.NameClaimType"/>.
/// </summary>
/// <remarks>
/// Controls the value <see cref="ClaimsIdentity.Name"/> returns. It will return the first <see cref="Claim.Value"/> where the <see cref="Claim.Type"/> equals <see cref="NameClaimType"/>.
/// The default is <see cref="ClaimsIdentity.DefaultNameClaimType"/>.
/// </remarks>
public string NameClaimType { get; set; } = ClaimsIdentity.DefaultNameClaimType;

/// <summary>
/// Gets or sets the <see cref="string"/> that defines the <see cref="ClaimsIdentity.RoleClaimType"/>.
/// </summary>
/// <remarks>
/// <para>Controls the results of <see cref="ClaimsPrincipal.IsInRole( string )"/>.</para>
/// <para>Each <see cref="Claim"/> where <see cref="Claim.Type"/> == <see cref="RoleClaimType"/> will be checked for a match against the 'string' passed to <see cref="ClaimsPrincipal.IsInRole(string)"/>.</para>
/// The default is <see cref="ClaimsIdentity.DefaultRoleClaimType"/>.
/// </remarks>
public string RoleClaimType { get; set; } = ClaimsIdentity.DefaultRoleClaimType;

/// <summary>
/// <see langword="true"/> to register the <see cref="IJwtBearerService"/> service in the <see cref="IServiceCollection"/> (Default: true).
/// </summary>
Expand Down
6 changes: 4 additions & 2 deletions src/SimpleAuthentication/JwtBearer/JwtBearerService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public JwtBearerService(IOptions<JwtBearerSettings> jwtBearerSettingsOptions)
public string CreateToken(string userName, IList<Claim>? claims = null, string? issuer = null, string? audience = null, DateTime? absoluteExpiration = null)
{
claims ??= new List<Claim>();
claims.Update(ClaimTypes.Name, userName);
claims.Update(jwtBearerSettings.NameClaimType, userName);
claims.Update(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString());
claims.Remove(JwtRegisteredClaimNames.Aud);

Expand All @@ -42,6 +42,8 @@ public ClaimsPrincipal ValidateToken(string token, bool validateLifetime)
{
var tokenValidationParameters = new TokenValidationParameters
{
NameClaimType = jwtBearerSettings.NameClaimType,
RoleClaimType = jwtBearerSettings.RoleClaimType,
ValidateIssuer = jwtBearerSettings.Issuers?.Any() ?? false,
ValidIssuers = jwtBearerSettings.Issuers,
ValidateAudience = jwtBearerSettings.Audiences?.Any() ?? false,
Expand Down Expand Up @@ -69,7 +71,7 @@ public string RefreshToken(string token, bool validateLifetime, DateTime? absolu
var principal = ValidateToken(token, validateLifetime);
var claims = (principal.Identity as ClaimsIdentity)!.Claims.ToList();

var userName = claims.First(c => c.Type == ClaimTypes.Name).Value;
var userName = claims.First(c => c.Type == jwtBearerSettings.NameClaimType).Value;
var issuer = claims.FirstOrDefault(c => c.Type == JwtRegisteredClaimNames.Iss)?.Value;
var audience = claims.FirstOrDefault(c => c.Type == JwtRegisteredClaimNames.Aud)?.Value;

Expand Down
5 changes: 4 additions & 1 deletion src/SimpleAuthentication/SimpleAuthentication.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="SimpleAuthenticationTools.Abstractions" Version="2.0.8" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="6.5.0" />
</ItemGroup>

Expand All @@ -42,5 +41,9 @@
</None>
<None Include="..\..\README.md" Pack="true" PackagePath="\" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\SimpleAuthentication.Abstractions\SimpleAuthentication.Abstractions.csproj" />
</ItemGroup>

</Project>
2 changes: 2 additions & 0 deletions src/SimpleAuthentication/SimpleAuthenticationExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ static void CheckAddJwtBearer(AuthenticationBuilder builder, IConfigurationSecti
{
options.TokenValidationParameters = new()
{
NameClaimType = settings.NameClaimType,
RoleClaimType = settings.RoleClaimType,
ValidateIssuer = settings.Issuers?.Any() ?? false,
ValidIssuers = settings.Issuers,
ValidateAudience = settings.Audiences?.Any() ?? false,
Expand Down