Skip to content

Commit

Permalink
Update Introduction to Identity with ASP.NET Core 2 API's (dotnet#4236)
Browse files Browse the repository at this point in the history
* Changes to split out the ASP.NET Core 2 Identity cofig from ASP.NET Core 1.

* Fix problem with number rendering
Show differences between ASP.NET Core 1.x and 2.x config.

* Fix extra spaces
Add snippet_ prefix to regions

* Correct what UseAuthentication does.

* Update snippet regions with snippet_ prefix.
  • Loading branch information
scottsauber authored and scottaddie committed Sep 11, 2017
1 parent 7d0b33a commit c5649dc
Show file tree
Hide file tree
Showing 4 changed files with 139 additions and 19 deletions.
50 changes: 36 additions & 14 deletions aspnetcore/security/authentication/identity.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,19 +43,33 @@ In this topic, you'll learn how to use ASP.NET Core Identity to add functionalit
2. Configure Identity services and add middleware in `Startup`.

The Identity services are added to the application in the `ConfigureServices` method in the `Startup` class:

[!code-csharp[Main](identity/sample/src/ASPNET-IdentityDemo/Startup.cs?name=configureservices&highlight=7-9,13-34)]


# [ASP.NET Core 2.x](#tab/aspnetcore2x)

[!code-csharp[Main](identity/sample/src/ASPNETv2-IdentityDemo/Startup.cs?name=snippet_configureservices&highlight=7-9,11-28,30-39)]

These services are made available to the application through [dependency injection](xref:fundamentals/dependency-injection).

Identity is enabled for the application by calling `UseIdentity` in the `Configure` method. `UseIdentity` adds cookie-based authentication [middleware](xref:fundamentals/middleware) to the request pipeline.

[!code-csharp[Main](identity/sample/src/ASPNET-IdentityDemo/Startup.cs?name=configure&highlight=21)]


Identity is enabled for the application by calling `UseAuthentication` in the `Configure` method. `UseAuthentication` adds authentication [middleware](xref:fundamentals/middleware) to the request pipeline.

[!code-csharp[Main](identity/sample/src/ASPNETv2-IdentityDemo/Startup.cs?name=snippet_configure&highlight=17)]

# [ASP.NET Core 1.x](#tab/aspnetcore1x)

[!code-csharp[Main](identity/sample/src/ASPNET-IdentityDemo/Startup.cs?name=snippet_configureservices&highlight=7-9,13-34)]

These services are made available to the application through [dependency injection](xref:fundamentals/dependency-injection).

Identity is enabled for the application by calling `UseIdentity` in the `Configure` method. `UseIdentity` adds cookie-based authentication [middleware](xref:fundamentals/middleware) to the request pipeline.

[!code-csharp[Main](identity/sample/src/ASPNET-IdentityDemo/Startup.cs?name=snippet_configure&highlight=21)]

---
For more information about the application start up process, see [Application Startup](xref:fundamentals/startup).

3. Create a user.

Launch the application and then click on the **Register** link.

If this is the first time you're performing this action, you may be required to run migrations. The application prompts you to **Apply Migrations**:
Expand All @@ -71,7 +85,7 @@ In this topic, you'll learn how to use ASP.NET Core Identity to add functionalit

When the user clicks the **Register** link, the ``Register`` action is invoked on ``AccountController``. The ``Register`` action creates the user by calling `CreateAsync` on the `_userManager` object (provided to ``AccountController`` by dependency injection):

[!code-csharp[Main](identity/sample/src/ASPNET-IdentityDemo/Controllers/AccountController.cs?name=register&highlight=11)]
[!code-csharp[Main](identity/sample/src/ASPNET-IdentityDemo/Controllers/AccountController.cs?name=snippet_register&highlight=11)]

If the user was created successfully, the user is logged in by the call to ``_signInManager.SignInAsync``.

Expand All @@ -81,7 +95,7 @@ In this topic, you'll learn how to use ASP.NET Core Identity to add functionalit

Users can sign in by clicking the **Log in** link at the top of the site, or they may be navigated to the Login page if they attempt to access a part of the site that requires authorization. When the user submits the form on the Login page, the ``AccountController`` ``Login`` action is called.

