Giter VIP home page Giter VIP logo

authendpoints's Introduction

AuthEndpoints

nuget issues downloads workflow CodeFactor license

A simple jwt authentication library for ASP.Net 6. AuthEndpoints library provides a set of minimal api endpoints to handle basic web & JWT authentication actions such as registration, email verification, reset password, create jwt, etc. It works with custom identity user model.

swagger_authendpoints

Supported endpoints

  • Users API:
    • sign-up
    • email verification
    • user profile (retrieving)
    • reset password
    • change password
    • enable 2fa
    • login 2fa
  • TokenAuth:
    • Create (login)
    • Destroy (logout)
  • Simple JWT:
    • Create (login)
    • Refresh
    • Verify

Current limitations

  • Only works with IdentityUser & EfCore
  • 2fa via email

Installing via NuGet

The easiest way to install AuthEndpoints is via NuGet

Install the library using the following .net cli command:

dotnet add package AuthEndpoints

or in Visual Studio's Package Manager Console, enter the following command:

Install-Package AuthEndpoints

Quick start

// MyDbContext.cs


using AuthEndpoints.SimpleJwt.Core.Models;

public class MyDbContext : IdentityDbContext
{
  public DbSet<RefreshToken>? RefreshTokens { get; set; } // <--
  public MyDbContext(DbContextOptions<MyDbContext> options) : base(options) { }
}

Add migration and apply migration:

// using dotnet cli
$ dotnet ef migrations add CreateRefreshToken
$ dotnet ef database update

// or using package manager console in visual studio
PM> Add-Migration CreateRefreshToken
PM> Update-Database

Add endpoints and call app.MapEndpoints() before app.Run();

// Program.cs


// Required services
builder.Services.AddIdentityCore<IdentityUser>(); // <--

// Add core services & users api
builder.Services.AddAuthEndpointsCore<IdentityUser, MyDbContext>() // <--
                .AddUsersApiEndpoints()
                .Add2FAEndpoints();

// Add jwt endpoints
// When no options are provided
// AuthEndpoints will create a secret key and use a single security key (symmetric encryption)
// for each access jwt and refresh jwt.
// Secrets will be created under `keys/` directory.
builder.Services.AddSimpleJwtEndpoints<IdentityUser, MyDbContext>(); // <--

var app = builder.Build();

...

app.UseAuthentication(); // <--
app.UseAuthorization(); // <--

...

app.MapEndpoints(); // <--

app.Run();

Documentations

Documentation is available at https://madeyoga.github.io/AuthEndpoints/ and in docs directory.

Contributing

Your contributions are always welcome! simply send a pull request! The up-for-grabs label is a great place to start. If you find a flaw, please open an issue or a PR and let's sort things out.

The project is far from perfect so every bit of help is more than welcome.

authendpoints's People

Contributors

dependabot[bot] avatar madeyoga avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

authendpoints's Issues

Microsoft.AspNetCore.Identity.EntityFrameworkCore seems to be missing from the package

Hello!

GREAT library!

I am just running your demo app with the instructions here: Quick Start

I see here that .AddEntityFrameworkStores<MyDbContext>() is required:

image

The reference of .AddEntityFrameworkStores is 'not found' until you install the nuget package: Microsoft.AspNetCore.Identity.EntityFrameworkCore

I am not sure if this is a bug, or if the user is required to install Microsoft.AspNetCore.Identity.EntityFrameworkCore themselves. I just wanted to report this.

Thanks!

Roles

Can you recommend how to add roles?

I am trying to do, as an example, [Authorize(AuthenticationSchemes = "Bearer", Roles = "Administrator")], but it is not working.

If it is not a feature, could be good to add for a future version.

Unhandled exception. System.InvalidOperationException: Unable to find the required services. Please add all the required services by calling 'IServiceCollection.AddAuthorization' in the application startup code

Unhandled exception. System.InvalidOperationException: Unable to find the required services. Please add all the required services by calling 'IServiceCollection.AddAuthorization' in the application startup code.
   at Microsoft.AspNetCore.Builder.AuthorizationAppBuilderExtensions.VerifyServicesRegistered(IApplicationBuilder app)
   at Microsoft.AspNetCore.Builder.AuthorizationAppBuilderExtensions.UseAuthorization(IApplicationBuilder app)

Adding IServiceCollection.AddAuthorization into ServiceCollectionExtensions.ConfigureServices may fix this issue

Default Options Value

Services.AddAuthEndpoints<,>();

Configure default values for AuthEndpointsOptions

  • Access: Secret Key
  • Refresh: Secret Key
  • AccessSigningOptions
  • RefreshSigningOptions
  • AccessValidationParameters
  • RefreshValidationParameters

