Skip to content

Commit 365db75

Browse files
Copilotwadepickett
andauthored
Fix Cookie Authentication guide flow with complete Cookie Policy Middleware integration examples (#36101)
* Initial plan * Fix Cookie Authentication guide flow with complete Cookie Policy Middleware examples Co-authored-by: wadepickett <[email protected]> * Update aspnetcore/security/authentication/cookie.md Fixing Copilot mistake on ms.date. It claims it is 2024 currently. * Fix code snippet syntax according to copilot-instructions.md guidelines Co-authored-by: wadepickett <[email protected]> * Replace highlight syntax with named snippet markers using // &lt;snippet_name&gt; format Co-authored-by: wadepickett <[email protected]> * Restore line highlighting using correct triple-colon syntax with name and highlight attributes Co-authored-by: wadepickett <[email protected]> * Fix code snippet syntax by removing unsupported name attribute and using correct range/highlight syntax Co-authored-by: wadepickett <[email protected]> * Fix code snippet syntax to use id attribute instead of range according to copilot-instructions.md Co-authored-by: wadepickett <[email protected]> * Replace #region syntax with // &lt;snippet_name&gt; format in sample files according to copilot-instructions.md Co-authored-by: wadepickett <[email protected]> * Remove #region syntax and added comments from .cs files per copilot-instructions.md Co-authored-by: wadepickett <[email protected]> * Add comprehensive Copilot PR Success Checklist based on #35782 feedback Co-authored-by: wadepickett <[email protected]> * Remove Copilot PR Success Checklist from .github/copilot-instructions.md file per user request Co-authored-by: wadepickett <[email protected]> --------- Co-authored-by: copilot-swe-agent[bot] <[email protected]> Co-authored-by: wadepickett <[email protected]> Co-authored-by: Wade Pickett <[email protected]>
1 parent 387d709 commit 365db75

File tree

5 files changed

+177
-34
lines changed

5 files changed

+177
-34
lines changed

aspnetcore/security/authentication/cookie.md

Lines changed: 10 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
---
22
title: Use cookie authentication without ASP.NET Core Identity
3+
ai-usage: ai-assisted
34
author: wadepickett
45
description: Learn how to use cookie authentication without ASP.NET Core Identity.
56
monikerRange: '>= aspnetcore-3.1'
67
ms.author: wpickett
7-
ms.date: 1/1/2022
8+
ms.date: 09/12/2025
89
uid: security/authentication/cookie
910
---
1011
# Use cookie authentication without ASP.NET Core Identity
@@ -46,22 +47,15 @@ Configure <xref:Microsoft.AspNetCore.Authentication.Cookies.CookieAuthentication
4647
## Cookie Policy Middleware
4748

4849
The
49-
[Cookie Policy Middleware (GitHub Source)](https://github.com/dotnet/aspnetcore/blob/main/src/Security/CookiePolicy/src/CookiePolicyMiddleware.cs) <xref:Microsoft.AspNetCore.Builder.CookiePolicyAppBuilderExtensions.UseCookiePolicy%2A> enables cookie policy capabilities. Middleware is processed in the order it's added:
50-
51-
```csharp
52-
app.UseCookiePolicy(cookiePolicyOptions);
53-
```
50+
[Cookie Policy Middleware (GitHub Source)](https://github.com/dotnet/aspnetcore/blob/main/src/Security/CookiePolicy/src/CookiePolicyMiddleware.cs) <xref:Microsoft.AspNetCore.Builder.CookiePolicyAppBuilderExtensions.UseCookiePolicy%2A> enables cookie policy capabilities. Middleware is processed in the order it's added, and Cookie Policy Middleware should be added before cookie authentication middleware.
5451

5552
Use <xref:Microsoft.AspNetCore.Builder.CookiePolicyOptions> provided to the Cookie Policy Middleware to control global characteristics of cookie processing and hook into cookie processing handlers when cookies are appended or deleted.
5653

5754
The default <xref:Microsoft.AspNetCore.Builder.CookiePolicyOptions.MinimumSameSitePolicy> value is `SameSiteMode.Lax` to permit OAuth2 authentication. To strictly enforce a same-site policy of `SameSiteMode.Strict`, set the `MinimumSameSitePolicy`. Although this setting breaks OAuth2 and other cross-origin authentication schemes, it elevates the level of cookie security for other types of apps that don't rely on cross-origin request processing.
5855

59-
```csharp
60-
var cookiePolicyOptions = new CookiePolicyOptions
61-
{
62-
MinimumSameSitePolicy = SameSiteMode.Strict,
63-
};
64-
```
56+
The following example shows how to configure cookie authentication with Cookie Policy Middleware:
57+
58+
:::code language="csharp" source="cookie/snippets/6.0/Program.cs" id="snippet_policy" highlight="3-5,9":::
6559

6660
The Cookie Policy Middleware setting for `MinimumSameSitePolicy` can affect the setting of `Cookie.SameSite` in `CookieAuthenticationOptions` settings according to the matrix below.
6761

@@ -223,22 +217,15 @@ services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
223217

224218
## Cookie Policy Middleware
225219

226-
[Cookie Policy Middleware](xref:Microsoft.AspNetCore.CookiePolicy.CookiePolicyMiddleware) enables cookie policy capabilities. Adding the middleware to the app processing pipeline is order sensitive&mdash;it only affects downstream components registered in the pipeline.
227-
228-
```csharp
229-
app.UseCookiePolicy(cookiePolicyOptions);
230-
```
220+
[Cookie Policy Middleware](xref:Microsoft.AspNetCore.CookiePolicy.CookiePolicyMiddleware) enables cookie policy capabilities. Adding the middleware to the app processing pipeline is order sensitive&mdash;it only affects downstream components registered in the pipeline, and Cookie Policy Middleware should be added before cookie authentication middleware.
231221

232222
Use <xref:Microsoft.AspNetCore.Builder.CookiePolicyOptions> provided to the Cookie Policy Middleware to control global characteristics of cookie processing and hook into cookie processing handlers when cookies are appended or deleted.
233223

234224
The default <xref:Microsoft.AspNetCore.Builder.CookiePolicyOptions.MinimumSameSitePolicy> value is `SameSiteMode.Lax` to permit OAuth2 authentication. To strictly enforce a same-site policy of `SameSiteMode.Strict`, set the `MinimumSameSitePolicy`. Although this setting breaks OAuth2 and other cross-origin authentication schemes, it elevates the level of cookie security for other types of apps that don't rely on cross-origin request processing.
235225

236-
```csharp
237-
var cookiePolicyOptions = new CookiePolicyOptions
238-
{
239-
MinimumSameSitePolicy = SameSiteMode.Strict,
240-
};
241-
```
226+
The following example shows how to configure cookie authentication with Cookie Policy Middleware:
227+
228+
:::code language="csharp" source="cookie/snippets/3.x/Startup.cs" id="snippet_policy" highlight="3-5,9":::
242229

243230
The Cookie Policy Middleware setting for `MinimumSameSitePolicy` can affect the setting of `Cookie.SameSite` in `CookieAuthenticationOptions` settings according to the matrix below.
244231

aspnetcore/security/authentication/cookie/samples/3.x/CookieSample/Startup.cs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,15 @@ public void ConfigureServices(IServiceCollection services)
1616
options.Conventions.AuthorizePage("/Contact");
1717
});
1818

19-
#region snippet1
19+
// <snippet1>
2020
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
2121
.AddCookie();
22-
#endregion
22+
// </snippet1>
2323

2424
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
2525
}
2626

