Giter Club home page Giter Club logo

cleanarchitecture.webapi's Introduction

ASP.NET Core WebApi - Clean Architecture

.NET Core GitHub stars Twitter Follow


An Implementation of Clean Architecture with ASP.NET Core 3.1 WebApi. With this Open-Source BoilerPlate Template, you will get access to the world of Loosely-Coupled and Inverted-Dependency Architecture in ASP.NET Core 3.1 WebApi with a lot of best practices.

Check out the Project Page to learn more about this Open Source Project.

Read the Changelog file to see the new changes.

Annoucement : fullstackhero - .NET 6.0 Clean Architecture WebAPI !

I am no longer supporting this project. No more new features will be added to this repository. I am building a .NET WebApi 6.0 Clean Architecture Boilerplate Project with better features and Multitenancy ofcourse! Visit the new project - https://github.com/fullstackhero/dotnet-webapi-boilerplate

fullstackhero

0.0.1 RC is available now!

This is the first pre-release version of the fullstackhero .NET WebAPI Boilerplate package. Newer versions will be available on a weekly basis with newer updates and patches. Read the getting-started guide for more.

The Release Version is expected to be out by Novemeber, 2021 as soon as .NET 6 LTS is launched by Microsoft. Preview versions of this project is available for Initial Developer Testing.

Important Links & Documentations

[Documentation] Overview - Read

[Documentation] Getting Started - Read

[Documentation] Development Environment - Learn about setting up the DEV environment

Track Progress - Release 1.0 Milestones

Participate in Discussions - QNA & General Discussions

Join our Discord - fullstackhero @ Discord

Releases - ASP.NET Core 3.1 Template

v1.1 - Stable Release - Download the Stable Release

v1.0-preview - Download the first Preview here

v1.1

Follow these steps to get started with this Boiler Plate Template.

Download the Extension

Make sure Visual Studio 2019 is installed on your machine with the latest SDK. Download from Visual Studio Marketplace. Install it on your machine.

Follow these Steps to get started.

alt text

alt text

You Solution Template is Ready!

alt text

Visit the Project Page to learn more - Click Here

Alternatively you can also clone the Repository.

  1. Clone this Repository and Extract it to a Folder.
  2. Change the Connection Strings for the Application and Identity in the WebApi/appsettings.json - (WebApi Project)
  3. Run the following commands on Powershell in the WebApi Projecct's Directory.
  • dotnet restore
  • dotnet ef database update -Context ApplicationDbContext
  • dotnet ef database update -Context IdentityContext
  • dotnet run (OR) Run the Solution using Visual Studio 2019

Check out my blog or say Hi on Twitter!

How to use MySQL or PostgreSQL as your Data Provider

The Project currently uses MSSQL as the default Data Provider. If you are more comfortable with MySQL or PostgreSQL, here is how to migrate to them easily.

  1. delete all existing file inside migrations folder on both project

    • {YourProjectName}.Infrastructure.Identity
    • {YourProjectName}.Infrastructure.Persistence
  2. In in ServiceExtensions.cs and ServiceRegistration.cs change from options.UseSqlServer to:

For MySql

options.UseMySql

For PostgreSQL

options.UseNpgsql

  1. Add NuGet packages to both projects (Infrastructure.Identity and Infrastructure.Persistence):

For MySql:

run dotnet add package Pomelo.EntityFrameworkCore.MySql --version 3.1.2 (remember to do this on both projects)

For PostgreSQL:

run

dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL
dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL.Design

(remember to do this on both projects)

  1. on IdentityContext.cs comment builder.HasDefaultSchema("Identity"); because ef doesn't support that on mysql

  2. cd to {YourProjectName}.Infrastructure.Identity and run

    • dotnet ef database update --startup-project ../{YourProjectName}.WebApi/{YourProjectName}.WebApi.csproj -c "IdentityContext"
    • dotnet ef migrations add Initial --startup-project ../{YourProjectName}.WebApi/{YourProjectName}.WebApi.csproj -c "IdentityContext"
  3. cd to {YourProjectName}.Infrastructure.Persistence and run

    • dotnet ef database update --startup-project ../{YourProjectName}.WebApi/{YourProjectName}.WebApi.csproj -c "ApplicationDbContext"
    • dotnet ef migrations add Initial --startup-project ../{YourProjectName}.WebApi/{YourProjectName}.WebApi.csproj -c "ApplicationDbContext"

