Giter Club home page Giter Club logo

security.identity's Introduction

.NET DevPack

What is the .NET DevPack.Identity?

.NET DevPack Identity is a set of common implementations to help you implementing ASP.NET Identity, JWT, claims validation and another facilities

Codacy Badge Build status .NET Core License

Give a Star! ⭐

If you liked the project or if NetDevPack helped you, please give a star ;)

Get Started

Package Version Popularity
NetDevPack.Identity NuGet Nuget

.NET DevPack.Identity can be installed in your ASP.NET Core application using the Nuget package manager or the dotnet CLI.

dotnet add package NetDevPack.Identity

If you want to use our IdentityDbContext (ASP.NET Identity standard) you will need to create the Identity tables. Set your connection string in the appsettings.json and follow the next steps:

Add the IdentityDbContext configuration in your startup.cs:

services.AddIdentityEntityFrameworkContextConfiguration(options => 
	options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"), 
	b=>b.MigrationsAssembly("AspNetCore.Jwt.Sample")));

Note: You must inform the namespace to avoid migration errors

Note: You must install the Microsoft.EntityFrameworkCore.SqlServer or another provider like Npgsql.EntityFrameworkCore.PostgreSQL package to have support from your database. Find the package for your database here

Add the Identity configuration in ConfigureServices method of your startup.cs:

services.AddIdentityConfiguration();

Note: This extension returns an IdentityBuilder to allow you extending the configuration

Add the Identity configuration in Configure method of your startup.cs:

app.UseAuthConfiguration();

Note: This method need to be set between app.UseRouting() and app.UseEndpoints()

Run the command to generate the migration files:

dotnet ef migrations add Initial --context NetDevPackAppDbContext --project <Your patch>/<Your Project>.csproj

Run the command to generate the database:

dotnet ef database update --context NetDevPackAppDbContext --project <Your patch>/<Your Project>.csproj

Note: If are you using your own IdentityDbContext you must change the NetDevPackAppDbContext value to your context class name in the commands above.

After execute this steps you will be all set to use the Identity in your Application.

Configuring JWT

If you want to generate JSON Web Tokens in your application you need to add the JWT configuration in ConfigureServices method of your startup.cs

services.AddJwtConfiguration(Configuration)
        .AddNetDevPackIdentity<IdentityUser>();

Set your appsettings.json file with this values:

"AppJwtSettings": {
    "Audience": "MyApplication.Name"
}

It's possible to configure some aspects of token

Key Meaning Default
Expiration Expiration time (in hours) 1
Issuer The party that "created" the token and signed it with its private key. Usually the application Url Get current root Url from HttpContext
Audience API's that should accept the token. E.g your application Main name. NetDevPack
RefreshTokenExpiration Refresh token expiration (In Days) 30
RefreshTokenType OneTime or ReUse 30
SecretKey Deprecated Is your key to build JWT. Read notes Do not use it

Note: Now we are using NetDevPack.Security.Jwt to generate and Store your keys. It generate a RSA 2048 by default. You can check the project for more info.

Generating JWT

You will need to set a single dependency in your Authentication Controller:

public AuthController(IJwtBuilder jwtBuilder)
{
    _jwtBuilder = jwtBuilder;
}

After user register or login process you can generate a JWT to respond the request. Use our implementation, you just need inform the user email and the dependencies injected in your controller:

return _jwtBuilder
	.WithEmail(email)
    	.WithRefreshToken()
	.BuildToken();

Note: This builder can return a single string with JWT or a complex object UserResponse if you want return more data than a single JWT string.

Adding Claims to your JWT

You can call more methods in JwtBuilder to provide more information about the user:

return _jwtBuilder
    .WithEmail(email)
    .WithJwtClaims()
    .WithUserClaims()
    .WithUserRoles()
    .WithRefreshToken()
    .BuildToken();
Method Meaning
WithJwtClaims() Claims of JWT like sub, jti, nbf and others
WithUserClaims() The user claims registered in AspNetUserClaims table
WithUserRoles() The user roles (as claims) registered in AspNetUserRoles table
BuildToken() Build and return the JWT as single string