[!code-csharp[Main](identity/sample/src/ASPNET-IdentityDemo/Controllers/AccountController.cs?name=login&highlight=13-14)]
[!code-csharp[Main](identity/sample/src/ASPNET-IdentityDemo/Controllers/AccountController.cs?name=snippet_login&highlight=13-14)]

The ``Login`` action calls ``PasswordSignInAsync`` on the ``_signInManager`` object (provided to ``AccountController`` by dependency injection).

Expand All @@ -91,15 +105,23 @@ In this topic, you'll learn how to use ASP.NET Core Identity to add functionalit

Clicking the **Log out** link calls the `LogOut` action.

[!code-csharp[Main](identity/sample/src/ASPNET-IdentityDemo/Controllers/AccountController.cs?name=logout&highlight=7)]
[!code-csharp[Main](identity/sample/src/ASPNET-IdentityDemo/Controllers/AccountController.cs?name=snippet_logout&highlight=7)]

The preceding code above calls the `_signInManager.SignOutAsync` method. The `SignOutAsync` method clears the user's claims stored in a cookie.

6. Configuration.

Identity has some default behaviors that you can override in your application's startup class. You do not need to configure ``IdentityOptions`` if you are using the default behaviors.

[!code-csharp[Main](identity/sample/src/ASPNET-IdentityDemo/Startup.cs?name=configureservices&highlight=13-34)]

# [ASP.NET Core 2.x](#tab/aspnetcore2x)

[!code-csharp[Main](identity/sample/src/ASPNETv2-IdentityDemo/Startup.cs?name=snippet_configureservices&highlight=7-9,11-28,30-39)]

# [ASP.NET Core 1.x](#tab/aspnetcore1x)

[!code-csharp[Main](identity/sample/src/ASPNET-IdentityDemo/Startup.cs?name=snippet_configureservices&highlight=13-34)]

---

For more information about how to configure Identity, see [Configure Identity](xref:security/authentication/identity-configuration).

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public IActionResult Login(string returnUrl = null)
ViewData["ReturnUrl"] = returnUrl;
return View();
}
#region login
#region snippet_login
//
// POST: /Account/Login
[HttpPost]
Expand Down Expand Up @@ -97,7 +97,7 @@ public IActionResult Register()
{
return View();
}
#region register
#region snippet_register
//
// POST: /Account/Register
[HttpPost]
Expand Down Expand Up @@ -129,7 +129,7 @@ public async Task<IActionResult> Register(RegisterViewModel model)
}
#endregion

#region logout
#region snippet_logout
//
// POST: /Account/LogOut
[HttpPost]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public Startup(IHostingEnvironment env)
public IConfigurationRoot Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
#region configureservices
#region snippet_configureservices
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
Expand Down Expand Up @@ -77,7 +77,7 @@ public void ConfigureServices(IServiceCollection services)
#endregion

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
#region configure
#region snippet_configure
public void Configure(IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using WebApplication5.Data;
using WebApplication5.Models;
using WebApplication5.Services;

namespace WebApplication5
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

#region snippet_configureservices
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();

services.Configure<IdentityOptions>(options =>
{
// Password settings
options.Password.RequireDigit = true;
options.Password.RequiredLength = 8;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = true;
options.Password.RequireLowercase = false;
options.Password.RequiredUniqueChars = 6;

// Lockout settings
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
options.Lockout.MaxFailedAccessAttempts = 10;
options.Lockout.AllowedForNewUsers = true;

// User settings
options.User.RequireUniqueEmail = true;
});

services.ConfigureApplicationCookie(options =>
{
// Cookie settings
options.Cookie.HttpOnly = true;
options.Cookie.Expiration = TimeSpan.FromDays(150);
options.LoginPath = "/Account/Login"; // If the LoginPath is not set here, ASP.NET Core will default to /Account/Login
options.LogoutPath = "/Account/Logout"; // If the LogoutPath is not set here, ASP.NET Core will default to /Account/Logout
options.AccessDeniedPath = "/Account/AccessDenied"; // If the AccessDeniedPath is not set here, ASP.NET Core will default to /Account/AccessDenied
options.SlidingExpiration = true;
});

// Add application services.
services.AddTransient<IEmailSender, EmailSender>();

services.AddMvc();
}
#endregion

#region snippet_configure
// 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();
app.UseBrowserLink();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}

app.UseStaticFiles();

app.UseAuthentication();

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
#endregion
}
}

0 comments on commit c5649dc

Please sign in to comment.