Scaffold Identity in ASP.NET Core projects

[ad_1]


By Rick Anderson

ASP.NET Core 2.1 and later provides ASP.NET Core Identity as a Razor Class Library. Applications that include Identity can apply the scaffolder to selectively add the source code contained in the Identity Razor Class Library (RCL). You might want to generate source code so you can modify the code and change the behavior. For example, you could instruct the scaffolder to generate the code used in registration. Generated code takes precedence over the same code in the Identity RCL.

Applications that do not include authentication can apply the scaffolder to add the RCL Identity package. You have the option of selecting Identity code to be generated.

Although the scaffolder generates most of the necessary code, you’ll have to update your project to complete the process. This document explains the steps needed to complete an Identity scaffolding update.

When the Identity scaffolder is run, a ScaffoldingReadme.txt file is created in the project directory. The ScaffoldingReadme.txt file contains general instructions on what’s needed to complete the Identity scaffolding update. This document contains more complete instructions than the ScaffoldingReadme.txt file.

We recommend using a source control system that shows file differences and allows you to back out of changes. Inspect the changes after running the Identity scaffolder.

Scaffold identity into an empty project

Run the Identity scaffolder:

  • From Solution Explorer, right-click on the project > Add > New Scaffolded Item.
  • From the left pane of the Add Scaffold dialog, select Identity > ADD.
  • In the ADD Identity dialog, select the options you want.
    • Select your existing layout page, or your layout file will be overwritten with incorrect markup. For example
      ~/Pages/Shared/_Layout.cshtml for Razor Pages
      ~/Views/Shared/_Layout.cshtml for MVC projects
    • Select the + button to create a new Data context class.
  • Select ADD.

Add the following highlighted calls to the Startup class:

public class Startup
        
    public void ConfigureServices(IServiceCollection services)
    
        services.AddMvc();
    

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    
        if (env.IsDevelopment())
        
            app.UseDeveloperExceptionPage();
        
        else
        
            app.UseHsts();
        

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseAuthentication();
        app.UseMvc();
    

UseHsts is recommended but not required. See HTTP Strict Transport Security Protocol for more information.

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

In the Visual Studio Package Manager Console:

Add-Migration CreateIdentitySchema
Update-Database

The “CreateIdentitySchema” name parameter for the Add-Migration command is arbitrary. "CreateIdentitySchema" describes the migration.

Scaffold identity into a Razor project without existing authorization

Run the Identity scaffolder:

  • From Solution Explorer, right-click on the project > Add > New Scaffolded Item.
  • From the left pane of the Add Scaffold dialog, select Identity > ADD.
  • In the ADD Identity dialog, select the options you want.
    • Select your existing layout page, or your layout file will be overwritten with incorrect markup. For example
      ~/Pages/Shared/_Layout.cshtml for Razor Pages
      ~/Views/Shared/_Layout.cshtml for MVC projects
    • Select the + button to create a new Data context class.
  • Select ADD.

Identity is configured in Areas/Identity/IdentityHostingStartup.cs. for more information, see IHostingStartup.

Migrations, UseAuthentication, and layout

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

In the Visual Studio Package Manager Console:

Add-Migration CreateIdentitySchema
Update-Database

The “CreateIdentitySchema” name parameter for the Add-Migration command is arbitrary. "CreateIdentitySchema" describes the migration.

In the Configure method of the Startup class, call UseAuthentication after UseStaticFiles:

public class Startup

    public Startup(IConfiguration configuration)
    
        Configuration = configuration;
    

    public IConfiguration Configuration  get; 

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

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

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseAuthentication();

        app.UseMvc();
    

UseHsts is recommended but not required. See HTTP Strict Transport Security Protocol for more information.

Layout changes

Optional: Add the login partial (_LoginPartial) to the layout file:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - RazorNoAuth8</title>

    <environment include="Development">
        <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
        <link rel="stylesheet" href="~/css/site.css" />
    </environment>
    <environment exclude="Development">
        <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css"
              asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
              asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
        <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
    </environment>
</head>
<body>
    <nav class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a asp-page="/Index" class="navbar-brand">RazorNoAuth8</a>
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li><a asp-page="/Index">Home</a></li>
                    <li><a asp-page="/About">About</a></li>
                    <li><a asp-page="/Contact">Contact</a></li>
                </ul>
                <partial name="_LoginPartial" />
            </div>
        </div>
    </nav>

    <partial name="_CookieConsentPartial" />

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; 2018 - RazorNoAuth8</p>
        </footer>
    </div>

    <environment include="Development">
        <script src="~/lib/jquery/dist/jquery.js"></script>
        <script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
        <script src="~/js/site.js" asp-append-version="true"></script>
    </environment>
    <environment exclude="Development">
        <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js"
                asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
                asp-fallback-test="window.jQuery"
                crossorigin="anonymous"
                integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk">
        </script>
        <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
                asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
                asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
                crossorigin="anonymous"
                integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
        </script>
        <script src="~/js/site.min.js" asp-append-version="true"></script>
    </environment>

    @RenderSection("Scripts", required: false)