If you want return your complex object UserResponse you need to change the last method to:

return _jwtBuilder
    .WithEmail(email)
    .WithJwtClaims()
    .WithUserClaims()
    .WithUserRoles()
    .WithRefreshToken()
    .BuildUserResponse();

Examples

Use the sample application to understand how NetDevPack.Identity can be implemented and help you to decrease the complexity of your application and development time.

Compatibility

The NetDevPack.Identity was developed to be implemented in ASP.NET Core. It support all .NET versions since 3.1.

About

.NET DevPack.Identity was developed by Eduardo Pires under the MIT license.

security.identity's People

Contributors

brunobritodev avatar eduardopires avatar kirisky avatar paulomonteirodev avatar semantic-release-bot 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  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

security.identity's Issues

sample can't run

Describe the bug
the sample can't run

To Reproduce
Steps to reproduce the behavior:

  1. F5
    2.Open the sawgger page
  2. Use account/register
  3. See error
System.InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.SignInManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' while attempting to activate 'AspNetCore.Jwt.Sample.Controllers.AuthController'.
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
   at lambda_method9(Closure, IServiceProvider, Object[])
   at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass6_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)

so i Add this code next services.AddIdentityCore(...)

            services.TryAddScoped<UserManager<MyIntIdentityUser>>();
            services.TryAddScoped<SignInManager<MyIntIdentityUser>>();
            services.TryAddScoped<RoleManager<MyIntIdentityRoles>>();

the register can work, but when i use the /login api it met another problem,

