Skip to content
This repository was archived by the owner on Dec 13, 2018. It is now read-only.

[Fixes #1133] Limit the path on the nonce and correlation id cookies #1262

Merged
merged 1 commit into from
Jun 15, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -886,16 +886,21 @@ private void WriteNonceCookie(string nonce)
throw new ArgumentNullException(nameof(nonce));
}

var options = new CookieOptions
{
HttpOnly = true,
SameSite = Http.SameSiteMode.None,
Path = OriginalPathBase + Options.CallbackPath,
Secure = Request.IsHttps,
Expires = Clock.UtcNow.Add(Options.ProtocolValidator.NonceLifetime)
};

Options.ConfigureNonceCookie?.Invoke(Context, options);

Response.Cookies.Append(
OpenIdConnectDefaults.CookieNoncePrefix + Options.StringDataFormat.Protect(nonce),
NonceProperty,
new CookieOptions
{
HttpOnly = true,
SameSite = Http.SameSiteMode.None,
Secure = Request.IsHttps,
Expires = Clock.UtcNow.Add(Options.ProtocolValidator.NonceLifetime)
});
options);
}

/// <summary>
Expand Down Expand Up @@ -924,10 +929,13 @@ private string ReadNonceCookie(string nonce)
var cookieOptions = new CookieOptions
{
HttpOnly = true,
Path = OriginalPathBase + Options.CallbackPath,
SameSite = Http.SameSiteMode.None,
Secure = Request.IsHttps
};

Options.ConfigureNonceCookie?.Invoke(Context, cookieOptions);

Response.Cookies.Delete(nonceKey, cookieOptions);
return nonce;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -262,5 +262,11 @@ public override void Validate()
/// remote OpenID Connect provider as an authorization/logout request parameter.
/// </summary>
public bool DisableTelemetry { get; set; }

/// <summary>
/// Gets or sets an action that can override the nonce cookie options before the
/// cookie gets added to the response.
/// </summary>
public Action<HttpContext, CookieOptions> ConfigureNonceCookie { get; set; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ protected override async Task<AuthenticateResult> HandleRemoteAuthenticateAsync(
Secure = Request.IsHttps
};

Options.ConfigureStateCookie?.Invoke(Context, cookieOptions);

Response.Cookies.Delete(StateCookie, cookieOptions);

var accessToken = await ObtainAccessTokenAsync(requestToken, oauthVerifier);
Expand Down Expand Up @@ -159,6 +161,8 @@ protected override async Task HandleChallengeAsync(AuthenticationProperties prop
Expires = Clock.UtcNow.Add(Options.RemoteAuthenticationTimeout),
};

Options.ConfigureStateCookie?.Invoke(Context, cookieOptions);

Response.Cookies.Append(StateCookie, Options.StateDataFormat.Protect(requestToken), cookieOptions);

var redirectContext = new TwitterRedirectToAuthorizationEndpointContext(Context, Scheme, Options, properties, twitterAuthenticationEndpoint);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,12 @@ public TwitterOptions()
/// </summary>
public ISecureDataFormat<RequestToken> StateDataFormat { get; set; }

/// <summary>
/// Gets or sets an action that can override the state cookie options before the
/// cookie gets added to the response.
/// </summary>
public Action<HttpContext, CookieOptions> ConfigureStateCookie { get; set; }

/// <summary>
/// Gets or sets the <see cref="TwitterEvents"/> used to handle authentication events.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -205,9 +205,12 @@ protected virtual void GenerateCorrelationId(AuthenticationProperties properties
HttpOnly = true,
SameSite = SameSiteMode.None,
Secure = Request.IsHttps,
Path = OriginalPathBase + Options.CallbackPath,
Expires = Clock.UtcNow.Add(Options.RemoteAuthenticationTimeout),
};

Options.ConfigureCorrelationIdCookie?.Invoke(Context, cookieOptions);

properties.Items[CorrelationProperty] = correlationId;