The above guide (To use MySQL) was contributed by geekz-reno.

Default Roles & Credentials

As soon you build and run your application, default users and roles get added to the database.

Default Roles are as follows.

  • SuperAdmin
  • Admin
  • Moderator
  • Basic

Here are the credentials for the default users.

You can use these default credentials to generate valid JWTokens at the ../api/account/authenticate endpoint.

Purpose of this Project

Does it really make sense to Setup your ASP.NET Core Solution everytime you start a new WebApi Project ? Aren't we wasting quite a lot of time in doing this over and over gain?

This is the exact Problem that I intend to solve with this Full-Fledged ASP.NET Core 3.1 WebApi Solution Template, that also follows various principles of Clean Architecture.

The primary goal is to create a Full-Fledged implementation, that is well documented along with the steps taken to build this Solution from Scratch. This Solution Template will also be available within Visual Studio 2019 (by installing the required Nuget Package / Extension).

  • Demonstrate Clean Monolith Architecture in ASP.NET Core 3.1
  • This is not a Proof of Concept
  • Implementation that is ready for Production
  • Integrate the most essential libraries and packages

Give a Star ⭐️

If you found this Implementation helpful or used it in your Projects, do give it a star. Thanks! Or, If you are feeling really generous, Support the Project with a small contribution!

Technologies

  • ASP.NET Core 3.1 WebApi
  • REST Standards
  • .NET Core 3.1 / Standard 2.1 Libraries

Features

  • Onion Architecture
  • CQRS with MediatR Library
  • Entity Framework Core - Code First
  • Repository Pattern - Generic
  • MediatR Pipeline Logging & Validation
  • Serilog
  • Swagger UI
  • Response Wrappers
  • Healthchecks
  • Pagination
  • In-Memory Caching
  • Redis Caching
  • In-Memory Database
  • Microsoft Identity with JWT Authentication
  • Role based Authorization
  • Identity Seeding
  • Database Seeding
  • Custom Exception Handling Middlewares
  • API Versioning
  • Fluent Validation
  • Automapper
  • SMTP / Mailkit / Sendgrid Email Service
  • Complete User Management Module (Register / Generate Token / Forgot Password / Confirmation Mail)
  • User Auditing

Brief Overview

alt text

Prerequisites

  • Visual Studio 2019 Community and above
  • .NET Core 3.1 SDK and above
  • Basic Understanding of Architectures and Clean Code Principles
  • I Recommend that you read Onion Architecture In ASP.NET Core With CQRS – Detailed article to understand this implementation much better. This project is just an Advanced Version of the mentioned article.

Getting Started

Changelog

Every changes / additions / deletions will be recorded in the Changelog file.

Questions? Bugs? Suggestions for Improvement?

Having any issues or troubles getting started? Get in touch with me or Raise a Bug or Feature Request. Always happy to help.

Support

Has this Project helped you learn something New? or Helped you at work? Do Consider Supporting.

Buy Me A Coffee

Share it!

I have personally not come across a clean implementation on a WebAPI, which is the reason that I started building this up. There are quite a lot of improvements and fixes along the way from the day I started out. Thanks to the community for the support and suggestions. Please share this Repository within your developer community, if you think that this would a difference! Thanks.

About the Author

Mukesh Murugan

Licensing

iammukeshm/CleanArchitecture.WebApi Project is licensed with the MIT License.

cleanarchitecture.webapi's People

Contributors

brunomoureau avatar dankyungu avatar dependabot[bot] avatar iammukeshm avatar nerdsquirrel avatar nprovotorov avatar rtbhosale avatar virux99 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  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

cleanarchitecture.webapi's Issues

Error in handling Authentication failed event

I'm testing authentication logic. JWT token expired and validation system produced exception:
IDX10223: Lifetime validation failed. The token is expired. ValidTo: 'System.DateTime', Current time: 'System.DateTime'.

OnAuthenticationFailed handler called and response started with status code 500
Then OnChallenge handler called.
On row context.Response.StatusCode = 401; i got InvalidOperationException because response already started.