System.InvalidOperationException: No sign-in authentication handlers are registered. Did you forget to call AddAuthentication().AddCookie("Identity.Application",...)?
   at Microsoft.AspNetCore.Authentication.AuthenticationService.SignInAsync(HttpContext context, String scheme, ClaimsPrincipal principal, AuthenticationProperties properties)
   at Microsoft.AspNetCore.Identity.SignInManager`1.SignInWithClaimsAsync(TUser user, AuthenticationProperties authenticationProperties, IEnumerable`1 additionalClaims)
   at Microsoft.AspNetCore.Identity.SignInManager`1.SignInOrTwoFactorAsync(TUser user, Boolean isPersistent, String loginProvider, Boolean bypassTwoFactor)
   at Microsoft.AspNetCore.Identity.SignInManager`1.PasswordSignInAsync(TUser user, String password, Boolean isPersistent, Boolean lockoutOnFailure)
   at Microsoft.AspNetCore.Identity.SignInManager`1.PasswordSignInAsync(String userName, String password, Boolean isPersistent, Boolean lockoutOnFailure)
   at AspNetCore.Jwt.Sample.Controllers.AuthCustomConfigAndKeyController.Login(LoginUser loginUser) in E:\Code\Demo\NetDevPack\Security.Identity\src\Samples\AspNetCore.Jwt.Sample\Controllers\AuthCustomConfigAndKeyController.cs:line 63
   at lambda_method209(Closure, Object)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfActionResultExecutor.Execute(ActionContext actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)

Autofac + IJwtBuilder ?

I'm using AutoFac for IoC and I can't figure out a way to register the "IJwtBuilder" interface. Its implementation is "internal". Any tips or examples?

Thank you =)

---- EXCEPTION

Autofac.Core.DependencyResolutionException: An exception was thrown while activating NetDevPack.Identity.Jwt.JwtBuilderInject2[[Microsoft.AspNetCore.Identity.IdentityUser, Microsoft.Extensions.Identity.Stores, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60],[System.String, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]. ---> Autofac.Core.DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'NetDevPack.Identity.Jwt.JwtBuilderInject2[Microsoft.AspNetCore.Identity.IdentityUser,System.String]' can be invoked with the available services and parameters:
Cannot resolve parameter 'Microsoft.AspNetCore.Identity.UserManager1[Microsoft.AspNetCore.Identity.IdentityUser] userManager' of constructor 'Void .ctor(Microsoft.AspNetCore.Identity.UserManager1[Microsoft.AspNetCore.Identity.IdentityUser], Microsoft.Extensions.Options.IOptions1[NetDevPack.Identity.Jwt.AppJwtSettings], NetDevPack.Security.Jwt.Core.Interfaces.IJwtService, Microsoft.AspNetCore.Http.IHttpContextAccessor)'. at Autofac.Core.Activators.Reflection.ReflectionActivator.<>c__DisplayClass12_0.<UseSingleConstructorActivation>b__0(ResolveRequestContext ctxt, Action1 next)
at Autofac.Core.Resolving.Pipeline.ResolvePipelineBuilder.<>c__DisplayClass14_0.b__1(ResolveRequestContext ctxt)
at Autofac.Core.Resolving.Middleware.DisposalTrackingMiddleware.Execute(ResolveRequestContext context, Action1 next) at Autofac.Core.Resolving.Pipeline.ResolvePipelineBuilder.<>c__DisplayClass14_0.<BuildPipeline>b__1(ResolveRequestContext ctxt) at Autofac.Core.Resolving.Middleware.ActivatorErrorHandlingMiddleware.Execute(ResolveRequestContext context, Action1 next)
--- End of inner exception stack trace ---
at Autofac.Core.Resolving.Middleware.ActivatorErrorHandlingMiddleware.Execute(ResolveRequestContext context, Action1 next) at Autofac.Core.Resolving.Pipeline.ResolvePipelineBuilder.<>c__DisplayClass14_0.<BuildPipeline>b__1(ResolveRequestContext ctxt) at Autofac.Core.Resolving.Pipeline.ResolvePipelineBuilder.<>c__DisplayClass14_0.<BuildPipeline>b__1(ResolveRequestContext ctxt) at Autofac.Core.Resolving.Middleware.SharingMiddleware.<>c__DisplayClass5_0.<Execute>b__0() at Autofac.Core.Lifetime.LifetimeScope.CreateSharedInstance(Guid id, Func1 creator)
at Autofac.Core.Lifetime.LifetimeScope.CreateSharedInstance(Guid primaryId, Nullable1 qualifyingId, Func1 creator)
at Autofac.Core.Resolving.Middleware.SharingMiddleware.Execute(ResolveRequestContext context, Action1 next) at Autofac.Core.Resolving.Pipeline.ResolvePipelineBuilder.<>c__DisplayClass14_0.<BuildPipeline>b__1(ResolveRequestContext ctxt) at Autofac.Core.Resolving.Pipeline.ResolvePipelineBuilder.<>c__DisplayClass14_0.<BuildPipeline>b__1(ResolveRequestContext ctxt) at Autofac.Core.Resolving.Middleware.CircularDependencyDetectorMiddleware.Execute(ResolveRequestContext context, Action1 next)
at Autofac.Core.Resolving.Pipeline.ResolvePipelineBuilder.<>c__DisplayClass14_0.b__1(ResolveRequestContext ctxt)
at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, ResolveRequest request)
at Autofac.Core.Resolving.ResolveOperation.ExecuteOperation(ResolveRequest request)
at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable1 parameters, Object& instance) at Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable1 parameters)
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
at lambda_method486(Closure , IServiceProvider , Object[] )
at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass7_0.b__0(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass6_0.g__CreateController|0(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker invoker)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker invoker)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

HEADERS

Accept: /
Accept-Encoding: gzip, deflate, br
Accept-Language: pt-BR,pt;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6
Connection: close
Content-Length: 287
Content-Type: application/json
Host: localhost:44327
Referer: https://localhost:44327/swagger/index.html
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.53 Safari/537.36 Edg/103.0.1264.37
sec-ch-ua: " Not;A Brand";v="99", "Microsoft Edge";v="103", "Chromium";v="103"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
origin: https://localhost:44327
sec-fetch-site: same-origin
sec-fetch-mode: cors
sec-fetch-dest: empty

How does a library work without SecretKey?

I tried to create an authentication api without the secret key using the standard documentation on github.

My appsetting.json in Identity Provider Api

"AppJwtSettings": {
    "Issuer": "MyInssuerValue",    
    "Audience": "MyAudience" 
// SecretKey is missing
}

My Statup.cs in Identity Provider Api

 public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();

            services.AddMemoryCache(); // Add this line

            services.AddIdentityEntityFrameworkContextConfiguration(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
                b => b.MigrationsAssembly(GetType().Namespace)));

            services.AddIdentityConfiguration();

            services.AddJwtConfiguration(Configuration)
                    .AddNetDevPackIdentity<IdentityUser>();
                    
            services.AddSwaggerConfiguration();
        }

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwaggerConfiguration();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthConfiguration();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
// [...]

In the other api that is authenticated by the identity provider I made the following settings:

My appsetting.json in Web Api

"AppJwtSettings": {
    "Issuer": "MyInssuerValue",    
    "Audience": "MyAudience" 
// SecretKey is missing
}

My Program.cs in Web Api

var builder = WebApplication.CreateBuilder(args);

builder.Services?.AddJwtConfiguration(builder.Configuration);
// more code

var app = builder.Build();

// middlewares
app.UseAuthConfiguration();
//more middlewares

app.Run();

And for every request the answer is the same:

 content-length: 0 
 date: Thu,28 Jul 2022 18:22:22 GMT 
 server: Kestrel 
 www-authenticate: Bearer error="invalid_token",error_description="The signature key was not found" 

But, if include SecretKey parameter works fine!

Use a LDAP Server or ActiveDirectory to authenticate

Is your feature request related to a problem? Please describe.
Could be possible if the library use a LDAP or ActiveDirectory to authenticate and then return the JWT Token?

Describe the solution you'd like
So we could build like an interface where we would create the implementation and with it create the JWT Token with claims and any other thing required.

Sample not working

Describe the bug
When you run the sample project as is you get the following exception:

System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity.IUserClaimsPrincipalFactory1[AspNetCore.Jwt.Sample.Config.MyIntIdentityUser] Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.UserClaimsPrincipalFactory2[AspNetCore.Jwt.Sample.Config.MyIntIdentityUser,Microsoft.AspNetCore.Identity.IdentityRole1[System.Int32]]': Unable to resolve service for type 'Microsoft.AspNetCore.Identity.IRoleStore1[Microsoft.AspNetCore.Identity.IdentityRole1[System.Int32]]' while attempting to activate 'Microsoft.AspNetCore.Identity.RoleManager1[Microsoft.AspNetCore.Identity.IdentityRole1[System.Int32]]'.) (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity.RoleManager1[Microsoft.AspNetCore.Identity.IdentityRole1[System.Int32]] Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.RoleManager1[Microsoft.AspNetCore.Identity.IdentityRole1[System.Int32]]': Unable to resolve service for type 'Microsoft.AspNetCore.Identity.IRoleStore1[Microsoft.AspNetCore.Identity.IdentityRole1[System.Int32]]' while attempting to activate 'Microsoft.AspNetCore.Identity.RoleManager1[Microsoft.AspNetCore.Identity.IdentityRole1[System.Int32]]'.) (Error while validating the service descriptor 'ServiceType: NetDevPack.Identity.Interfaces.IJwtBuilder Lifetime: Scoped ImplementationType: NetDevPack.Identity.Jwt.JwtBuilderInject2[AspNetCore.Jwt.Sample.Config.MyIntIdentityUser,System.Int32]': Unable to resolve service for type 'Microsoft.Extensions.Caching.Memory.IMemoryCache' while attempting to activate 'NetDevPack.Security.Jwt.Core.DefaultStore.DataProtectionStore'.) (Error while validating the service descriptor 'ServiceType: NetDevPack.Security.Jwt.Core.Interfaces.IJwtService Lifetime: Scoped ImplementationType: NetDevPack.Security.Jwt.Core.Jwt.JwtService': Unable to resolve service for type 'Microsoft.Extensions.Caching.Memory.IMemoryCache' while attempting to activate 'NetDevPack.Security.Jwt.Core.DefaultStore.DataProtectionStore'.) (Error while validating the service descriptor 'ServiceType: NetDevPack.Security.Jwt.Core.Interfaces.IJsonWebKeyStore Lifetime: Scoped ImplementationType: NetDevPack.Security.Jwt.Core.DefaultStore.DataProtectionStore': Unable to resolve service for type 'Microsoft.Extensions.Caching.Memory.IMemoryCache' while attempting to activate 'NetDevPack.Security.Jwt.Core.DefaultStore.DataProtectionStore'.)'

if you comment out

builder.Services.AddCustomIdentityAndKeyConfiguration(builder.Configuration);

and uncomment

//builder.Services.AddDefaultIdentityConfiguration(builder.Configuration);

you get a runtime exception:
System.InvalidOperationException: Unable to resolve service for type 'NetDevPack.Identity.Interfaces.IJwtBuilder' while attempting to activate 'AspNetCore.Jwt.Sample.Controllers.AuthController'.
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
at lambda_method9(Closure , IServiceProvider , Object[] )
at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass7_0.b__0(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass6_0.g__CreateController|0(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

Default role for new users

Hey, first of all thank you for this great library, I've got two quick questions , I've looked through the demo but I'm still unsure of the correct way to do this.

  1. How to set a default Role to new users , should this be done in a way similar to this or am I off?
  2. Users with a specified role do not inherit the claims of the role , is there a setting to turn this on?

Thanks in advance!

Change the Context Name

Its not a problem, but it would be better if change the name of NetDevPackAppDbContext to the Identity original ApplicationDbContext name. As it only appear at the source code, can be hard to remember the name.

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here are some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Missing package.json file.

A package.json file at the root of your project is required to release on npm.

Please follow the npm guideline to create a valid package.json file.


Good luck with your project ✨

Your semantic-release bot 📦🚀

Dependency Injection

I was following the readme to configure my project and when I ran my project I got the following issue.

I added the version 6.1.7 (NetDevPack.Identity)

System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: NetDevPack.Identity.Interfaces.IJwtBuilder Lifetime: Scoped ImplementationType: NetDevPack.Identity.Jwt.JwtBuilderInject`2[Microsoft.AspNetCore.Identity.IdentityUser,System.String]': Unable to resolve service for type 'Microsoft.Extensions.Caching.Memory.IMemoryCache' while attempting to activate 'NetDevPack.Security.Jwt.Core.DefaultStore.DataProtectionStore'.) (Error while validating the service descriptor 'ServiceType: NetDevPack.Security.Jwt.Core.Interfaces.IJwtService Lifetime: Scoped ImplementationType: NetDevPack.Security.Jwt.Core.Jwt.JwtService': Unable to resolve service for type 'Microsoft.Extensions.Caching.Memory.IMemoryCache' while attempting to activate 'NetDevPack.Security.Jwt.Core.DefaultStore.DataProtectionStore'.) (Error while validating the service descriptor 'ServiceType: NetDevPack.Security.Jwt.Core.Interfaces.IJsonWebKeyStore Lifetime: Scoped ImplementationType: NetDevPack.Security.Jwt.Core.DefaultStore.DataProtectionStore': Unable to resolve service for type 'Microsoft.Extensions.Caching.Memory.IMemoryCache' while attempting to activate 'NetDevPack.Security.Jwt.Core.DefaultStore.DataProtectionStore'.)'