var cookieName = CorrelationPrefix + Scheme.Name + "." + correlationId;
Expand Down Expand Up @@ -243,9 +246,13 @@ protected virtual bool ValidateCorrelationId(AuthenticationProperties properties
var cookieOptions = new CookieOptions
{
HttpOnly = true,
Path = OriginalPathBase + Options.CallbackPath,
SameSite = SameSiteMode.None,
Secure = Request.IsHttps
};

Options.ConfigureCorrelationIdCookie?.Invoke(Context, cookieOptions);

Response.Cookies.Delete(cookieName, cookieOptions);

if (!string.Equals(correlationCookie, CorrelationMarker, StringComparison.Ordinal))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,5 +87,11 @@ public override void Validate()
/// the size of the final authentication cookie.
/// </summary>
public bool SaveTokens { get; set; }

/// <summary>
/// Gets or sets an action that can override the correlation id cookie options before the
/// cookie gets added to the response.
/// </summary>
public Action<HttpContext, CookieOptions> ConfigureCorrelationIdCookie { get; set; }
}
}
65 changes: 65 additions & 0 deletions test/Microsoft.AspNetCore.Authentication.Test/OAuthTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
Expand Down Expand Up @@ -165,6 +166,70 @@ public async Task ThrowsIfSignInSchemeMissing()
Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
}

[Fact]
public async Task RedirectToIdentityProvider_SetsCorrelationIdCookiePath_ToCallBackPath()
{
var server = CreateServer(
app => { },
s => s.AddOAuthAuthentication(
"Weblie",
opt =>
{
opt.ClientId = "Test Id";
opt.ClientSecret = "secret";
opt.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
opt.AuthorizationEndpoint = "https://example.com/provider/login";
opt.TokenEndpoint = "https://example.com/provider/token";
opt.CallbackPath = "/oauth-callback";
}),
ctx =>
{
ctx.ChallengeAsync("Weblie").ConfigureAwait(false).GetAwaiter().GetResult();
return true;
});

var transaction = await server.SendAsync("https://www.example.com/challenge");
var res = transaction.Response;

Assert.Equal(HttpStatusCode.Redirect, res.StatusCode);
Assert.NotNull(res.Headers.Location);
var setCookie = Assert.Single(res.Headers, h => h.Key == "Set-Cookie");
var correlation = Assert.Single(setCookie.Value, v => v.StartsWith(".AspNetCore.Correlation."));
Assert.Contains("path=/oauth-callback", correlation);
}

[Fact]
public async Task RedirectToAuthorizeEndpoint_CorrelationIdCookieOptions_CanBeOverriden()
{
var server = CreateServer(
app => { },
s => s.AddOAuthAuthentication(
"Weblie",
opt =>
{
opt.ClientId = "Test Id";
opt.ClientSecret = "secret";
opt.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
opt.AuthorizationEndpoint = "https://example.com/provider/login";
opt.TokenEndpoint = "https://example.com/provider/token";
opt.CallbackPath = "/oauth-callback";
opt.ConfigureCorrelationIdCookie = (ctx, options) => options.Path = "/";
}),
ctx =>
{
ctx.ChallengeAsync("Weblie").ConfigureAwait(false).GetAwaiter().GetResult();
return true;
});

var transaction = await server.SendAsync("https://www.example.com/challenge");
var res = transaction.Response;

Assert.Equal(HttpStatusCode.Redirect, res.StatusCode);
Assert.NotNull(res.Headers.Location);
var setCookie = Assert.Single(res.Headers, h => h.Key == "Set-Cookie");
var correlation = Assert.Single(setCookie.Value, v => v.StartsWith(".AspNetCore.Correlation."));
Assert.Contains("path=/", correlation);
}

private static TestServer CreateServer(Action<IApplicationBuilder> configure, Action<IServiceCollection> configureServices, Func<HttpContext, bool> handler)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,108 @@ public async Task SignOutSettingMessage()
OpenIdConnectParameterNames.VersionTelemetry);
}