27+
// <snippet_policy>
2728
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
2829
{
2930
if (env.IsDevelopment())
@@ -40,7 +41,13 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
4041
app.UseStaticFiles();
4142
app.UseRouting();
4243

43-
#region snippet2
44+
var cookiePolicyOptions = new CookiePolicyOptions
45+
{
46+
MinimumSameSitePolicy = SameSiteMode.Strict,
47+
};
48+
49+
app.UseCookiePolicy(cookiePolicyOptions);
50+
4451
app.UseAuthentication();
4552
app.UseAuthorization();
4653

@@ -49,7 +56,7 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
4956
endpoints.MapControllers();
5057
endpoints.MapRazorPages();
5158
});
52-
#endregion
5359
}
60+
// </snippet_policy>
5461
}
5562
}

aspnetcore/security/authentication/cookie/samples/6.x/CookieSample/Program.cs

Lines changed: 52 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
#define FIRST // FIRST SECOND CC
1+
#define FIRST // FIRST SECOND POLICY CC
22
#if NEVER
33
#elif FIRST
4-
#region snippet1
4+
// <snippet1>
55
using Microsoft.AspNetCore.Authentication.Cookies;
66

77
var builder = WebApplication.CreateBuilder(args);
@@ -32,9 +32,9 @@
3232
app.MapDefaultControllerRoute();
3333

3434
app.Run();
35-
#endregion
35+
// </snippet1>
3636
#elif SECOND
37-
#region snippet2
37+
// <snippet2>
3838
using Microsoft.AspNetCore.Authentication.Cookies;
3939

4040
var builder = WebApplication.CreateBuilder(args);
@@ -70,9 +70,54 @@
7070
app.MapDefaultControllerRoute();
7171