I used the following commands.

builder.Services.AddIdentityEntityFrameworkContextConfiguration(options =>
     options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"),
     b => b.MigrationsAssembly("AspNetCore.Jwt.Sample")));

builder.Services.AddIdentityConfiguration();

builder.Services.AddJwtConfiguration(builder.Configuration)
         .AddNetDevPackIdentity();

....

app.UseAuthConfiguration();

I solved this issue adding the following item.

builder.Services.AddMemoryCache();

my question is if this setting is missing from the readme or would there be some other method that would solve this dependency injection error (JwtService depends on Microsoft.Extensions.Caching.Memory.IMemoryCache)?

Custom IdentityUser

I liked the package, but I would like to use the IdentityUser with the ID with Int type, however the method that generates the JWT does not currently allow a generic implementation.

Gostei do pack mas queria usar o IdentityUser com o Id do tipo Int, porém o metodo que gera o JWT não permite uma implementação genérica atualmente.

GetUserResponse return a null 204 error

EDIT / UPDATE

The problem is not with the .net version, is with the NetDevPack.Identity version. This issue occurs with the 1.2.0 version only. Using the 1.1.1 work perfectly even with .net5

---------------------------

Describe the bug
Trying to change the default GetFullJwt to GetUserResponse at Login action in AccountController in a .net5 project return an error 204 when try to Login or create a new Account (note that, even though return an error, the user is created at data base). Using with .net core 3.1 work just fine

