Git Product home page Git Product logo

authendpoints's Introduction

  • ๐Ÿ‘‹ Hi, I'm Oga.
  • ๐Ÿ‘€ Iโ€™m focusing on web development.
  • ๐ŸŒฑ Iโ€™m currently learning csharp and aspnetcore.
  • Foundational C# with Microsoft


My Skills

authendpoints's People

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

Current state

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

2fa actions

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

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.

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

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.

Base endpoints: User

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

Token authentication

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

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;
}
}
}

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

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.