7272
app.Run();
73-
#endregion
73+
// </snippet2>
74+
#elif POLICY
75+
// <snippet_policy>
76+
using Microsoft.AspNetCore.Authentication.Cookies;
77+
78+
var builder = WebApplication.CreateBuilder(args);
79+
80+
builder.Services.AddRazorPages();
81+
builder.Services.AddControllersWithViews();
82+
83+
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
84+
.AddCookie(options =>
85+
{
86+
options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
87+
options.SlidingExpiration = true;
88+
options.AccessDeniedPath = "/Forbidden/";
89+
});
90+
91+
builder.Services.AddHttpContextAccessor();
92+
93+
var app = builder.Build();
94+
95+
if (!app.Environment.IsDevelopment())
96+
{
97+
app.UseExceptionHandler("/Error");
98+
app.UseHsts();
99+
}
100+
101+
app.UseHttpsRedirection();
102+
app.UseStaticFiles();
103+
104+
var cookiePolicyOptions = new CookiePolicyOptions
105+
{
106+
MinimumSameSitePolicy = SameSiteMode.Strict,
107+
};
108+
109+
app.UseCookiePolicy(cookiePolicyOptions);
110+
111+
app.UseAuthentication();
112+
app.UseAuthorization();
113+
114+
app.MapRazorPages();
115+
app.MapDefaultControllerRoute();
116+
117+
app.Run();
118+
// </snippet_policy>
74119
#elif CC
75-
#region snippet_cc
120+
// <snippet_cc>
76121
using Microsoft.AspNetCore.Authentication.Cookies;
77122

78123
var builder = WebApplication.CreateBuilder(args);
@@ -106,5 +151,5 @@
106151
app.MapDefaultControllerRoute();
107152

108153
app.Run();
109-
#endregion
154+
// </snippet_cc>
110155
#endif
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
using Microsoft.AspNetCore.Authentication.Cookies;
2+
using Microsoft.AspNetCore.Builder;
3+
using Microsoft.AspNetCore.Hosting;
4+
using Microsoft.AspNetCore.Http;
5+
using Microsoft.Extensions.DependencyInjection;
6+
using Microsoft.Extensions.Hosting;
7+
8+
namespace CookieSample
9+
{
10+
public class Startup
11+
{
12+
public void ConfigureServices(IServiceCollection services)
13+
{
14+
services.AddRazorPages(options =>
15+
{
16+
options.Conventions.AuthorizePage("/Contact");
17+
});
18+
19+
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
20+
.AddCookie();
21+
22+
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
23+
}
24+
25+
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
26+
{
27+
if (env.IsDevelopment())
28+
{
29+
app.UseDeveloperExceptionPage();
30+
}
31+
else
32+
{
33+
app.UseExceptionHandler("/Error");
34+
app.UseHsts();
35+
}
36+
37+
app.UseHttpsRedirection();
38+
app.UseStaticFiles();
39+
app.UseRouting();
40+
41+
// <snippet_policy>
42+
var cookiePolicyOptions = new CookiePolicyOptions
43+
{
44+
MinimumSameSitePolicy = SameSiteMode.Strict,
45+
};
46+
47+
app.UseCookiePolicy(cookiePolicyOptions);
48+
// </snippet_policy>
49+
50+
app.UseAuthentication();
51+
app.UseAuthorization();
52+
53+
app.UseEndpoints(endpoints =>
54+
{
55+
endpoints.MapControllers();
56+
endpoints.MapRazorPages();
57+
});
58+
}
59+
}
60+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
using Microsoft.AspNetCore.Authentication.Cookies;
2+
3+
var builder = WebApplication.CreateBuilder(args);
4+
5+
builder.Services.AddRazorPages();
6+
builder.Services.AddControllersWithViews();
7+
8+
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
9+
.AddCookie(options =>
10+
{
11+
options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
12+
options.SlidingExpiration = true;
13+
options.AccessDeniedPath = "/Forbidden/";
14+
});
15+
16+
builder.Services.AddHttpContextAccessor();
17+
18+
var app = builder.Build();
19+
20+
if (!app.Environment.IsDevelopment())
21+
{
22+
app.UseExceptionHandler("/Error");
23+
app.UseHsts();
24+
}
25+
26+
app.UseHttpsRedirection();
27+
app.UseStaticFiles();
28+
29+
// <snippet_policy>
30+
var cookiePolicyOptions = new CookiePolicyOptions
31+
{
32+
MinimumSameSitePolicy = SameSiteMode.Strict,
33+
};
34+
35+
app.UseCookiePolicy(cookiePolicyOptions);
36+
// </snippet_policy>
37+
38+
app.UseAuthentication();
39+
app.UseAuthorization();
40+
41+
app.MapRazorPages();
42+
app.MapDefaultControllerRoute();
43+
44+
app.Run();

0 commit comments

Comments
 (0)