To Reproduce
Just try to use with an .net5 project

Expected behavior
The response should be 200 with the user's token and infos.

I can't use jwt with "authorize" attribute. where am i doing wrong?

my settings

    
    public static void AddDbConfiguration(this IServiceCollection services, IConfiguration configuration)
    {
        services.AddDbContext<DataListContext>(opt =>
            {
                opt.UseSqlServer(configuration.GetConnectionString("DefaultConnection"),
                    builder => { builder.MigrationsAssembly(typeof(DataListContext).Assembly.FullName); });
            })
            .AddIdentity<AspNetUser, AspNetRole>(opt =>
            {
                opt.SignIn.RequireConfirmedEmail = true;
                opt.SignIn.RequireConfirmedPhoneNumber = true;
                opt.SignIn.RequireConfirmedAccount = true;
            })
            .AddUserManager<UserManager<AspNetUser>>()
            .AddRoleManager<RoleManager<AspNetRole>>()
            .AddSignInManager<SignInManager<AspNetUser>>()
            .AddErrorDescriber<TurkishIdentityErrorDescriber>()
            .AddEntityFrameworkStores<DataListContext>()
            .AddDefaultTokenProviders();

        services.AddJwtConfiguration(configuration).AddNetDevPackIdentity<AspNetUser, int>(opt => { });

        services.AddScoped<IAspNetUser, NetDevPack.Identity.User.AspNetUser>();
    }

