Skip to content

Commit c5649dc

Browse files
scottsauberscottaddie
authored andcommitted
Update Introduction to Identity with ASP.NET Core 2 API's (#4236)
* 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.
1 parent 7d0b33a commit c5649dc

File tree

4 files changed

+139
-19
lines changed

4 files changed

+139
-19
lines changed

aspnetcore/security/authentication/identity.md

Lines changed: 36 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -43,19 +43,33 @@ In this topic, you'll learn how to use ASP.NET Core Identity to add functionalit
4343
2. Configure Identity services and add middleware in `Startup`.
4444

4545
The Identity services are added to the application in the `ConfigureServices` method in the `Startup` class:
46-
47-
[!code-csharp[Main](identity/sample/src/ASPNET-IdentityDemo/Startup.cs?name=configureservices&highlight=7-9,13-34)]
48-
46+
47+
# [ASP.NET Core 2.x](#tab/aspnetcore2x)
48+
49+
[!code-csharp[Main](identity/sample/src/ASPNETv2-IdentityDemo/Startup.cs?name=snippet_configureservices&highlight=7-9,11-28,30-39)]
50+
4951
These services are made available to the application through [dependency injection](xref:fundamentals/dependency-injection).
50-
51-
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.
52-
53-
[!code-csharp[Main](identity/sample/src/ASPNET-IdentityDemo/Startup.cs?name=configure&highlight=21)]
54-
52+
53+
Identity is enabled for the application by calling `UseAuthentication` in the `Configure` method. `UseAuthentication` adds authentication [middleware](xref:fundamentals/middleware) to the request pipeline.
54+
55+
[!code-csharp[Main](identity/sample/src/ASPNETv2-IdentityDemo/Startup.cs?name=snippet_configure&highlight=17)]
56+
57+
# [ASP.NET Core 1.x](#tab/aspnetcore1x)
58+
59+
[!code-csharp[Main](identity/sample/src/ASPNET-IdentityDemo/Startup.cs?name=snippet_configureservices&highlight=7-9,13-34)]
60+
61+
These services are made available to the application through [dependency injection](xref:fundamentals/dependency-injection).
62+
63+
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.
64+
65+
[!code-csharp[Main](identity/sample/src/ASPNET-IdentityDemo/Startup.cs?name=snippet_configure&highlight=21)]
66+
67+
---
68+
5569
For more information about the application start up process, see [Application Startup](xref:fundamentals/startup).
5670

5771
3. Create a user.
58-
72+
5973
Launch the application and then click on the **Register** link.
6074

6175
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**:
@@ -71,7 +85,7 @@ In this topic, you'll learn how to use ASP.NET Core Identity to add functionalit
7185

7286
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):
7387

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

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

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

8296
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.
8397

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

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

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

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

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

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

98112
6. Configuration.
99113

100114
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.
101-
102-
[!code-csharp[Main](identity/sample/src/ASPNET-IdentityDemo/Startup.cs?name=configureservices&highlight=13-34)]
115+
116+
# [ASP.NET Core 2.x](#tab/aspnetcore2x)
117+
118+
[!code-csharp[Main](identity/sample/src/ASPNETv2-IdentityDemo/Startup.cs?name=snippet_configureservices&highlight=7-9,11-28,30-39)]
119+
120+
# [ASP.NET Core 1.x](#tab/aspnetcore1x)
121+
122+
[!code-csharp[Main](identity/sample/src/ASPNET-IdentityDemo/Startup.cs?name=snippet_configureservices&highlight=13-34)]
123+
124+
---
103125

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

aspnetcore/security/authentication/identity/sample/src/ASPNET-IdentityDemo/Controllers/AccountController.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ public IActionResult Login(string returnUrl = null)
4848
ViewData["ReturnUrl"] = returnUrl;
4949
return View();
5050
}
51-
#region login
51+
#region snippet_login
5252
//
5353
// POST: /Account/Login
5454
[HttpPost]
@@ -97,7 +97,7 @@ public IActionResult Register()
9797
{
9898
return View();
9999
}
100-
#region register
100+
#region snippet_register
101101
//
102102
// POST: /Account/Register
103103
[HttpPost]
@@ -129,7 +129,7 @@ public async Task<IActionResult> Register(RegisterViewModel model)
129129
}
130130
#endregion
131131

