Skip to content

Commit

Permalink
Add user agent sniffing sample
Browse files Browse the repository at this point in the history
  • Loading branch information
Tratcher committed Oct 1, 2019
1 parent 786ccb7 commit 4462a0a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFrameworks>$(DefaultNetCoreTargetFramework)</TargetFrameworks>
Expand All @@ -14,6 +14,7 @@
<Reference Include="Microsoft.AspNetCore" />
<Reference Include="Microsoft.AspNetCore.Authentication.Cookies" />
<Reference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" />
<Reference Include="Microsoft.AspNetCore.CookiePolicy" />
<Reference Include="Microsoft.Extensions.FileProviders.Embedded" />
</ItemGroup>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,36 @@ public Startup(IConfiguration config, IWebHostEnvironment env)
public IConfiguration Configuration { get; set; }
public IWebHostEnvironment Environment { get; }

private void CheckSameSite(HttpContext httpContext, CookieOptions options)
{
if (options.SameSite > SameSiteMode.Unspecified)
{
var userAgent = httpContext.Request.Headers["User-Agent"];
// TODO: Use your User Agent library of choice here.
if (userAgent.Contains("CPU iPhone OS 12") // Also covers iPod touch
|| userAgent.Contains("iPad; CPU OS 12")
// Safari 12 and 13 are both broken on Mojave
|| userAgent.Contains("Macintosh; Intel Mac OS X 10_14"))
{
options.SameSite = SameSiteMode.Unspecified;
}
}
}

public void ConfigureServices(IServiceCollection services)
{
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

services.Configure<CookiePolicyOptions>(options =>
{
options.MinimumSameSitePolicy = SameSiteMode.Unspecified;
options.OnAppendCookie = cookieContext => CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
options.OnDeleteCookie = cookieContext => CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
});

services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
Expand Down Expand Up @@ -84,6 +106,7 @@ public void ConfigureServices(IServiceCollection services)
public void Configure(IApplicationBuilder app, IOptionsMonitor<OpenIdConnectOptions> optionsMonitor)
{
app.UseDeveloperExceptionPage();
app.UseCookiePolicy(); // Before UseAuthentication or anything else that writes cookies.
app.UseAuthentication();

app.Run(async context =>
Expand Down

0 comments on commit 4462a0a

Please sign in to comment.