mycontroller settings

   
   services.AddControllersWithViews(opt =>
            {
                //for Authorization
                var policy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme)
                    .RequireAuthenticatedUser()
                    .Build();

                opt.Filters.Add(new AuthorizeFilter(policy));
     })

appsettings.json

"AppJwtSettings": { "Audience": "MyApplication.Name" },

mycontroller

 public async Task<IActionResult> SignIn([FromBody] LoginDto loginDto)
    { 
        var user = await _userManager.FindByEmailAsync(loginDto.Email);

        if (user is not null)
        {
            var result = await _signInManager.PasswordSignInAsync(user, loginDto.Password, loginDto.RememberMe, true);

            if (result.Succeeded)
            {
                var response = await GetJwtToken(user);
                return Ok(response);
            }

            if (result.ToString() != "Failed")
            {
                return NotFound(result.ToString());
            }
        }

        return NotFound("Email or password is incorrect");
    }

 [NonAction]
    private Task<UserResponse> GetJwtToken(AspNetUser user)
    {
        return _jwtBuilder
            .WithUserId(user.Id.ToString())
            .WithUsername(user.UserName)
            .WithEmail(user.Email)
            .WithJwtClaims()
            .WithUserClaims()
            .WithUserRoles()
            .WithRefreshToken()
            .BuildUserResponse();
    }

my error;