[Fact]
public async Task RedirectToIdentityProvider_SetsNonceCookiePath_ToCallBackPath()
{
var setting = new TestSettings(opt =>
{
opt.ClientId = "Test Id";
opt.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
opt.Configuration = new OpenIdConnectConfiguration
{
AuthorizationEndpoint = "https://example.com/provider/login"
};
});

var server = setting.CreateTestServer();

var transaction = await server.SendAsync(DefaultHost + TestServerBuilder.Challenge);
var res = transaction.Response;

Assert.Equal(HttpStatusCode.Redirect, res.StatusCode);
Assert.NotNull(res.Headers.Location);
var setCookie = Assert.Single(res.Headers, h => h.Key == "Set-Cookie");
var nonce = Assert.Single(setCookie.Value, v => v.StartsWith(OpenIdConnectDefaults.CookieNoncePrefix));
Assert.Contains("path=/signin-oidc", nonce);
}

[Fact]
public async Task RedirectToIdentityProvider_NonceCookieOptions_CanBeOverriden()
{
var setting = new TestSettings(opt =>
{
opt.ClientId = "Test Id";
opt.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
opt.Configuration = new OpenIdConnectConfiguration
{
AuthorizationEndpoint = "https://example.com/provider/login"
};
opt.ConfigureNonceCookie = (ctx, options) => options.Path = "/";
});

var server = setting.CreateTestServer();

var transaction = await server.SendAsync(DefaultHost + TestServerBuilder.Challenge);
var res = transaction.Response;

Assert.Equal(HttpStatusCode.Redirect, res.StatusCode);
Assert.NotNull(res.Headers.Location);
var setCookie = Assert.Single(res.Headers, h => h.Key == "Set-Cookie");
var nonce = Assert.Single(setCookie.Value, v => v.StartsWith(OpenIdConnectDefaults.CookieNoncePrefix));
Assert.Contains("path=/", nonce);
}

[Fact]
public async Task RedirectToIdentityProvider_SetsCorrelationIdCookiePath_ToCallBackPath()
{
var setting = new TestSettings(opt =>
{
opt.ClientId = "Test Id";
opt.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
opt.Configuration = new OpenIdConnectConfiguration
{
AuthorizationEndpoint = "https://example.com/provider/login"
};
});

var server = setting.CreateTestServer();

var transaction = await server.SendAsync(DefaultHost + TestServerBuilder.Challenge);
var res = transaction.Response;

Assert.Equal(HttpStatusCode.Redirect, res.StatusCode);
Assert.NotNull(res.Headers.Location);
var setCookie = Assert.Single(res.Headers, h => h.Key == "Set-Cookie");
var correlation = Assert.Single(setCookie.Value, v => v.StartsWith(".AspNetCore.Correlation."));
Assert.Contains("path=/signin-oidc", correlation);
}

[Fact]
public async Task RedirectToIdentityProvider_CorrelationIdCookieOptions_CanBeOverriden()
{
var setting = new TestSettings(opt =>
{
opt.ClientId = "Test Id";
opt.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
opt.Configuration = new OpenIdConnectConfiguration
{
AuthorizationEndpoint = "https://example.com/provider/login"
};
opt.ConfigureCorrelationIdCookie = (ctx, options) => options.Path = "/";
});

var server = setting.CreateTestServer();

var transaction = await server.SendAsync(DefaultHost + TestServerBuilder.Challenge);
var res = transaction.Response;

Assert.Equal(HttpStatusCode.Redirect, res.StatusCode);
Assert.NotNull(res.Headers.Location);
var setCookie = Assert.Single(res.Headers, h => h.Key == "Set-Cookie");
var correlation = Assert.Single(setCookie.Value, v => v.StartsWith(".AspNetCore.Correlation."));
Assert.Contains("path=/", correlation);
}

[Fact]
public async Task EndSessionRequestDoesNotIncludeTelemetryParametersWhenDisabled()
{
Expand Down Expand Up @@ -173,7 +275,8 @@ public async Task SignOutWith_Specific_RedirectUri_From_Authentication_Properite
[Fact]
public async Task SignOut_WithMissingConfig_Throws()
{
var setting = new TestSettings(opt => {
var setting = new TestSettings(opt =>
{
opt.ClientId = "Test Id";
opt.Configuration = new OpenIdConnectConfiguration();
});
Expand Down