o.Events = new JwtBearerEvents()
{
    OnAuthenticationFailed = c =>         //Called first   <<---------------------
    {
        c.NoResult();
        c.Response.StatusCode = 500;
        c.Response.ContentType = "text/plain";
        return c.Response.WriteAsync(c.Exception.ToString());
    },
    OnChallenge = context =>             //Called second  <<---------------------
    {
        context.HandleResponse();
        context.Response.StatusCode = 401;                           // Exception here because response alredy started 
        context.Response.ContentType = "application/json";
        var result = JsonConvert.SerializeObject(new Response<string>("You are not Authorized"));
        return context.Response.WriteAsync(result);
    },
    OnForbidden = context =>
    {
        context.Response.StatusCode = 403;
        context.Response.ContentType = "application/json";
        var result = JsonConvert.SerializeObject(new Response<string>("You are not authorized to access this resource"));
        return context.Response.WriteAsync(result);
    },
};

So, in that template authentication done somewhat wrong and won't work at all after token expiration.
Client do not receive any responce from server (status code = 0, error = Failed receive response stream)

Feature request

Describe alternatives you've considered
https://github.com/iammukeshm/CleanArchitecture.WebApi/blob/master/Application/Interfaces/IDateTimeService.cs.
This code is a good candidate to become an extension method

https://github.com/iammukeshm/CleanArchitecture.WebApi/blob/master/Application/Interfaces/IGenericRepositoryAsync.cs
There is a precedent to split this repository into the read-only repo and write-only repo (CQRS).

https://github.com/iammukeshm/CleanArchitecture.WebApi/blob/master/Application/Interfaces/IEmailService.cs
This can be part of the infrastructure code. moving this code into a common lib would be nice.

https://github.com/iammukeshm/CleanArchitecture.WebApi/blob/master/Application/Behaviours/ValidationBehaviour.cs
Throwing exception vs returning error from the business layer is subject to debate, but returning an error from the business layer seems more meaningful ( Honestly, this is a personal belief)
https://softwareengineering.stackexchange.com/questions/405038/result-object-vs-throwing-exceptions

https://github.com/iammukeshm/CleanArchitecture.WebApi/blob/master/Application/Wrappers/PagedResponse.cs
https://github.com/iammukeshm/CleanArchitecture.WebApi/blob/master/Application/Wrappers/Response.cs
The above code files are eligible to move into common lib.

https://github.com/iammukeshm/CleanArchitecture.WebApi/tree/master/Domain/Common
Context of a DDD approach, This can be moved to Sharable code space. ( SharedKernal/ common lib)

https://github.com/iammukeshm/CleanArchitecture.WebApi/blob/master/Domain/Common/BaseEntity.cs
Nice to have a generic version of BaseEntity to support different Id type (int,guid,string etc).

https://github.com/iammukeshm/CleanArchitecture.WebApi/blob/master/Domain/Common/AuditableBaseEntity.cs
Seems good but can be great by adding additional details like Ip, browser,

https://github.com/iammukeshm/CleanArchitecture.WebApi/tree/master/Domain/Settings
Not sure this is part of Domain, Seems good candidates for Infrastructure.

All the above comments are just personal thoughts. This project seems promising and appreciable. Good Job Man!

Why is 401 always returned in JwtBearerEvent OnChallenge?

When adding authentication in AddIdentityInfrastructure() in ServiceExtensions.cs, the code clearly states it should return 401 when OnChallenge event is invoked. Why is that? Nothing bad has really happened?

OnChallenge = context =>
                        {
                            context.HandleResponse();
                            context.Response.StatusCode = 401;
                            context.Response.ContentType = "application/json";
                            var result = JsonConvert.SerializeObject(new Response<string>("You are not Authorized"));
                            return context.Response.WriteAsync(result);
                        }

https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.jwtbearer.jwtbearerevents.onchallenge?view=aspnetcore-3.0

seeder not inserted

I try re-code the infrastructure Identity. And try to add migration, after that update-database.

but after its done, when I check database, there is no seed data inserted

Mysql Error Migrations

im using pamelo

dotnet add package Pomelo.EntityFrameworkCore.MySql --version 3.1.2

error this