[23:09:22 INF] Request starting HTTP/1.1 GET https://localhost:5001/api/myinternethatlaris - -
[23:09:22 INF] Executing endpoint 'DataListWebUI.Controllers.MyInternetHatlarisController.Get (DataListWebUI)'
[23:09:22 INF] Route matched with {action = "Get", controller = "MyInternetHatlaris"}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IActionResult Get(Microsoft.AspNetCore.OData.Query.ODataQueryOptions1[DataListWebUI.ViewModels.Serverside.MyInternetHatlariDto]) on controller DataListWebUI.Controllers.MyInternetHatlarisController (DataListWebUI). [23:09:22 INF] Failed to validate the token. Microsoft.IdentityModel.Tokens.SecurityTokenSignatureKeyNotFoundException: IDX10501: Signature validation failed. Unable to match key: kid: 'GySumUujvO3KXAfWoANOZg'. Number of keys in TokenValidationParameters: '0'. Number of keys in Configuration: '0'. Exceptions caught: ''. token: '{"alg":"PS256","kid":"GySumUujvO3KXAfWoANOZg","typ":"at+jwt"}.{"sub":"3","email":"[email protected]","jti":"8aa1b8ea-e5a0-4f5a-b8f0-515b7d480edc","iat":1652644903,"nbf":1652644903,"exp":1652648503,"iss":"NetDevPack.Identity","aud":"MyApplication.Name"}'. at Microsoft.IdentityModel.Tokens.InternalValidators.ValidateLifetimeAndIssuerAfterSignatureNotValidatedJwt(SecurityToken securityToken, Nullable1 notBefore, Nullable`1 expires, String kid, TokenValidationParameters validationParameters, BaseConfiguration configuration, StringBuilder exceptionStrings, Int32 numKeysInConfiguration, Int32 numKeysInTokenValidationParameters)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateSignature(String token, TokenValidationParameters validationParameters, BaseConfiguration configuration)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateJWS(String token, TokenValidationParameters validationParameters, BaseConfiguration currentConfiguration, SecurityToken& signatureValidatedToken, ExceptionDispatchInfo& exceptionThrown)
--- End of stack trace from previous location ---
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, JwtSecurityToken outerToken, TokenValidationParameters validationParameters, SecurityToken& signatureValidatedToken)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken& validatedToken)
at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
[23:09:22 INF] Bearer was not authenticated. Failure message: IDX10501: Signature validation failed. Unable to match key:
kid: 'GySumUujvO3KXAfWoANOZg'.
Number of keys in TokenValidationParameters: '0'.
Number of keys in Configuration: '0'.
Exceptions caught:
''.
token: '{"alg":"PS256","kid":"GySumUujvO3KXAfWoANOZg","typ":"at+jwt"}.{"sub":"3","email":"[email protected]","jti":"8aa1b8ea-e5a0-4f5a-b8f0-515b7d480edc","iat":1652644903,"nbf":1652644903,"exp":1652648503,"iss":"NetDevPack.Identity","aud":"MyApplication.Name"}'.
[23:09:22 INF] Authorization failed. These requirements were not met:
DenyAnonymousAuthorizationRequirement: Requires an authenticated user.
[23:09:22 INF] Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
[23:09:22 INF] Executing ChallengeResult with authentication schemes (["Bearer"]).
[23:09:22 INF] AuthenticationScheme: Bearer was challenged.
[23:09:22 INF] Executed action DataListWebUI.Controllers.MyInternetHatlarisController.Get (DataListWebUI) in 0.7457ms
[23:09:22 INF] Executed endpoint 'DataListWebUI.Controllers.MyInternetHatlarisController.Get (DataListWebUI)'
[23:09:22 INF] Request finished HTTP/1.1 GET https://localhost:5001/api/myinternethatlaris - - - 401 0 - 1.4608ms

Add migration error using AddCustomIdentity

I'm trying to use AddCustomIdentity() and I'm getting this error when run the add migration command.

No DbContext named 'NetDevPackAppDbContext' was found.
File IdentityConfig.cs

services.AddIdentityEntityFrameworkContextConfiguration(options =>
                options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"),
                    b => b.MigrationsAssembly("Equinox.Infra.CrossCutting.Identity")))
                .AddCustomIdentity<ApplicationUser>();

ApplicationUser.cs

public class ApplicationUser : IdentityUser
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

AspNetCore.Jwt.Sample

Could not load file or assembly 'AspNetCore.Jwt.Sample, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified when I run using .Net Core 5

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.