</body>
</html>

Scaffold identity into a Razor project with authorization

Run the Identity scaffolder:

  • From Solution Explorer, right-click on the project > Add > New Scaffolded Item.
  • From the left pane of the Add Scaffold dialog, select Identity > ADD.
  • In the ADD Identity dialog, select the options you want.
    • Select your existing layout page, or your layout file will be overwritten with incorrect markup. When an existing _Layout.cshtml file is selected, it is not overwritten.

For example
~/Pages/Shared/_Layout.cshtml for Razor Pages
~/Views/Shared/_Layout.cshtml for MVC projects

  • To use your existing data context, select at least one file to override. You must select at least one file to add your data context.
    • Select your data context class.
    • Select ADD.
  • To create a new user context and possibly create a custom user class for Identity:
    • Select the + button to create a new Data context class.
    • Select ADD.

Note: If you’re creating a new user context, you don’t have to select a file to override.

Some Identity options are configured in Areas/Identity/IdentityHostingStartup.cs. For more information, see IHostingStartup.

Scaffold identity into an MVC project without existing authorization

Run the Identity scaffolder:

  • From Solution Explorer, right-click on the project > Add > New Scaffolded Item.
  • From the left pane of the Add Scaffold dialog, select Identity > ADD.
  • In the ADD Identity dialog, select the options you want.
    • Select your existing layout page, or your layout file will be overwritten with incorrect markup. For example
      ~/Pages/Shared/_Layout.cshtml for Razor Pages
      ~/Views/Shared/_Layout.cshtml for MVC projects
    • Select the + button to create a new Data context class.
  • Select ADD.

Optional: Add the login partial (_LoginPartial) to the Views/Shared/_Layout.cshtml file:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - MvcNoAuth3</title>

    <environment include="Development">
        <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
        <link rel="stylesheet" href="~/css/site.css" />
    </environment>
    <environment exclude="Development">
        <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css"
              asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
              asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
        <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
    </environment>
</head>
<body>
    <nav class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a asp-area="" asp-controller="Home" asp-action="Index" class="navbar-brand">MvcNoAuth3</a>
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
                    <li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li>
                    <li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>
                </ul>
                <partial name="_LoginPartial" />
            </div>
        </div>
    </nav>

    <partial name="_CookieConsentPartial" />

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; 2018 - MvcNoAuth3</p>
        </footer>
    </div>

    <environment include="Development">
        <script src="~/lib/jquery/dist/jquery.js"></script>
        <script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
        <script src="~/js/site.js" asp-append-version="true"></script>
    </environment>
    <environment exclude="Development">
        <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js"
                asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
                asp-fallback-test="window.jQuery"
                crossorigin="anonymous"
                integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk">
        </script>
        <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
                asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
                asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
                crossorigin="anonymous"
                integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
        </script>
        <script src="~/js/site.min.js" asp-append-version="true"></script>
    </environment>

    @RenderSection("Scripts", required: false)
</body>
</html>
  • Move the Pages/Shared/_LoginPartial.cshtml file to Views/Shared/_LoginPartial.cshtml

Identity is configured in Areas/Identity/IdentityHostingStartup.cs. For more information, see IHostingStartup.

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

In the Visual Studio Package Manager Console:

Add-Migration CreateIdentitySchema
Update-Database

The “CreateIdentitySchema” name parameter for the Add-Migration command is arbitrary. "CreateIdentitySchema" describes the migration.

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();
        app.UseMvcWithDefaultRoute();
    

UseHsts is recommended but not required. See HTTP Strict Transport Security Protocol for more information.

Scaffold identity into an MVC project with authorization

Run the Identity scaffolder:

  • From Solution Explorer, right-click on the project > Add > New Scaffolded Item.
  • From the left pane of the Add Scaffold dialog, select Identity > ADD.
  • In the ADD Identity dialog, select the options you want.
    • Select your existing layout page, or your layout file will be overwritten with incorrect markup. When an existing _Layout.cshtml file is selected, it is not overwritten.

For example
~/Pages/Shared/_Layout.cshtml for Razor Pages
~/Views/Shared/_Layout.cshtml for MVC projects

  • To use your existing data context, select at least one file to override. You must select at least one file to add your data context.
    • Select your data context class.
    • Select ADD.
  • To create a new user context and possibly create a custom user class for Identity:
    • Select the + button to create a new Data context class.
    • Select ADD.

Note: If you’re creating a new user context, you don’t have to select a file to override.

Delete the Pages/Shared folder and the files in that folder.




[ad_2]

source_link
https://www.asp.net