dotnet ef database update -c "IdentityContext"
Build started...
Build succeeded.
System.InvalidOperationException: A schema "Identity" has been set for an object of type "CreateTableOperation" with the name of "Role". MySQL does not support the EF Core concept of schemas. Any schema property of any "MigrationOperation" must be null.
at Pomelo.EntityFrameworkCore.MySql.Migrations.MySqlMigrationsSqlGenerator.CheckSchema(MigrationOperation operation)
at Pomelo.EntityFrameworkCore.MySql.Migrations.MySqlMigrationsSqlGenerator.Generate(MigrationOperation operation, IModel model, MigrationCommandListBuilder builder)
at Microsoft.EntityFrameworkCore.Migrations.MigrationsSqlGenerator.Generate(IReadOnlyList`1 operations, IModel model)
at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.GenerateUpSql(Migration migration)
at Pomelo.EntityFrameworkCore.MySql.Migrations.Internal.MySqlMigrator.GenerateUpSql(Migration migration)
at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.<>c__DisplayClass15_2.b__2()
at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
at Pomelo.EntityFrameworkCore.MySql.Migrations.Internal.MySqlMigrator.Migrate(String targetMigration)
at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
A schema "Identity" has been set for an object of type "CreateTableOperation" with the name of "Role". MySQL does not support the EF Core concept of schemas. Any schema property of any "MigrationOperation" must be null.

how to deal join tables query

hi,i found the example is only a table curd,in actual . many interface include many tables join .i hope you help me .howto deal ths
scenario。

register error

when try to register new user get json error without IdentityError messages

{
  "Succeeded": false,
  **"Message": "System.Collections.Generic.List`1[Microsoft.AspNetCore.Identity.IdentityError]",**
  "Errors": null,
  "Data": null
}

for example., try to register new user with this json:

{
  "firstName": "string",
  "lastName": "string",
  "email": "[email protected]",
  "userName": "string",
  "password": "string",
  "confirmPassword": "string"
}

the Message must return 3 errors from result.Errors

  1. Passwords must have at least one non alphanumeric character.
  2. Passwords must have at least one digit ('0'-'9').
  3. Passwords must have at least one uppercase ('A'-'Z').

Unrecognized option '-Context' when running dotnet ef command

Describe the bug
When following the commands to install, after dotnet restore it gives the error Unrocognized option '-Context'

To Reproduce
Steps to reproduce the behavior:

  1. Clone Project
  2. Change connection string
  3. Run dotnet restore
  4. Run dotnet-ef database update -Context ApplicationDbContext

Expected behavior
I expected it would create the tables

Desktop (please complete the following information):

  • OS: Windows 10
  • 3.1 SDK installed

Some doubts with the structure of the template

Hi, great work with this template. Right now I am testing your template and would like to hear your thoughts regarding the following topic:
I have a scenario where I want to use your template to implement a test backend, this backend will be consumed by a Xamarin mobile app and I am stuck at the point of sharing DTO's, I don't think the best option is to create a dependency from my Xamarin project to the application layer, so I have thought about taking the DTO's to a separate project that is consumed by the application layer and the app.
Something that is difficult for me to understand is also the relationship between DTO's and ViewModels that I see in some Queries, can you explain it?
I hope you can let me read your thoughts regarding all of the above.
Thank you

Add MySQL Provider

Hi, thank for your great efforts for this boilerplate.

Just want to add some instruction for newcomers like me, if you prefer to use mysql than mssql,

  1. delete all existing file inside migrations folder on both project

    • {YourProjectName}.Infrastructure.Identity
    • {YourProjectName}.Infrastructure.Persistence
  2. change from options.UseSqlServer to options.UseMySql in ServiceExtensions.cs and ServiceRegistration.cs

  3. run dotnet add package Pomelo.EntityFrameworkCore.MySql --version 3.1.2 on two project/subproject

  4. on IdentityContext.cs comment builder.HasDefaultSchema("Identity"); because ef doesn't support that on mysql

  5. cd to {YourProjectName}.Infrastructure.Identity and run

    • dotnet ef database update --startup-project ../{YourProjectName}.WebApi/{YourProjectName}.WebApi.csproj -c "IdentityContext"
    • dotnet ef migrations add Initial --startup-project ../{YourProjectName}.WebApi/{YourProjectName}.WebApi.csproj -c "IdentityContext"
  6. cd to {YourProjectName}.Infrastructure.Persistence and run

    • dotnet ef database update --startup-project ../{YourProjectName}.WebApi/{YourProjectName}.WebApi.csproj -c "ApplicationDbContext"
    • dotnet ef migrations add Initial --startup-project ../{YourProjectName}.WebApi/{YourProjectName}.WebApi.csproj -c "ApplicationDbContext"