public void PostConfigure(string name, AuthEndpointsOptions options)
{
var accessOptions = options.AccessSigningOptions!;
if (accessOptions.Algorithm!.StartsWith("HS"))
{
if (options.AccessValidationParameters == null)
{
options.AccessValidationParameters = new TokenValidationParameters()
{
IssuerSigningKey = accessOptions.SigningKey,
ValidIssuer = options.Issuer,
ValidAudience = options.Audience,
ValidateIssuerSigningKey = true,
ClockSkew = TimeSpan.Zero,
};
}
else
{
options.AccessValidationParameters.IssuerSigningKey = accessOptions.SigningKey;
}
}
var refreshOptions = options.RefreshSigningOptions!;
if (refreshOptions.Algorithm!.StartsWith("HS"))
{
if (options.RefreshValidationParameters == null)
{
options.RefreshValidationParameters = new TokenValidationParameters()
{
IssuerSigningKey = refreshOptions.SigningKey,
ValidIssuer = options.Issuer,
ValidAudience = options.Audience,
ValidateIssuerSigningKey = true,
ClockSkew = TimeSpan.Zero,
};
}
else
{
options.RefreshValidationParameters.IssuerSigningKey = refreshOptions.SigningKey;
}
}
}

Add swagger 'Authorization' feature

Hi,

This is looking very good, but the swagger could be improved by using its authorization feature. I have this working, and this is what I did.

In program.cs: after the following lines, add the "// To Enable authorization using Swagger (JWT)" section of code

var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
options.IncludeXmlComments(xmlPath);

// To Enable authorization using Swagger (JWT)
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
    Name = "Authorization",
    Type = SecuritySchemeType.ApiKey,
    Scheme = "Bearer",
    BearerFormat = "JWT",
    In = ParameterLocation.Header,
    Description = "JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 12345abcdef\"",
});

options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
    {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            Array.Empty<string>()
    }
});

To use, get the bearer token, and press the green Authorize button.

In the input box type the word Bearer followed by a space and paste the bearer token. Then press the authorize button and the close button.

Features like /users/me, should now work as expected. This worked great for me, and I think should be part of the demo code.

Hope this helps.

JWT in HttpOnly cookie

Features:

  • Write/Store JWT in httponly cookie
HttpContext.Response.Cookies.Append("access_token", "<access_jwt>", new CookieOptions { HttpOnly = true });
  • Read/Validate JWT from cookie instead of headers. Or catch the request and move the token from the cookie to the header as auth bearer
  • Refresh JWT in httponly cookie

2fa actions

Simple Two factor authentication for issuing an access token, using email

There is no way to revoke refresh tokens

Currently, refresh tokens are not stored on the server side. There is no way to revoke refresh tokens other than changing the secret key.

public string GenerateRefreshToken(TUser user)
{
JwtSigningOptions signingOptions = _options.RefreshSigningOptions!;
var credentials = new SigningCredentials(signingOptions.SigningKey, signingOptions.Algorithm);
var header = new JwtHeader(credentials);
var payload = new JwtPayload(
_options.Issuer!,
_options.Audience!,
_claimsProvider.provideRefreshClaims(user),
DateTime.UtcNow,
DateTime.UtcNow.AddMinutes(signingOptions.ExpirationMinutes)
);
return _tokenHandler.WriteToken(new JwtSecurityToken(header, payload));
}

public virtual async Task<IResult> Refresh([FromBody] RefreshRequest request,
IJwtValidator jwtValidator,
IOptions<AuthEndpointsOptions> options,
UserManager<TUser> userManager,
IAuthenticator<TUser> authenticator)
{
bool isValidRefreshToken = jwtValidator.Validate(request.RefreshToken!,
options.Value.RefreshValidationParameters!);
if (!isValidRefreshToken)
{
// Token may be expired, invalid, etc. but this good enough for now.
return Results.BadRequest(new ErrorResponse("Invalid refresh token. Token may be expired or invalid."));
}

Todo

  1. Store refresh token in database or HttpOnly cookies
  2. Update token validator services

Base endpoints: User

  • User create
  • Email confirmation
  • User resend email confirmation email
  • User me
  • User delete

Current state

  • Can only support 1 jwt bearer authentication scheme
  • Current backend can be customized/extended using AuthEndpointsBuilder to support Asymmetric implementation of jwt

Token authentication

  • Authenticator
  • Controller
    • Create
    • Destroy
  • Token model
  • Repository
  • Token generator algorithm

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.