Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How add ASP.NET Core identity to existing Core mvc project?

I have already started my dotnet core mvc project without identity on Mac with CLI and now I want to add this feature. The only option I have known till now is to create a new project by

dotnet new mvc --auth

Is there a better way to add identity to an existing project? I hope there is a 'dotnet new' command.

like image 273
Anil P Babu Avatar asked May 04 '18 16:05

Anil P Babu


People also ask

What is identity in ASP.NET Core MVC?

ASP.NET Core Identity: Is an API that supports user interface (UI) login functionality. Manages users, passwords, profile data, roles, claims, tokens, email confirmation, and more.

How do I change the authentication in MVC project?

Select File >> New >> select ASP.NET Core Web Application, and change the authentication to Windows Authentication. We can also configure the existing application for Windows Authentication by selecting the option of WA. To configure the authentication manually, open Visual Studio project properties >> go to Debug tab.


1 Answers

According to docs.microsoft.com you can scaffold identity into an existing MVC project with aspnet-codegenerator.

1) If you have not previously installed the ASP.NET Core scaffolder, install it now:

dotnet tool install -g dotnet-aspnet-codegenerator

2) Add a package reference to Microsoft.VisualStudio.Web.CodeGeneration.Design to the project (*.csproj) file. Run the following command in the project directory:

dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design
dotnet restore

3) Run the following command to list the Identity scaffolder options:

dotnet aspnet-codegenerator identity -h

4) In the project folder, run the Identity scaffolder with the options you want. For example, to setup identity with the default UI and the minimum number of files, run the following command:

dotnet aspnet-codegenerator identity --useDefaultUI

5) The generated Identity database code requires Entity Framework Core Migrations. Create a migration and update the database. For example, run the following commands:

dotnet ef migrations add CreateIdentitySchema
dotnet ef database update

6) Call UseAuthentication after UseStaticFiles:

public class Startup
{

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseAuthentication(); // <-- add this line
        app.UseMvcWithDefaultRoute();
    }
}
like image 117
ulmer-morozov Avatar answered Sep 19 '22 15:09

ulmer-morozov