One more, when i try to login i got this error,

{ "Succeeded": false, "Message": "nodename nor servname provided, or not known", "Errors": null, "Data": null }

the problem was with var host = Dns.GetHostEntry(Dns.GetHostName()); in IpHelper.cs

just try to replace with,

        private static string GetLocalIPv4(NetworkInterfaceType type)
        {
            var output = "";
            foreach (var item in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (item.NetworkInterfaceType == type && item.OperationalStatus == OperationalStatus.Up)
                {
                    var adapterProperties = item.GetIPProperties();
                    if (adapterProperties.GatewayAddresses.FirstOrDefault() != null)
                    {
                        foreach (var ip in adapterProperties.UnicastAddresses)
                        {
                            if (ip.Address.AddressFamily != AddressFamily.InterNetwork) continue;
                            
                            output = ip.Address.ToString();
                            break;
                        }
                    }
                }

                if (output != "")
                    break;
            }

            return output;
        }

        public static string GetIpAddress()
        {
            return GetLocalIPv4(NetworkInterfaceType.Ethernet);
            // var host = Dns.GetHostEntry(Dns.GetHostName());
            // foreach (var ip in host.AddressList)
            // {
            //     if (ip.AddressFamily == AddressFamily.InterNetwork)
            //     {
            //         return ip.ToString();
            //     }
            // }
            // return string.Empty;
        }

reff this

Postgresql support

How should I implement PostgreSQL? The directives for MySQL do not work successfully for PostgreSQL.

best regards

Adding a Cookie option to compliment JWT

Is your feature request related to a problem? Please describe.
Currently, when using an API built like this with a modern front end (e.g. Angular, React, Vue), you need to store the JWT in localStorage or sessionStorage. You can also create a cookie client side, but that comes with risks of its own.

Describe the solution you'd like
Ideally, we'd be able to return an HttpOnly cookie with the JWT to be used that way. As a bonus, I've seen an even more secure method of using cokoies and JWT by hvaing your API use two cookies, one HttpOnly and one client side cookie, both of which would be required to have a valid session.

Describe alternatives you've considered
I'm researching how to add this on my project, but am new to the auth realm, so figured I'd float the idea here since it's a very common need.

Any ideas to implement complex authorization logic

I need to implement complex authorization logic, normally I would solve this using Identity policies, in this architecture I don't know what would be a good way to implement this.
policies in the project for identity?
use validations in MediatR behaviorss?
Let me know your thoughts.

Serilog application layer database or serilog saving

Hello, I want to save my models to database or serilog.seq with serilog in business layer.

I tried the Webapi controller as follows, but there was no change in the console.

//**

public class ProductController : BaseApiController
{

    private readonly ILogger _logger;

    public ProductController(ILogger<ProductController> logger)
    {
        _logger = logger;
    }

    // GET: api/<controller>
    [HttpGet]
    public async Task<IActionResult> Get([FromQuery] GetAllProductsParameter filter)
    {
        var don = await Mediator.Send(new GetAllProductsQuery() { PageSize = filter.PageSize, PageNumber = filter.PageNumber });

        _logger.LogError("log is here!");
        return Ok(don);
    }

etc..
**//
For example why always use entity framework and mssql !

i am using dapper and oracle db.

** I would be glad if you could help with this

Error response occurred when try to give wrong password policy.

Describe the bug
Error occurred when register new account when try to give wrong password policy on identity

To Reproduce
add identityoptions to services.AddIdentity

opt.Password.RequireDigit = true;
opt.Password.RequireLowercase = true;
opt.Password.RequireNonAlphanumeric = false;
opt.Password.RequireUppercase = true;

when i try to give password adindaku, will return this response.

{
  "Succeeded": false,
  "Message": "System.Collections.Generic.List`1[Microsoft.AspNetCore.Identity.IdentityError]",
  "Errors": null,
  "Data": null
}

Expected behavior
will return correct validation message

{
  "Succeeded": false,
  "Message": "One or more validation failures have occurred.",
  "Errors": [
    "Passwords must have at least one digit ('0'-'9').",
    "Passwords must have at least one uppercase ('A'-'Z')."
  ],
  "Data": null
}

Desktop (please complete the following information):