132-
#region logout
132+
#region snippet_logout
133133
//
134134
// POST: /Account/LogOut
135135
[HttpPost]

aspnetcore/security/authentication/identity/sample/src/ASPNET-IdentityDemo/Startup.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ public Startup(IHostingEnvironment env)
3434
public IConfigurationRoot Configuration { get; }
3535

3636
// This method gets called by the runtime. Use this method to add services to the container.
37-
#region configureservices
37+
#region snippet_configureservices
3838
public void ConfigureServices(IServiceCollection services)
3939
{
4040
// Add framework services.
@@ -77,7 +77,7 @@ public void ConfigureServices(IServiceCollection services)
7777
#endregion
7878

7979
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
80-
#region configure
80+
#region snippet_configure
8181
public void Configure(IApplicationBuilder app,
8282
IHostingEnvironment env,
8383
ILoggerFactory loggerFactory)
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
using Microsoft.AspNetCore.Builder;
2+
using Microsoft.AspNetCore.Identity;
3+
using Microsoft.EntityFrameworkCore;
4+
using Microsoft.AspNetCore.Hosting;
5+
using Microsoft.Extensions.Configuration;
6+
using Microsoft.Extensions.DependencyInjection;
7+
using WebApplication5.Data;
8+
using WebApplication5.Models;
9+
using WebApplication5.Services;
10+
11+
namespace WebApplication5
12+
{
13+
public class Startup
14+
{
15+
public Startup(IConfiguration configuration)
16+
{
17+
Configuration = configuration;
18+
}
19+
20+
public IConfiguration Configuration { get; }
21+
22+
#region snippet_configureservices
23+
// This method gets called by the runtime. Use this method to add services to the container.
24+
public void ConfigureServices(IServiceCollection services)
25+
{
26+
services.AddDbContext<ApplicationDbContext>(options =>
27+
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
28+
29+
services.AddIdentity<ApplicationUser, IdentityRole>()
30+
.AddEntityFrameworkStores<ApplicationDbContext>()
31+
.AddDefaultTokenProviders();
32+
33+
services.Configure<IdentityOptions>(options =>
34+
{
35+
// Password settings
36+
options.Password.RequireDigit = true;
37+
options.Password.RequiredLength = 8;
38+
options.Password.RequireNonAlphanumeric = false;
39+
options.Password.RequireUppercase = true;
40+
options.Password.RequireLowercase = false;
41+
options.Password.RequiredUniqueChars = 6;
42+
43+
// Lockout settings
44+
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
45+
options.Lockout.MaxFailedAccessAttempts = 10;
46+
options.Lockout.AllowedForNewUsers = true;
47+
48+
// User settings
49+
options.User.RequireUniqueEmail = true;
50+
});
51+
52+
services.ConfigureApplicationCookie(options =>
53+
{
54+
// Cookie settings
55+
options.Cookie.HttpOnly = true;
56+
options.Cookie.Expiration = TimeSpan.FromDays(150);
57+
options.LoginPath = "/Account/Login"; // If the LoginPath is not set here, ASP.NET Core will default to /Account/Login
58+
options.LogoutPath = "/Account/Logout"; // If the LogoutPath is not set here, ASP.NET Core will default to /Account/Logout
59+
options.AccessDeniedPath = "/Account/AccessDenied"; // If the AccessDeniedPath is not set here, ASP.NET Core will default to /Account/AccessDenied
60+
options.SlidingExpiration = true;
61+
});
62+
63+
// Add application services.
64+
services.AddTransient<IEmailSender, EmailSender>();
65+
66+
services.AddMvc();
67+
}
68+
#endregion
69+
70+
#region snippet_configure
71+
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
72+
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
73+
{
74+
if (env.IsDevelopment())
75+
{
76+
app.UseDeveloperExceptionPage();
77+
app.UseBrowserLink();
78+
app.UseDatabaseErrorPage();
79+
}
80+
else
81+
{
82+
app.UseExceptionHandler("/Home/Error");
83+
}
84+
85+
app.UseStaticFiles();
86+
87+
app.UseAuthentication();
88+
89+
app.UseMvc(routes =>
90+
{
91+
routes.MapRoute(
92+
name: "default",
93+
template: "{controller=Home}/{action=Index}/{id?}");
94+
});
95+
}
96+
#endregion
97+
}
98+
}

0 commit comments

Comments
 (0)