  • OS: MacOS Catalina

Additional context
the problem with throw new ApiException($"{result.Errors}"); it has string constructor.
problem solve when i switch to throw new ValidationException(result.Errors.Select(x => x.Description)); and add another constructor on ValidationException.cs that accept IEnumerable<string> failures.

but i think is that are not acceptable solution because it always return error with header message
"Message": "One or more validation failures have occurred.", either that the exception come from IdentityError or database error.

SSLPort is wrong

Describe the bug
When running your solution, a CONN_RESET error will show up in Chrome, and the solution will start but won't work

To Reproduce
Just install the VSIX you created

Expected behavior
I should see Swagger

The IIS Express documentation states that the minimum port number for SSL is 44300.
In your launchsettings the port is set to 41*** something, therefore it doesn't start.

dotnet/aspnetcore#7736 <<<< link

Cheers

Module development

This is great project. thank you.
Do you planning module development in this project?

Upgrade to .NET 5

Is your feature request related to a problem? Please describe.
It would nice for the project to be upgraded to .NET 5

Describe the solution you'd like
I could help with upgrading the project .NET 5 and then create a pull request. I just wanted to discuss it here first.

Describe alternatives you've considered
None at the moment

Additional context
No additional context at the moment

Adding multiple authentication providers

Describe the solution you'd like
Any thoughts on adding multiple authentication providers (e.g. Facebook, Google, Github, MS, Auth0, Okta, etc.)?

Describe alternatives you've considered
Currently researching how to add these, but don't have a ton of experience on the Auth side of things.

Multi-factor authentication

Authentication using username and password is good but not enough for some scenarios. I think it's good to add at least 2FA support to AccountService. ASP.NET Core Identity supports MFA Including security code generation, backup codes and even QR code generation.

ApplicationUser in a infraestructure

I see that the applicationuser is in the infrastructure project on identity, what idea do you have about the user being a domain entity and what approach could we use to keep it in the domain but at the same time not couple that layer to identity?
PD: He's doing a great job here, wait for a coffee from me.

Cannot create a new project inside this

I am trying to create one more Class Library project but I keep getting this error

NETSDK1004 Assets file 'C:\Code\Git<PrjName>\ClassLibrary1\obj\project.assets.json' not found. Run a NuGet package restore to generate this file. ClassLibrary1 C:\Program Files\dotnet\sdk\5.0.406\Sdks\Microsoft.NET.Sdk\targets\Microsoft.PackageDependencyResolution.targets 241

userManager in AccountService is null

Describe the bug
I tried to re-create this to dotnet core 6 for my project, I believe nothing wrong with my code becuase I tried to copy and paste and modify one by one. but when I try for register, _userManager is null

Expected behavior
_userManager in AccountService is populated or not null

Screenshots
Screen Shot 2022-07-26 at 19 34 22

Desktop (please complete the following information):

  • OS: Mac
  • Browser Chrome

Additional context
this is my program.cs in web api

using Application;
using Application.Interfaces;
using Infrastructure.Identity;
using Infrastructure.Persistence;
using Infrastructure.Identity.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Readbuk.Api.Services;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddApplication();

builder.Services.AddIdentityInfrastructure(builder.Configuration);
builder.Services.AddPersistenceInfrastructure(builder.Configuration);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddScoped<IAuthenticatedUserService, AuthenticatedUserService>();

#region API Versioning
// Add API Versioning to the Project
builder.Services.AddApiVersioning(config =>
{
    // Specify the default API Version as 1.0
    config.DefaultApiVersion = new ApiVersion(1, 0);
    // If the client hasn't specified the API version in the request, use the default API version number 
    config.AssumeDefaultVersionWhenUnspecified = true;
    // Advertise the API versions supported for the particular endpoint
    config.ReportApiVersions = true;
});
#endregion

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
    var scopeFactory = app.Services.GetRequiredService<IServiceScopeFactory>();
    using (var scope = scopeFactory.CreateScope())
    {
        var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
        var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
        //await DefaultRoles.SeedAsync(userManager, roleManager);
        //await DefaultBasicUser.SeedAsync(userManager, roleManager);
        //await DefaultSuperAdmin.SeedAsync(userManager, roleManager);
    }
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

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.