Fix stuff

This commit is contained in:
Hao Kung 2015-09-21 14:56:05 -07:00
parent 081577e4f4
commit 59ccbdd8ca
68 changed files with 200 additions and 417 deletions

View File

@ -1,8 +1,8 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<configuration> <configuration>
<packageSources> <packageSources>
<add key="AspNetVNext" value="https://www.myget.org/F/aspnetcidev/api/v3/index.json" /> <add key="AspNetVNext" value="https://www.myget.org/F/aspnetcidev/api/v3/index.json" />
<add key="NuGet" value="https://api.nuget.org/v3/index.json" /> <add key="NuGet" value="https://api.nuget.org/v3/index.json" />
<add key="AzureAD" value="http://www.myget.org/F/azureadwebstacknightly"/> <add key="AzureAD" value="http://www.myget.org/F/azureadwebstacknightly" />
</packageSources> </packageSources>
</configuration> </configuration>

View File

@ -40,7 +40,7 @@ Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNet.Authentica
EndProject EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNet.Authentication.Test", "test\Microsoft.AspNet.Authentication.Test\Microsoft.AspNet.Authentication.Test.xproj", "{8DA26CD1-1302-4CFD-9270-9FA1B7C6138B}" Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNet.Authentication.Test", "test\Microsoft.AspNet.Authentication.Test\Microsoft.AspNet.Authentication.Test.xproj", "{8DA26CD1-1302-4CFD-9270-9FA1B7C6138B}"
EndProject EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNet.Authentication.JwtBearer", "src\Microsoft.AspNet.Authentication.JwtBearer\Microsoft.AspNet.Authentication.JwtBearer.xproj", "{2755BFE5-7421-4A31-A644-F817DF5CAA98}" Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNet.Authentication.OpenIdConnectBearer", "src\Microsoft.AspNet.Authentication.JwtBearer\Microsoft.AspNet.Authentication.OpenIdConnectBearer.xproj", "{2755BFE5-7421-4A31-A644-F817DF5CAA98}"
EndProject EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNet.Authorization.Test", "test\Microsoft.AspNet.Authorization.Test\Microsoft.AspNet.Authorization.Test.xproj", "{7AF5AD96-EB6E-4D0E-8ABE-C0B543C0F4C2}" Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNet.Authorization.Test", "test\Microsoft.AspNet.Authorization.Test\Microsoft.AspNet.Authorization.Test.xproj", "{7AF5AD96-EB6E-4D0E-8ABE-C0B543C0F4C2}"
EndProject EndProject

View File

@ -6,7 +6,7 @@ using Microsoft.Framework.Caching.Memory;
namespace CookieSessionSample namespace CookieSessionSample
{ {
public class MemoryCacheSessionStore : IAuthenticationSessionStore public class MemoryCacheSessionStore : ITicketStore
{ {
private const string KeyPrefix = "AuthSessionStore-"; private const string KeyPrefix = "AuthSessionStore-";
private IMemoryCache _cache; private IMemoryCache _cache;

View File

@ -130,7 +130,7 @@ namespace CookieSample
// Retrieving user information is unique to each provider. // Retrieving user information is unique to each provider.
Events = new OAuthEvents Events = new OAuthEvents
{ {
OnAuthenticated = async context => OnCreatingTicket = async context =>
{ {
// Get the GitHub user // Get the GitHub user
var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint); var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);

View File

@ -225,7 +225,7 @@ namespace Microsoft.AspNet.Authentication.Cookies
{ {
var cookieOptions = BuildCookieOptions(); var cookieOptions = BuildCookieOptions();
var signInContext = new CookieResponseSignInContext( var signInContext = new CookieSigningInContext(
Context, Context,
Options, Options,
Options.AuthenticationScheme, Options.AuthenticationScheme,
@ -249,7 +249,7 @@ namespace Microsoft.AspNet.Authentication.Cookies
signInContext.Properties.ExpiresUtc = issuedUtc.Add(Options.ExpireTimeSpan); signInContext.Properties.ExpiresUtc = issuedUtc.Add(Options.ExpireTimeSpan);
} }
await Options.Events.ResponseSignIn(signInContext); await Options.Events.SigningIn(signInContext);
if (signInContext.Properties.IsPersistent) if (signInContext.Properties.IsPersistent)
{ {
@ -279,14 +279,14 @@ namespace Microsoft.AspNet.Authentication.Cookies
cookieValue, cookieValue,
signInContext.CookieOptions); signInContext.CookieOptions);
var signedInContext = new CookieResponseSignedInContext( var signedInContext = new CookieSignedInContext(
Context, Context,
Options, Options,
Options.AuthenticationScheme, Options.AuthenticationScheme,
signInContext.Principal, signInContext.Principal,
signInContext.Properties); signInContext.Properties);
await Options.Events.ResponseSignedIn(signedInContext); await Options.Events.SignedIn(signedInContext);
var shouldLoginRedirect = Options.LoginPath.HasValue && OriginalPath == Options.LoginPath; var shouldLoginRedirect = Options.LoginPath.HasValue && OriginalPath == Options.LoginPath;
ApplyHeaders(shouldLoginRedirect); ApplyHeaders(shouldLoginRedirect);
@ -314,12 +314,12 @@ namespace Microsoft.AspNet.Authentication.Cookies
await Options.SessionStore.RemoveAsync(_sessionKey); await Options.SessionStore.RemoveAsync(_sessionKey);
} }
var context = new CookieResponseSignOutContext( var context = new CookieSigningOutContext(
Context, Context,
Options, Options,
cookieOptions); cookieOptions);
await Options.Events.ResponseSignOut(context); await Options.Events.SigningOut(context);
Options.CookieManager.DeleteCookie( Options.CookieManager.DeleteCookie(
Context, Context,

View File

@ -146,7 +146,7 @@ namespace Microsoft.AspNet.Authentication.Cookies
/// An optional container in which to store the identity across requests. When used, only a session identifier is sent /// An optional container in which to store the identity across requests. When used, only a session identifier is sent
/// to the client. This can be used to mitigate potential problems with very large identities. /// to the client. This can be used to mitigate potential problems with very large identities.
/// </summary> /// </summary>
public IAuthenticationSessionStore SessionStore { get; set; } public ITicketStore SessionStore { get; set; }
CookieAuthenticationOptions IOptions<CookieAuthenticationOptions>.Value CookieAuthenticationOptions IOptions<CookieAuthenticationOptions>.Value
{ {

View File

@ -21,17 +21,17 @@ namespace Microsoft.AspNet.Authentication.Cookies
/// <summary> /// <summary>
/// A delegate assigned to this property will be invoked when the related method is called /// A delegate assigned to this property will be invoked when the related method is called
/// </summary> /// </summary>
public Func<CookieResponseSignInContext, Task> OnResponseSignIn { get; set; } = context => Task.FromResult(0); public Func<CookieSigningInContext, Task> OnSigningIn { get; set; } = context => Task.FromResult(0);
/// <summary> /// <summary>
/// A delegate assigned to this property will be invoked when the related method is called /// A delegate assigned to this property will be invoked when the related method is called
/// </summary> /// </summary>
public Func<CookieResponseSignedInContext, Task> OnResponseSignedIn { get; set; } = context => Task.FromResult(0); public Func<CookieSignedInContext, Task> OnSignedIn { get; set; } = context => Task.FromResult(0);
/// <summary> /// <summary>
/// A delegate assigned to this property will be invoked when the related method is called /// A delegate assigned to this property will be invoked when the related method is called
/// </summary> /// </summary>
public Func<CookieResponseSignOutContext, Task> OnResponseSignOut { get; set; } = context => Task.FromResult(0); public Func<CookieSigningOutContext, Task> OnSigningOut { get; set; } = context => Task.FromResult(0);
/// <summary> /// <summary>
/// A delegate assigned to this property will be invoked when the related method is called /// A delegate assigned to this property will be invoked when the related method is called
@ -58,19 +58,19 @@ namespace Microsoft.AspNet.Authentication.Cookies
/// Implements the interface method by invoking the related delegate method /// Implements the interface method by invoking the related delegate method
/// </summary> /// </summary>
/// <param name="context"></param> /// <param name="context"></param>
public virtual Task ResponseSignIn(CookieResponseSignInContext context) => OnResponseSignIn(context); public virtual Task SigningIn(CookieSigningInContext context) => OnSigningIn(context);
/// <summary> /// <summary>
/// Implements the interface method by invoking the related delegate method /// Implements the interface method by invoking the related delegate method
/// </summary> /// </summary>
/// <param name="context"></param> /// <param name="context"></param>
public virtual Task ResponseSignedIn(CookieResponseSignedInContext context) => OnResponseSignedIn(context); public virtual Task SignedIn(CookieSignedInContext context) => OnSignedIn(context);
/// <summary> /// <summary>
/// Implements the interface method by invoking the related delegate method /// Implements the interface method by invoking the related delegate method
/// </summary> /// </summary>
/// <param name="context"></param> /// <param name="context"></param>
public virtual Task ResponseSignOut(CookieResponseSignOutContext context) => OnResponseSignOut(context); public virtual Task SigningOut(CookieSigningOutContext context) => OnSigningOut(context);
/// <summary> /// <summary>
/// Implements the interface method by invoking the related delegate method /// Implements the interface method by invoking the related delegate method

View File

@ -8,9 +8,9 @@ using Microsoft.AspNet.Http.Authentication;
namespace Microsoft.AspNet.Authentication.Cookies namespace Microsoft.AspNet.Authentication.Cookies
{ {
/// <summary> /// <summary>
/// Context object passed to the ICookieAuthenticationEvents method ResponseSignedIn. /// Context object passed to the ICookieAuthenticationEvents method SignedIn.
/// </summary> /// </summary>
public class CookieResponseSignedInContext : BaseContext<CookieAuthenticationOptions> public class CookieSignedInContext : BaseContext<CookieAuthenticationOptions>
{ {
/// <summary> /// <summary>
/// Creates a new instance of the context object. /// Creates a new instance of the context object.
@ -20,7 +20,7 @@ namespace Microsoft.AspNet.Authentication.Cookies
/// <param name="authenticationScheme">Initializes AuthenticationScheme property</param> /// <param name="authenticationScheme">Initializes AuthenticationScheme property</param>
/// <param name="principal">Initializes Principal property</param> /// <param name="principal">Initializes Principal property</param>
/// <param name="properties">Initializes Properties property</param> /// <param name="properties">Initializes Properties property</param>
public CookieResponseSignedInContext( public CookieSignedInContext(
HttpContext context, HttpContext context,
CookieAuthenticationOptions options, CookieAuthenticationOptions options,
string authenticationScheme, string authenticationScheme,

View File

@ -8,9 +8,9 @@ using Microsoft.AspNet.Http.Authentication;
namespace Microsoft.AspNet.Authentication.Cookies namespace Microsoft.AspNet.Authentication.Cookies
{ {
/// <summary> /// <summary>
/// Context object passed to the ICookieAuthenticationProvider method ResponseSignIn. /// Context object passed to the ICookieAuthenticationEvents method ResponseSignIn.
/// </summary> /// </summary>
public class CookieResponseSignInContext : BaseContext<CookieAuthenticationOptions> public class CookieSigningInContext : BaseContext<CookieAuthenticationOptions>
{ {
/// <summary> /// <summary>
/// Creates a new instance of the context object. /// Creates a new instance of the context object.
@ -21,7 +21,7 @@ namespace Microsoft.AspNet.Authentication.Cookies
/// <param name="principal">Initializes Principal property</param> /// <param name="principal">Initializes Principal property</param>
/// <param name="properties">Initializes Extra property</param> /// <param name="properties">Initializes Extra property</param>
/// <param name="cookieOptions">Initializes options for the authentication cookie.</param> /// <param name="cookieOptions">Initializes options for the authentication cookie.</param>
public CookieResponseSignInContext( public CookieSigningInContext(
HttpContext context, HttpContext context,
CookieAuthenticationOptions options, CookieAuthenticationOptions options,
string authenticationScheme, string authenticationScheme,

View File

@ -6,9 +6,9 @@ using Microsoft.AspNet.Http;
namespace Microsoft.AspNet.Authentication.Cookies namespace Microsoft.AspNet.Authentication.Cookies
{ {
/// <summary> /// <summary>
/// Context object passed to the ICookieAuthenticationProvider method ResponseSignOut /// Context object passed to the ICookieAuthenticationEvents method SigningOut
/// </summary> /// </summary>
public class CookieResponseSignOutContext : BaseContext<CookieAuthenticationOptions> public class CookieSigningOutContext : BaseContext<CookieAuthenticationOptions>
{ {
/// <summary> /// <summary>
/// ///
@ -16,7 +16,7 @@ namespace Microsoft.AspNet.Authentication.Cookies
/// <param name="context"></param> /// <param name="context"></param>
/// <param name="options"></param> /// <param name="options"></param>
/// <param name="cookieOptions"></param> /// <param name="cookieOptions"></param>
public CookieResponseSignOutContext(HttpContext context, CookieAuthenticationOptions options, CookieOptions cookieOptions) public CookieSigningOutContext(HttpContext context, CookieAuthenticationOptions options, CookieOptions cookieOptions)
: base(context, options) : base(context, options)
{ {
CookieOptions = cookieOptions; CookieOptions = cookieOptions;

View File

@ -23,13 +23,13 @@ namespace Microsoft.AspNet.Authentication.Cookies
/// implementing this method the claims and extra information that go into the ticket may be altered. /// implementing this method the claims and extra information that go into the ticket may be altered.
/// </summary> /// </summary>
/// <param name="context">Contains information about the login session as well as the user <see cref="System.Security.Claims.ClaimsIdentity"/>.</param> /// <param name="context">Contains information about the login session as well as the user <see cref="System.Security.Claims.ClaimsIdentity"/>.</param>
Task ResponseSignIn(CookieResponseSignInContext context); Task SigningIn(CookieSigningInContext context);
/// <summary> /// <summary>
/// Called when an endpoint has provided sign in information after it is converted into a cookie. /// Called when an endpoint has provided sign in information after it is converted into a cookie.
/// </summary> /// </summary>
/// <param name="context">Contains information about the login session as well as the user <see cref="System.Security.Claims.ClaimsIdentity"/>.</param> /// <param name="context">Contains information about the login session as well as the user <see cref="System.Security.Claims.ClaimsIdentity"/>.</param>
Task ResponseSignedIn(CookieResponseSignedInContext context); Task SignedIn(CookieSignedInContext context);
/// <summary> /// <summary>
/// Called when a Challenge, SignIn, or SignOut causes a redirect in the cookie middleware /// Called when a Challenge, SignIn, or SignOut causes a redirect in the cookie middleware
@ -41,7 +41,7 @@ namespace Microsoft.AspNet.Authentication.Cookies
/// Called during the sign-out flow to augment the cookie cleanup process. /// Called during the sign-out flow to augment the cookie cleanup process.
/// </summary> /// </summary>
/// <param name="context">Contains information about the login session as well as information about the authentication cookie.</param> /// <param name="context">Contains information about the login session as well as information about the authentication cookie.</param>
Task ResponseSignOut(CookieResponseSignOutContext context); Task SigningOut(CookieSigningOutContext context);
/// <summary> /// <summary>
/// Called when an exception occurs during request or response processing. /// Called when an exception occurs during request or response processing.

View File

@ -9,7 +9,7 @@ namespace Microsoft.AspNet.Authentication.Cookies
/// while only sending a simple identifier key to the client. This is most commonly used to mitigate /// while only sending a simple identifier key to the client. This is most commonly used to mitigate
/// issues with serializing large identities into cookies. /// issues with serializing large identities into cookies.
/// </summary> /// </summary>
public interface IAuthenticationSessionStore public interface ITicketStore
{ {
/// <summary> /// <summary>
/// Store the identity ticket and return the associated key. /// Store the identity ticket and return the associated key.

View File

@ -62,7 +62,7 @@ namespace Microsoft.AspNet.Authentication.Facebook
var payload = JObject.Parse(await response.Content.ReadAsStringAsync()); var payload = JObject.Parse(await response.Content.ReadAsStringAsync());
var context = new OAuthAuthenticatedContext(Context, Options, Backchannel, tokens, payload) var context = new OAuthCreatingTicketContext(Context, Options, Backchannel, tokens, payload)
{ {
Properties = properties, Properties = properties,
Principal = new ClaimsPrincipal(identity) Principal = new ClaimsPrincipal(identity)
@ -104,7 +104,7 @@ namespace Microsoft.AspNet.Authentication.Facebook
identity.AddClaim(new Claim("urn:facebook:link", link, ClaimValueTypes.String, Options.ClaimsIssuer)); identity.AddClaim(new Claim("urn:facebook:link", link, ClaimValueTypes.String, Options.ClaimsIssuer));
} }
await Options.Events.Authenticated(context); await Options.Events.CreatingTicket(context);
return new AuthenticationTicket(context.Principal, context.Properties, context.Options.AuthenticationScheme); return new AuthenticationTicket(context.Principal, context.Properties, context.Options.AuthenticationScheme);
} }

View File

@ -32,7 +32,7 @@ namespace Microsoft.AspNet.Authentication.Google
var payload = JObject.Parse(await response.Content.ReadAsStringAsync()); var payload = JObject.Parse(await response.Content.ReadAsStringAsync());
var context = new OAuthAuthenticatedContext(Context, Options, Backchannel, tokens, payload) var context = new OAuthCreatingTicketContext(Context, Options, Backchannel, tokens, payload)
{ {
Properties = properties, Properties = properties,
Principal = new ClaimsPrincipal(identity) Principal = new ClaimsPrincipal(identity)
@ -74,7 +74,7 @@ namespace Microsoft.AspNet.Authentication.Google
identity.AddClaim(new Claim("urn:google:profile", profile, ClaimValueTypes.String, Options.ClaimsIssuer)); identity.AddClaim(new Claim("urn:google:profile", profile, ClaimValueTypes.String, Options.ClaimsIssuer));
} }
await Options.Events.Authenticated(context); await Options.Events.CreatingTicket(context);
return new AuthenticationTicket(context.Principal, context.Properties, context.Options.AuthenticationScheme); return new AuthenticationTicket(context.Principal, context.Properties, context.Options.AuthenticationScheme);
} }

View File

@ -3,11 +3,11 @@
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
namespace Microsoft.AspNet.Authentication.JwtBearer namespace Microsoft.AspNet.Authentication.OpenIdConnectBearer
{ {
public class AuthenticationChallengeContext : BaseControlContext<JwtBearerOptions> public class AuthenticationChallengeContext : BaseControlContext<OpenIdConnectBearerOptions>
{ {
public AuthenticationChallengeContext(HttpContext context, JwtBearerOptions options) public AuthenticationChallengeContext(HttpContext context, OpenIdConnectBearerOptions options)
: base(context, options) : base(context, options)
{ {
} }

View File

@ -4,11 +4,11 @@
using System; using System;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
namespace Microsoft.AspNet.Authentication.JwtBearer namespace Microsoft.AspNet.Authentication.OpenIdConnectBearer
{ {
public class AuthenticationFailedContext : BaseControlContext<JwtBearerOptions> public class AuthenticationFailedContext : BaseControlContext<OpenIdConnectBearerOptions>
{ {
public AuthenticationFailedContext(HttpContext context, JwtBearerOptions options) public AuthenticationFailedContext(HttpContext context, OpenIdConnectBearerOptions options)
: base(context, options) : base(context, options)
{ {
} }

View File

@ -4,14 +4,14 @@
using System.Threading.Tasks; using System.Threading.Tasks;
/// <summary> /// <summary>
/// Specifies events which the <see cref="JwtBearerAuthenticationMiddleware"></see> invokes to enable developer control over the authentication process. /> /// Specifies events which the <see cref="OpenIdConnectBearerAuthenticationMiddleware"></see> invokes to enable developer control over the authentication process. />
/// </summary> /// </summary>
namespace Microsoft.AspNet.Authentication.JwtBearer namespace Microsoft.AspNet.Authentication.OpenIdConnectBearer
{ {
/// <summary> /// <summary>
/// Jwt bearer token middleware events. /// OpenIdConnect bearer token middleware events.
/// </summary> /// </summary>
public interface IJwtBearerEvents public interface IOpenIdConnectBearerEvents
{ {
/// <summary> /// <summary>
/// Invoked if exceptions are thrown during request processing. The exceptions will be re-thrown after this event unless suppressed. /// Invoked if exceptions are thrown during request processing. The exceptions will be re-thrown after this event unless suppressed.

View File

@ -3,11 +3,11 @@
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
namespace Microsoft.AspNet.Authentication.JwtBearer namespace Microsoft.AspNet.Authentication.OpenIdConnectBearer
{ {
public class MessageReceivedContext : BaseControlContext<JwtBearerOptions> public class MessageReceivedContext : BaseControlContext<OpenIdConnectBearerOptions>
{ {
public MessageReceivedContext(HttpContext context, JwtBearerOptions options) public MessageReceivedContext(HttpContext context, OpenIdConnectBearerOptions options)
: base(context, options) : base(context, options)
{ {
} }

View File

@ -6,14 +6,14 @@ using System.Threading.Tasks;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
/// <summary> /// <summary>
/// Specifies events which the <see cref="JwtBearerAuthenticationMiddleware"></see> invokes to enable developer control over the authentication process. /> /// Specifies events which the <see cref="OpenIdConnectBearerAuthenticationMiddleware"></see> invokes to enable developer control over the authentication process. />
/// </summary> /// </summary>
namespace Microsoft.AspNet.Authentication.JwtBearer namespace Microsoft.AspNet.Authentication.OpenIdConnectBearer
{ {
/// <summary> /// <summary>
/// Jwt bearer token middleware events. /// OpenIdConnect bearer token middleware events.
/// </summary> /// </summary>
public class JwtBearerEvents : IJwtBearerEvents public class OpenIdConnectBearerEvents : IOpenIdConnectBearerEvents
{ {
/// <summary> /// <summary>
/// Invoked if exceptions are thrown during request processing. The exceptions will be re-thrown after this event unless suppressed. /// Invoked if exceptions are thrown during request processing. The exceptions will be re-thrown after this event unless suppressed.

View File

@ -3,11 +3,11 @@
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
namespace Microsoft.AspNet.Authentication.JwtBearer namespace Microsoft.AspNet.Authentication.OpenIdConnectBearer
{ {
public class SecurityTokenReceivedContext : BaseControlContext<JwtBearerOptions> public class SecurityTokenReceivedContext : BaseControlContext<OpenIdConnectBearerOptions>
{ {
public SecurityTokenReceivedContext(HttpContext context, JwtBearerOptions options) public SecurityTokenReceivedContext(HttpContext context, OpenIdConnectBearerOptions options)
: base(context, options) : base(context, options)
{ {
} }

View File

@ -3,11 +3,11 @@
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
namespace Microsoft.AspNet.Authentication.JwtBearer namespace Microsoft.AspNet.Authentication.OpenIdConnectBearer
{ {
public class SecurityTokenValidatedContext : BaseControlContext<JwtBearerOptions> public class SecurityTokenValidatedContext : BaseControlContext<OpenIdConnectBearerOptions>
{ {
public SecurityTokenValidatedContext(HttpContext context, JwtBearerOptions options) public SecurityTokenValidatedContext(HttpContext context, OpenIdConnectBearerOptions options)
: base(context, options) : base(context, options)
{ {
} }

View File

@ -2,16 +2,16 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System;
using Microsoft.AspNet.Authentication.JwtBearer; using Microsoft.AspNet.Authentication.OpenIdConnectBearer;
using Microsoft.Framework.Internal; using Microsoft.Framework.Internal;
using Microsoft.Framework.OptionsModel; using Microsoft.Framework.OptionsModel;
namespace Microsoft.AspNet.Builder namespace Microsoft.AspNet.Builder
{ {
/// <summary> /// <summary>
/// Extension methods to add Jwt Bearer authentication capabilities to an HTTP application pipeline /// Extension methods to add OpenIdConnect Bearer authentication capabilities to an HTTP application pipeline
/// </summary> /// </summary>
public static class JwtBearerAppBuilderExtensions public static class OpenIdConnectBearerAppBuilderExtensions
{ {
/// <summary> /// <summary>
/// Adds Bearer token processing to an HTTP application pipeline. This middleware understands appropriately /// Adds Bearer token processing to an HTTP application pipeline. This middleware understands appropriately
@ -24,9 +24,9 @@ namespace Microsoft.AspNet.Builder
/// <param name="app">The application builder</param> /// <param name="app">The application builder</param>
/// <param name="options">Options which control the processing of the bearer header.</param> /// <param name="options">Options which control the processing of the bearer header.</param>
/// <returns>The application builder</returns> /// <returns>The application builder</returns>
public static IApplicationBuilder UseJwtBearerAuthentication([NotNull] this IApplicationBuilder app, [NotNull] JwtBearerOptions options) public static IApplicationBuilder UseOpenIdConnectBearerAuthentication([NotNull] this IApplicationBuilder app, [NotNull] OpenIdConnectBearerOptions options)
{ {
return app.UseMiddleware<JwtBearerMiddleware>(options); return app.UseMiddleware<OpenIdConnectBearerMiddleware>(options);
} }
/// <summary> /// <summary>
@ -40,14 +40,14 @@ namespace Microsoft.AspNet.Builder
/// <param name="app">The application builder</param> /// <param name="app">The application builder</param>
/// <param name="configureOptions">Used to configure Middleware options.</param> /// <param name="configureOptions">Used to configure Middleware options.</param>
/// <returns>The application builder</returns> /// <returns>The application builder</returns>
public static IApplicationBuilder UseJwtBearerAuthentication([NotNull] this IApplicationBuilder app, Action<JwtBearerOptions> configureOptions) public static IApplicationBuilder UseOpenIdConnectBearerAuthentication([NotNull] this IApplicationBuilder app, Action<OpenIdConnectBearerOptions> configureOptions)
{ {
var options = new JwtBearerOptions(); var options = new OpenIdConnectBearerOptions();
if (configureOptions != null) if (configureOptions != null)
{ {
configureOptions(options); configureOptions(options);
} }
return app.UseJwtBearerAuthentication(options); return app.UseOpenIdConnectBearerAuthentication(options);
} }
} }
} }

View File

@ -1,16 +1,16 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.AspNet.Authentication.JwtBearer namespace Microsoft.AspNet.Authentication.OpenIdConnectBearer
{ {
/// <summary> /// <summary>
/// Default values used by authorization server and bearer authentication. /// Default values used by authorization server and bearer authentication.
/// </summary> /// </summary>
public static class JwtBearerDefaults public static class OpenIdConnectBearerDefaults
{ {
/// <summary> /// <summary>
/// Default value for AuthenticationScheme property in the JwtBearerAuthenticationOptions and /// Default value for AuthenticationScheme property in the OpenIdConnectBearerAuthenticationOptions and
/// JwtAuthorizationServerOptions. /// OpenIdConnectAuthorizationServerOptions.
/// </summary> /// </summary>
public const string AuthenticationScheme = "Bearer"; public const string AuthenticationScheme = "Bearer";
} }

View File

@ -10,9 +10,9 @@ using Microsoft.AspNet.Http.Features.Authentication;
using Microsoft.Framework.Logging; using Microsoft.Framework.Logging;
using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Microsoft.IdentityModel.Protocols.OpenIdConnect;
namespace Microsoft.AspNet.Authentication.JwtBearer namespace Microsoft.AspNet.Authentication.OpenIdConnectBearer
{ {
public class JwtBearerHandler : AuthenticationHandler<JwtBearerOptions> internal class OpenIdConnectBearerHandler : AuthenticationHandler<OpenIdConnectBearerOptions>
{ {
private OpenIdConnectConfiguration _configuration; private OpenIdConnectConfiguration _configuration;

View File

@ -6,35 +6,34 @@ using System.Net.Http;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.Framework.Internal; using Microsoft.Framework.Internal;
using Microsoft.Framework.Logging; using Microsoft.Framework.Logging;
using Microsoft.Framework.OptionsModel;
using Microsoft.Framework.WebEncoders; using Microsoft.Framework.WebEncoders;
using Microsoft.IdentityModel.Protocols; using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Microsoft.IdentityModel.Protocols.OpenIdConnect;
namespace Microsoft.AspNet.Authentication.JwtBearer namespace Microsoft.AspNet.Authentication.OpenIdConnectBearer
{ {
/// <summary> /// <summary>
/// Bearer authentication middleware component which is added to an HTTP pipeline. This class is not /// Bearer authentication middleware component which is added to an HTTP pipeline. This class is not
/// created by application code directly, instead it is added by calling the the IAppBuilder UseJwtBearerAuthentication /// created by application code directly, instead it is added by calling the the IAppBuilder UseOpenIdConnectBearerAuthentication
/// extension method. /// extension method.
/// </summary> /// </summary>
public class JwtBearerMiddleware : AuthenticationMiddleware<JwtBearerOptions> public class OpenIdConnectBearerMiddleware : AuthenticationMiddleware<OpenIdConnectBearerOptions>
{ {
/// <summary> /// <summary>
/// Bearer authentication component which is added to an HTTP pipeline. This constructor is not /// Bearer authentication component which is added to an HTTP pipeline. This constructor is not
/// called by application code directly, instead it is added by calling the the IAppBuilder UseJwtBearerAuthentication /// called by application code directly, instead it is added by calling the the IAppBuilder UseOpenIdConnectBearerAuthentication
/// extension method. /// extension method.
/// </summary> /// </summary>
public JwtBearerMiddleware( public OpenIdConnectBearerMiddleware(
[NotNull] RequestDelegate next, [NotNull] RequestDelegate next,
[NotNull] ILoggerFactory loggerFactory, [NotNull] ILoggerFactory loggerFactory,
[NotNull] IUrlEncoder encoder, [NotNull] IUrlEncoder encoder,
[NotNull] JwtBearerOptions options) [NotNull] OpenIdConnectBearerOptions options)
: base(next, options, loggerFactory, encoder) : base(next, options, loggerFactory, encoder)
{ {
if (Options.Events == null) if (Options.Events == null)
{ {
Options.Events = new JwtBearerEvents(); Options.Events = new OpenIdConnectBearerEvents();
} }
if (string.IsNullOrEmpty(Options.TokenValidationParameters.ValidAudience) && !string.IsNullOrEmpty(Options.Audience)) if (string.IsNullOrEmpty(Options.TokenValidationParameters.ValidAudience) && !string.IsNullOrEmpty(Options.Audience))
@ -74,9 +73,9 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
/// Called by the AuthenticationMiddleware base class to create a per-request handler. /// Called by the AuthenticationMiddleware base class to create a per-request handler.
/// </summary> /// </summary>
/// <returns>A new instance of the request handler</returns> /// <returns>A new instance of the request handler</returns>
protected override AuthenticationHandler<JwtBearerOptions> CreateHandler() protected override AuthenticationHandler<OpenIdConnectBearerOptions> CreateHandler()
{ {
return new JwtBearerHandler(); return new OpenIdConnectBearerHandler();
} }
} }
} }

View File

@ -9,19 +9,19 @@ using System.Net.Http;
using Microsoft.IdentityModel.Protocols; using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Microsoft.IdentityModel.Protocols.OpenIdConnect;
namespace Microsoft.AspNet.Authentication.JwtBearer namespace Microsoft.AspNet.Authentication.OpenIdConnectBearer
{ {
/// <summary> /// <summary>
/// Options class provides information needed to control Bearer Authentication middleware behavior /// Options class provides information needed to control Bearer Authentication middleware behavior
/// </summary> /// </summary>
public class JwtBearerOptions : AuthenticationOptions public class OpenIdConnectBearerOptions : AuthenticationOptions
{ {
/// <summary> /// <summary>
/// Creates an instance of bearer authentication options with default values. /// Creates an instance of bearer authentication options with default values.
/// </summary> /// </summary>
public JwtBearerOptions() : base() public OpenIdConnectBearerOptions() : base()
{ {
AuthenticationScheme = JwtBearerDefaults.AuthenticationScheme; AuthenticationScheme = OpenIdConnectBearerDefaults.AuthenticationScheme;
} }
/// <summary> /// <summary>
@ -35,24 +35,24 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
public string Authority { get; set; } public string Authority { get; set; }
/// <summary> /// <summary>
/// Gets or sets the audience for any received JWT token. /// Gets or sets the audience for any received OpenIdConnect token.
/// </summary> /// </summary>
/// <value> /// <value>
/// The expected audience for any received JWT token. /// The expected audience for any received OpenIdConnect token.
/// </value> /// </value>
public string Audience { get; set; } public string Audience { get; set; }
/// <summary> /// <summary>
/// Gets or sets the challenge to put in the "WWW-Authenticate" header. /// Gets or sets the challenge to put in the "WWW-Authenticate" header.
/// </summary> /// </summary>
public string Challenge { get; set; } = JwtBearerDefaults.AuthenticationScheme; public string Challenge { get; set; } = OpenIdConnectBearerDefaults.AuthenticationScheme;
/// <summary> /// <summary>
/// The object provided by the application to process events raised by the bearer authentication middleware. /// The object provided by the application to process events raised by the bearer authentication middleware.
/// The application may implement the interface fully, or it may create an instance of JwtBearerAuthenticationEvents /// The application may implement the interface fully, or it may create an instance of OpenIdConnectBearerAuthenticationEvents
/// and assign delegates only to the events it wants to process. /// and assign delegates only to the events it wants to process.
/// </summary> /// </summary>
public IJwtBearerEvents Events { get; set; } = new JwtBearerEvents(); public IOpenIdConnectBearerEvents Events { get; set; } = new OpenIdConnectBearerEvents();
/// <summary> /// <summary>
/// The HttpMessageHandler used to retrieve metadata. /// The HttpMessageHandler used to retrieve metadata.

View File

@ -1,5 +1,5 @@
// <auto-generated /> // <auto-generated />
namespace Microsoft.AspNet.Authentication.JwtBearer namespace Microsoft.AspNet.Authentication.OpenIdConnectBearer
{ {
using System.Globalization; using System.Globalization;
using System.Reflection; using System.Reflection;
@ -8,7 +8,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
internal static class Resources internal static class Resources
{ {
private static readonly ResourceManager _resourceManager private static readonly ResourceManager _resourceManager
= new ResourceManager("Microsoft.AspNet.Authentication.JwtBearer.Resources", typeof(Resources).GetTypeInfo().Assembly); = new ResourceManager("Microsoft.AspNet.Authentication.OpenIdConnectBearer.Resources", typeof(Resources).GetTypeInfo().Assembly);
/// <summary> /// <summary>
/// The '{0}' option must be provided. /// The '{0}' option must be provided.

View File

@ -1,6 +1,6 @@
{ {
"version": "1.0.0-*", "version": "1.0.0-*",
"description": "ASP.NET 5 middleware that enables an application to receive a Jwt bearer token.", "description": "ASP.NET 5 middleware that enables an application to receive a OpenIdConnect bearer token.",
"repository": { "repository": {
"type": "git", "type": "git",
"url": "git://github.com/aspnet/security" "url": "git://github.com/aspnet/security"

View File

@ -28,7 +28,7 @@ namespace Microsoft.AspNet.Authentication.MicrosoftAccount
var payload = JObject.Parse(await response.Content.ReadAsStringAsync()); var payload = JObject.Parse(await response.Content.ReadAsStringAsync());
var context = new OAuthAuthenticatedContext(Context, Options, Backchannel, tokens, payload) var context = new OAuthCreatingTicketContext(Context, Options, Backchannel, tokens, payload)
{ {
Properties = properties, Properties = properties,
Principal = new ClaimsPrincipal(identity) Principal = new ClaimsPrincipal(identity)
@ -54,7 +54,7 @@ namespace Microsoft.AspNet.Authentication.MicrosoftAccount
identity.AddClaim(new Claim(ClaimTypes.Email, email, ClaimValueTypes.String, Options.ClaimsIssuer)); identity.AddClaim(new Claim(ClaimTypes.Email, email, ClaimValueTypes.String, Options.ClaimsIssuer));
} }
await Options.Events.Authenticated(context); await Options.Events.CreatingTicket(context);
return new AuthenticationTicket(context.Principal, context.Properties, context.Options.AuthenticationScheme); return new AuthenticationTicket(context.Principal, context.Properties, context.Options.AuthenticationScheme);
} }

View File

@ -16,19 +16,19 @@ namespace Microsoft.AspNet.Authentication.OAuth
/// </summary> /// </summary>
/// <param name="context">Contains information about the login session.</param> /// <param name="context">Contains information about the login session.</param>
/// <returns>A <see cref="Task"/> representing the completed operation.</returns> /// <returns>A <see cref="Task"/> representing the completed operation.</returns>
Task Authenticated(OAuthAuthenticatedContext context); Task CreatingTicket(OAuthCreatingTicketContext context);
/// <summary> /// <summary>
/// Invoked prior to the <see cref="ClaimsIdentity"/> being saved in a local cookie and the browser being redirected to the originally requested URL. /// Invoked prior to the <see cref="ClaimsIdentity"/> being saved in a local cookie and the browser being redirected to the originally requested URL.
/// </summary> /// </summary>
/// <param name="context"></param> /// <param name="context"></param>
/// <returns>A <see cref="Task"/> representing the completed operation.</returns> /// <returns>A <see cref="Task"/> representing the completed operation.</returns>
Task ReturnEndpoint(OAuthReturnEndpointContext context); Task SigningIn(SigningInContext context);
/// <summary> /// <summary>
/// Called when a Challenge causes a redirect to the authorize endpoint. /// Called when a Challenge causes a redirect to the authorize endpoint.
/// </summary> /// </summary>
/// <param name="context">Contains redirect URI and <see cref="AuthenticationProperties"/> of the challenge.</param> /// <param name="context">Contains redirect URI and <see cref="AuthenticationProperties"/> of the challenge.</param>
Task ApplyRedirect(OAuthApplyRedirectContext context); Task RedirectToAuthorizationEndpoint(OAuthRedirectToAuthorizationEndpointContext context);
} }
} }

View File

@ -15,16 +15,16 @@ namespace Microsoft.AspNet.Authentication.OAuth
/// <summary> /// <summary>
/// Contains information about the login session as well as the user <see cref="System.Security.Claims.ClaimsIdentity"/>. /// Contains information about the login session as well as the user <see cref="System.Security.Claims.ClaimsIdentity"/>.
/// </summary> /// </summary>
public class OAuthAuthenticatedContext : BaseContext<OAuthOptions> public class OAuthCreatingTicketContext : BaseContext<OAuthOptions>
{ {
/// <summary> /// <summary>
/// Initializes a new <see cref="OAuthAuthenticatedContext"/>. /// Initializes a new <see cref="OAuthCreatingTicketContext"/>.
/// </summary> /// </summary>
/// <param name="context">The HTTP environment.</param> /// <param name="context">The HTTP environment.</param>
/// <param name="options">The options used by the authentication middleware.</param> /// <param name="options">The options used by the authentication middleware.</param>
/// <param name="backchannel">The HTTP client used by the authentication middleware</param> /// <param name="backchannel">The HTTP client used by the authentication middleware</param>
/// <param name="tokens">The tokens returned from the token endpoint.</param> /// <param name="tokens">The tokens returned from the token endpoint.</param>
public OAuthAuthenticatedContext( public OAuthCreatingTicketContext(
[NotNull] HttpContext context, [NotNull] HttpContext context,
[NotNull] OAuthOptions options, [NotNull] OAuthOptions options,
[NotNull] HttpClient backchannel, [NotNull] HttpClient backchannel,
@ -34,14 +34,14 @@ namespace Microsoft.AspNet.Authentication.OAuth
} }
/// <summary> /// <summary>
/// Initializes a new <see cref="OAuthAuthenticatedContext"/>. /// Initializes a new <see cref="OAuthCreatingTicketContext"/>.
/// </summary> /// </summary>
/// <param name="context">The HTTP environment.</param> /// <param name="context">The HTTP environment.</param>
/// <param name="options">The options used by the authentication middleware.</param> /// <param name="options">The options used by the authentication middleware.</param>
/// <param name="backchannel">The HTTP client used by the authentication middleware</param> /// <param name="backchannel">The HTTP client used by the authentication middleware</param>
/// <param name="tokens">The tokens returned from the token endpoint.</param> /// <param name="tokens">The tokens returned from the token endpoint.</param>
/// <param name="user">The JSON-serialized user.</param> /// <param name="user">The JSON-serialized user.</param>
public OAuthAuthenticatedContext( public OAuthCreatingTicketContext(
[NotNull] HttpContext context, [NotNull] HttpContext context,
[NotNull] OAuthOptions options, [NotNull] OAuthOptions options,
[NotNull] HttpClient backchannel, [NotNull] HttpClient backchannel,

View File

@ -14,17 +14,17 @@ namespace Microsoft.AspNet.Authentication.OAuth
/// <summary> /// <summary>
/// Gets or sets the function that is invoked when the Authenticated method is invoked. /// Gets or sets the function that is invoked when the Authenticated method is invoked.
/// </summary> /// </summary>
public Func<OAuthAuthenticatedContext, Task> OnAuthenticated { get; set; } = context => Task.FromResult(0); public Func<OAuthCreatingTicketContext, Task> OnCreatingTicket { get; set; } = context => Task.FromResult(0);
/// <summary> /// <summary>
/// Gets or sets the function that is invoked when the ReturnEndpoint method is invoked. /// Gets or sets the function that is invoked when the ReturnEndpoint method is invoked.
/// </summary> /// </summary>
public Func<OAuthReturnEndpointContext, Task> OnReturnEndpoint { get; set; } = context => Task.FromResult(0); public Func<SigningInContext, Task> OnSigningIn { get; set; } = context => Task.FromResult(0);
/// <summary> /// <summary>
/// Gets or sets the delegate that is invoked when the ApplyRedirect method is invoked. /// Gets or sets the delegate that is invoked when the RedirectToAuthorizationEndpoint method is invoked.
/// </summary> /// </summary>
public Func<OAuthApplyRedirectContext, Task> OnApplyRedirect { get; set; } = context => public Func<OAuthRedirectToAuthorizationEndpointContext, Task> OnRedirectToAuthorizationEndpoint { get; set; } = context =>
{ {
context.Response.Redirect(context.RedirectUri); context.Response.Redirect(context.RedirectUri);
return Task.FromResult(0); return Task.FromResult(0);
@ -35,19 +35,19 @@ namespace Microsoft.AspNet.Authentication.OAuth
/// </summary> /// </summary>
/// <param name="context">Contains information about the login session as well as the user <see cref="ClaimsIdentity"/>.</param> /// <param name="context">Contains information about the login session as well as the user <see cref="ClaimsIdentity"/>.</param>
/// <returns>A <see cref="Task"/> representing the completed operation.</returns> /// <returns>A <see cref="Task"/> representing the completed operation.</returns>
public virtual Task Authenticated(OAuthAuthenticatedContext context) => OnAuthenticated(context); public virtual Task CreatingTicket(OAuthCreatingTicketContext context) => OnCreatingTicket(context);
/// <summary> /// <summary>
/// Invoked prior to the <see cref="ClaimsIdentity"/> being saved in a local cookie and the browser being redirected to the originally requested URL. /// Invoked prior to the <see cref="ClaimsIdentity"/> being saved in a local cookie and the browser being redirected to the originally requested URL.
/// </summary> /// </summary>
/// <param name="context">Contains information about the login session as well as the user <see cref="ClaimsIdentity"/></param> /// <param name="context">Contains information about the login session as well as the user <see cref="ClaimsIdentity"/></param>
/// <returns>A <see cref="Task"/> representing the completed operation.</returns> /// <returns>A <see cref="Task"/> representing the completed operation.</returns>
public virtual Task ReturnEndpoint(OAuthReturnEndpointContext context) => OnReturnEndpoint(context); public virtual Task SigningIn(SigningInContext context) => OnSigningIn(context);
/// <summary> /// <summary>
/// Called when a Challenge causes a redirect to authorize endpoint in the OAuth middleware. /// Called when a Challenge causes a redirect to authorize endpoint in the OAuth middleware.
/// </summary> /// </summary>
/// <param name="context">Contains redirect URI and <see cref="AuthenticationProperties"/> of the challenge.</param> /// <param name="context">Contains redirect URI and <see cref="AuthenticationProperties"/> of the challenge.</param>
public virtual Task ApplyRedirect(OAuthApplyRedirectContext context) => OnApplyRedirect(context); public virtual Task RedirectToAuthorizationEndpoint(OAuthRedirectToAuthorizationEndpointContext context) => OnRedirectToAuthorizationEndpoint(context);
} }
} }

View File

@ -7,9 +7,9 @@ using Microsoft.AspNet.Http.Authentication;
namespace Microsoft.AspNet.Authentication.OAuth namespace Microsoft.AspNet.Authentication.OAuth
{ {
/// <summary> /// <summary>
/// Context passed when a Challenge causes a redirect to authorize endpoint in the Microsoft account middleware. /// Context passed when a Challenge causes a redirect to authorize endpoint in the middleware.
/// </summary> /// </summary>
public class OAuthApplyRedirectContext : BaseContext<OAuthOptions> public class OAuthRedirectToAuthorizationEndpointContext : BaseContext<OAuthOptions>
{ {
/// <summary> /// <summary>
/// Creates a new context object. /// Creates a new context object.
@ -17,7 +17,7 @@ namespace Microsoft.AspNet.Authentication.OAuth
/// <param name="context">The HTTP request context.</param> /// <param name="context">The HTTP request context.</param>
/// <param name="properties">The authentication properties of the challenge.</param> /// <param name="properties">The authentication properties of the challenge.</param>
/// <param name="redirectUri">The initial redirect URI.</param> /// <param name="redirectUri">The initial redirect URI.</param>
public OAuthApplyRedirectContext(HttpContext context, OAuthOptions options, AuthenticationProperties properties, string redirectUri) public OAuthRedirectToAuthorizationEndpointContext(HttpContext context, OAuthOptions options, AuthenticationProperties properties, string redirectUri)
: base(context, options) : base(context, options)
{ {
RedirectUri = redirectUri; RedirectUri = redirectUri;

View File

@ -1,31 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNet.Http;
namespace Microsoft.AspNet.Authentication.OAuth
{
/// <summary>
/// Specifies the HTTP request header for the bearer authentication scheme.
/// </summary>
public class OAuthRequestTokenContext : BaseContext
{
/// <summary>
/// Initializes a new <see cref="OAuthRequestTokenContext"/>
/// </summary>
/// <param name="context">HTTP environment</param>
/// <param name="token">The authorization header value.</param>
public OAuthRequestTokenContext(
HttpContext context,
string token)
: base(context)
{
Token = token;
}
/// <summary>
/// The authorization header value
/// </summary>
public string Token { get; set; }
}
}

View File

@ -8,7 +8,7 @@ namespace Microsoft.AspNet.Authentication.OAuth
/// <summary> /// <summary>
/// Provides context information to middleware providers. /// Provides context information to middleware providers.
/// </summary> /// </summary>
public class OAuthReturnEndpointContext : ReturnEndpointContext public class OAuthReturnEndpointContext : SigningInContext
{ {
/// <summary> /// <summary>
/// Initializes a new <see cref="OAuthReturnEndpointContext"/>. /// Initializes a new <see cref="OAuthReturnEndpointContext"/>.

View File

@ -57,7 +57,7 @@ namespace Microsoft.AspNet.Authentication.OAuth
}; };
ticket.Properties.RedirectUri = null; ticket.Properties.RedirectUri = null;
await Options.Events.ReturnEndpoint(context); await Options.Events.SigningIn(context);
if (context.SignInScheme != null && context.Principal != null) if (context.SignInScheme != null && context.Principal != null)
{ {
@ -183,13 +183,13 @@ namespace Microsoft.AspNet.Authentication.OAuth
protected virtual async Task<AuthenticationTicket> CreateTicketAsync(ClaimsIdentity identity, AuthenticationProperties properties, OAuthTokenResponse tokens) protected virtual async Task<AuthenticationTicket> CreateTicketAsync(ClaimsIdentity identity, AuthenticationProperties properties, OAuthTokenResponse tokens)
{ {
var context = new OAuthAuthenticatedContext(Context, Options, Backchannel, tokens) var context = new OAuthCreatingTicketContext(Context, Options, Backchannel, tokens)
{ {
Principal = new ClaimsPrincipal(identity), Principal = new ClaimsPrincipal(identity),
Properties = properties Properties = properties
}; };
await Options.Events.Authenticated(context); await Options.Events.CreatingTicket(context);
if (context.Principal?.Identity == null) if (context.Principal?.Identity == null)
{ {
@ -212,10 +212,10 @@ namespace Microsoft.AspNet.Authentication.OAuth
var authorizationEndpoint = BuildChallengeUrl(properties, BuildRedirectUri(Options.CallbackPath)); var authorizationEndpoint = BuildChallengeUrl(properties, BuildRedirectUri(Options.CallbackPath));
var redirectContext = new OAuthApplyRedirectContext( var redirectContext = new OAuthRedirectToAuthorizationEndpointContext(
Context, Options, Context, Options,
properties, authorizationEndpoint); properties, authorizationEndpoint);
await Options.Events.ApplyRedirect(redirectContext); await Options.Events.RedirectToAuthorizationEndpoint(redirectContext);
return true; return true;
} }
@ -263,7 +263,7 @@ namespace Microsoft.AspNet.Authentication.OAuth
var nonceBytes = new byte[32]; var nonceBytes = new byte[32];
CryptoRandom.GetBytes(nonceBytes); CryptoRandom.GetBytes(nonceBytes);
var correlationId = TextEncodings.Base64Url.Encode(nonceBytes); var correlationId = Base64UrlTextEncoder.Encode(nonceBytes);
var cookieOptions = new CookieOptions var cookieOptions = new CookieOptions
{ {

View File

@ -160,7 +160,7 @@ namespace Microsoft.AspNet.Authentication.OpenIdConnect
// order for local RedirectUri // order for local RedirectUri
// 1. challenge.Properties.RedirectUri // 1. challenge.Properties.RedirectUri
// 2. CurrentUri if Options.DefaultToCurrentUriOnRedirect is true) // 2. CurrentUri if Options.DefaultToCurrentUriOnRedirect is true)
AuthenticationProperties properties = new AuthenticationProperties(context.Properties); var properties = new AuthenticationProperties(context.Properties);
if (!string.IsNullOrEmpty(properties.RedirectUri)) if (!string.IsNullOrEmpty(properties.RedirectUri))
{ {
@ -491,7 +491,7 @@ namespace Microsoft.AspNet.Authentication.OpenIdConnect
ticket = ValidateToken(tokenEndpointResponse.ProtocolMessage.IdToken, message, properties, validationParameters, out jwt); ticket = ValidateToken(tokenEndpointResponse.ProtocolMessage.IdToken, message, properties, validationParameters, out jwt);
await ValidateOpenIdConnectProtocolAsync(null, message); ValidateOpenIdConnectProtocol(null, message);
var authenticationValidatedContext = await RunAuthenticationValidatedEventAsync(message, ticket, tokenEndpointResponse); var authenticationValidatedContext = await RunAuthenticationValidatedEventAsync(message, ticket, tokenEndpointResponse);
if (authenticationValidatedContext.HandledResponse) if (authenticationValidatedContext.HandledResponse)
@ -522,7 +522,7 @@ namespace Microsoft.AspNet.Authentication.OpenIdConnect
var validationParameters = Options.TokenValidationParameters.Clone(); var validationParameters = Options.TokenValidationParameters.Clone();
var ticket = ValidateToken(message.IdToken, message, properties, validationParameters, out jwt); var ticket = ValidateToken(message.IdToken, message, properties, validationParameters, out jwt);
await ValidateOpenIdConnectProtocolAsync(jwt, message); ValidateOpenIdConnectProtocol(jwt, message);
var authenticationValidatedContext = await RunAuthenticationValidatedEventAsync(message, ticket, tokenEndpointResponse: null); var authenticationValidatedContext = await RunAuthenticationValidatedEventAsync(message, ticket, tokenEndpointResponse: null);
if (authenticationValidatedContext.HandledResponse) if (authenticationValidatedContext.HandledResponse)
@ -588,7 +588,7 @@ namespace Microsoft.AspNet.Authentication.OpenIdConnect
/// <returns>Authentication ticket with identity with additional claims, if any.</returns> /// <returns>Authentication ticket with identity with additional claims, if any.</returns>
protected virtual async Task<AuthenticationTicket> GetUserInformationAsync(OpenIdConnectMessage message, AuthenticationTicket ticket) protected virtual async Task<AuthenticationTicket> GetUserInformationAsync(OpenIdConnectMessage message, AuthenticationTicket ticket)
{ {
string userInfoEndpoint = _configuration?.UserInfoEndpoint; var userInfoEndpoint = _configuration?.UserInfoEndpoint;
if (string.IsNullOrEmpty(userInfoEndpoint)) if (string.IsNullOrEmpty(userInfoEndpoint))
{ {
@ -734,7 +734,7 @@ namespace Microsoft.AspNet.Authentication.OpenIdConnect
var nonceBytes = new byte[32]; var nonceBytes = new byte[32];
CryptoRandom.GetBytes(nonceBytes); CryptoRandom.GetBytes(nonceBytes);
var correlationId = TextEncodings.Base64Url.Encode(nonceBytes); var correlationId = Base64UrlTextEncoder.Encode(nonceBytes);
var cookieOptions = new CookieOptions var cookieOptions = new CookieOptions
{ {
@ -1023,7 +1023,7 @@ namespace Microsoft.AspNet.Authentication.OpenIdConnect
return ticket; return ticket;
} }
private async Task ValidateOpenIdConnectProtocolAsync(JwtSecurityToken jwt, OpenIdConnectMessage message) private void ValidateOpenIdConnectProtocol(JwtSecurityToken jwt, OpenIdConnectMessage message)
{ {
string nonce = jwt?.Payload.Nonce; string nonce = jwt?.Payload.Nonce;
if (!string.IsNullOrEmpty(nonce)) if (!string.IsNullOrEmpty(nonce))

View File

@ -72,7 +72,7 @@ namespace Microsoft.AspNet.Authentication.OpenIdConnect
Options.AuthenticationScheme, Options.AuthenticationScheme,
"v1"); "v1");
Options.StringDataFormat = new SecureDataFormat<string>(new StringSerializer(), dataProtector, TextEncodings.Base64Url); Options.StringDataFormat = new SecureDataFormat<string>(new StringSerializer(), dataProtector);
} }
// if the user has not set the AuthorizeCallback, set it from the redirect_uri // if the user has not set the AuthorizeCallback, set it from the redirect_uri

View File

@ -15,19 +15,19 @@ namespace Microsoft.AspNet.Authentication.Twitter
/// </summary> /// </summary>
/// <param name="context">Contains information about the login session as well as the user <see cref="System.Security.Claims.ClaimsIdentity"/>.</param> /// <param name="context">Contains information about the login session as well as the user <see cref="System.Security.Claims.ClaimsIdentity"/>.</param>
/// <returns>A <see cref="Task"/> representing the completed operation.</returns> /// <returns>A <see cref="Task"/> representing the completed operation.</returns>
Task Authenticated(TwitterAuthenticatedContext context); Task CreatingTicket(TwitterCreatingTicketContext context);
/// <summary> /// <summary>
/// Invoked prior to the <see cref="System.Security.Claims.ClaimsIdentity"/> being saved in a local cookie and the browser being redirected to the originally requested URL. /// Invoked prior to the <see cref="System.Security.Claims.ClaimsIdentity"/> being saved in a local cookie and the browser being redirected to the originally requested URL.
/// </summary> /// </summary>
/// <param name="context"></param> /// <param name="context"></param>
/// <returns>A <see cref="Task"/> representing the completed operation.</returns> /// <returns>A <see cref="Task"/> representing the completed operation.</returns>
Task ReturnEndpoint(TwitterReturnEndpointContext context); Task SigningIn(SigningInContext context);
/// <summary> /// <summary>
/// Called when a Challenge causes a redirect to authorize endpoint in the Twitter middleware /// Called when a Challenge causes a redirect to authorize endpoint in the Twitter middleware
/// </summary> /// </summary>
/// <param name="context">Contains redirect URI and <see cref="AuthenticationProperties"/> of the challenge </param> /// <param name="context">Contains redirect URI and <see cref="AuthenticationProperties"/> of the challenge </param>
Task ApplyRedirect(TwitterApplyRedirectContext context); Task RedirectToAuthorizationEndpoint(TwitterRedirectToAuthorizationEndpointContext context);
} }
} }

View File

@ -10,17 +10,17 @@ namespace Microsoft.AspNet.Authentication.Twitter
/// <summary> /// <summary>
/// Contains information about the login session as well as the user <see cref="System.Security.Claims.ClaimsIdentity"/>. /// Contains information about the login session as well as the user <see cref="System.Security.Claims.ClaimsIdentity"/>.
/// </summary> /// </summary>
public class TwitterAuthenticatedContext : BaseContext public class TwitterCreatingTicketContext : BaseContext
{ {
/// <summary> /// <summary>
/// Initializes a <see cref="TwitterAuthenticatedContext"/> /// Initializes a <see cref="TwitterCreatingTicketContext"/>
/// </summary> /// </summary>
/// <param name="context">The HTTP environment</param> /// <param name="context">The HTTP environment</param>
/// <param name="userId">Twitter user ID</param> /// <param name="userId">Twitter user ID</param>
/// <param name="screenName">Twitter screen name</param> /// <param name="screenName">Twitter screen name</param>
/// <param name="accessToken">Twitter access token</param> /// <param name="accessToken">Twitter access token</param>
/// <param name="accessTokenSecret">Twitter access token secret</param> /// <param name="accessTokenSecret">Twitter access token secret</param>
public TwitterAuthenticatedContext( public TwitterCreatingTicketContext(
HttpContext context, HttpContext context,
string userId, string userId,
string screenName, string screenName,

View File

@ -14,17 +14,17 @@ namespace Microsoft.AspNet.Authentication.Twitter
/// <summary> /// <summary>
/// Gets or sets the function that is invoked when the Authenticated method is invoked. /// Gets or sets the function that is invoked when the Authenticated method is invoked.
/// </summary> /// </summary>
public Func<TwitterAuthenticatedContext, Task> OnAuthenticated { get; set; } = context => Task.FromResult(0); public Func<TwitterCreatingTicketContext, Task> OnCreatingTicket { get; set; } = context => Task.FromResult(0);
/// <summary> /// <summary>
/// Gets or sets the function that is invoked when the ReturnEndpoint method is invoked. /// Gets or sets the function that is invoked when the ReturnEndpoint method is invoked.
/// </summary> /// </summary>
public Func<TwitterReturnEndpointContext, Task> OnReturnEndpoint { get; set; } = context => Task.FromResult(0); public Func<SigningInContext, Task> OnSigningIn { get; set; } = context => Task.FromResult(0);
/// <summary> /// <summary>
/// Gets or sets the delegate that is invoked when the ApplyRedirect method is invoked. /// Gets or sets the delegate that is invoked when the ApplyRedirect method is invoked.
/// </summary> /// </summary>
public Func<TwitterApplyRedirectContext, Task> OnApplyRedirect { get; set; } = context => public Func<TwitterRedirectToAuthorizationEndpointContext, Task> OnRedirectToAuthorizationEndpoint { get; set; } = context =>
{ {
context.Response.Redirect(context.RedirectUri); context.Response.Redirect(context.RedirectUri);
return Task.FromResult(0); return Task.FromResult(0);
@ -35,19 +35,19 @@ namespace Microsoft.AspNet.Authentication.Twitter
/// </summary> /// </summary>
/// <param name="context">Contains information about the login session as well as the user <see cref="System.Security.Claims.ClaimsIdentity"/>.</param> /// <param name="context">Contains information about the login session as well as the user <see cref="System.Security.Claims.ClaimsIdentity"/>.</param>
/// <returns>A <see cref="Task"/> representing the completed operation.</returns> /// <returns>A <see cref="Task"/> representing the completed operation.</returns>
public virtual Task Authenticated(TwitterAuthenticatedContext context) => OnAuthenticated(context); public virtual Task CreatingTicket(TwitterCreatingTicketContext context) => OnCreatingTicket(context);
/// <summary> /// <summary>
/// Invoked prior to the <see cref="System.Security.Claims.ClaimsIdentity"/> being saved in a local cookie and the browser being redirected to the originally requested URL. /// Invoked prior to the <see cref="System.Security.Claims.ClaimsIdentity"/> being saved in a local cookie and the browser being redirected to the originally requested URL.
/// </summary> /// </summary>
/// <param name="context"></param> /// <param name="context"></param>
/// <returns>A <see cref="Task"/> representing the completed operation.</returns> /// <returns>A <see cref="Task"/> representing the completed operation.</returns>
public virtual Task ReturnEndpoint(TwitterReturnEndpointContext context) => OnReturnEndpoint(context); public virtual Task SigningIn(SigningInContext context) => OnSigningIn(context);
/// <summary> /// <summary>
/// Called when a Challenge causes a redirect to authorize endpoint in the Twitter middleware /// Called when a Challenge causes a redirect to authorize endpoint in the Twitter middleware
/// </summary> /// </summary>
/// <param name="context">Contains redirect URI and <see cref="AuthenticationProperties"/> of the challenge </param> /// <param name="context">Contains redirect URI and <see cref="AuthenticationProperties"/> of the challenge </param>
public virtual Task ApplyRedirect(TwitterApplyRedirectContext context) => OnApplyRedirect(context); public virtual Task RedirectToAuthorizationEndpoint(TwitterRedirectToAuthorizationEndpointContext context) => OnRedirectToAuthorizationEndpoint(context);
} }
} }

View File

@ -9,7 +9,7 @@ namespace Microsoft.AspNet.Authentication.Twitter
/// <summary> /// <summary>
/// The Context passed when a Challenge causes a redirect to authorize endpoint in the Twitter middleware. /// The Context passed when a Challenge causes a redirect to authorize endpoint in the Twitter middleware.
/// </summary> /// </summary>
public class TwitterApplyRedirectContext : BaseContext<TwitterOptions> public class TwitterRedirectToAuthorizationEndpointContext : BaseContext<TwitterOptions>
{ {
/// <summary> /// <summary>
/// Creates a new context object. /// Creates a new context object.
@ -18,7 +18,7 @@ namespace Microsoft.AspNet.Authentication.Twitter
/// <param name="options">The Twitter middleware options.</param> /// <param name="options">The Twitter middleware options.</param>
/// <param name="properties">The authentication properties of the challenge.</param> /// <param name="properties">The authentication properties of the challenge.</param>
/// <param name="redirectUri">The initial redirect URI.</param> /// <param name="redirectUri">The initial redirect URI.</param>
public TwitterApplyRedirectContext(HttpContext context, TwitterOptions options, public TwitterRedirectToAuthorizationEndpointContext(HttpContext context, TwitterOptions options,
AuthenticationProperties properties, string redirectUri) AuthenticationProperties properties, string redirectUri)
: base(context, options) : base(context, options)
{ {

View File

@ -1,25 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNet.Http;
namespace Microsoft.AspNet.Authentication.Twitter
{
/// <summary>
/// Provides context information to middleware providers.
/// </summary>
public class TwitterReturnEndpointContext : ReturnEndpointContext
{
/// <summary>
/// Initializes a new <see cref="TwitterReturnEndpointContext"/>.
/// </summary>
/// <param name="context">HTTP environment</param>
/// <param name="ticket">The authentication ticket</param>
public TwitterReturnEndpointContext(
HttpContext context,
AuthenticationTicket ticket)
: base(context, ticket)
{
}
}
}

View File

@ -1,21 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.AspNet.Authentication.Twitter
{
/// <summary>
/// Provides access to a request token serializer.
/// </summary>
public static class Serializers
{
static Serializers()
{
RequestToken = new RequestTokenSerializer();
}
/// <summary>
/// Gets or sets a statically-avaliable serializer object. The value for this property will be <see cref="RequestTokenSerializer"/> by default.
/// </summary>
public static IDataSerializer<RequestToken> RequestToken { get; private set; }
}
}

View File

@ -117,13 +117,13 @@ namespace Microsoft.AspNet.Authentication.Twitter
protected virtual async Task<AuthenticationTicket> CreateTicketAsync(ClaimsIdentity identity, AuthenticationProperties properties, AccessToken token) protected virtual async Task<AuthenticationTicket> CreateTicketAsync(ClaimsIdentity identity, AuthenticationProperties properties, AccessToken token)
{ {
var context = new TwitterAuthenticatedContext(Context, token.UserId, token.ScreenName, token.Token, token.TokenSecret) var context = new TwitterCreatingTicketContext(Context, token.UserId, token.ScreenName, token.Token, token.TokenSecret)
{ {
Principal = new ClaimsPrincipal(identity), Principal = new ClaimsPrincipal(identity),
Properties = properties Properties = properties
}; };
await Options.Events.Authenticated(context); await Options.Events.CreatingTicket(context);
if (context.Principal?.Identity == null) if (context.Principal?.Identity == null)
{ {
@ -154,10 +154,10 @@ namespace Microsoft.AspNet.Authentication.Twitter
Response.Cookies.Append(StateCookie, Options.StateDataFormat.Protect(requestToken), cookieOptions); Response.Cookies.Append(StateCookie, Options.StateDataFormat.Protect(requestToken), cookieOptions);
var redirectContext = new TwitterApplyRedirectContext( var redirectContext = new TwitterRedirectToAuthorizationEndpointContext(
Context, Options, Context, Options,
properties, twitterAuthenticationEndpoint); properties, twitterAuthenticationEndpoint);
await Options.Events.ApplyRedirect(redirectContext); await Options.Events.RedirectToAuthorizationEndpoint(redirectContext);
return true; return true;
} }
else else
@ -177,14 +177,14 @@ namespace Microsoft.AspNet.Authentication.Twitter
return true; return true;
} }
var context = new TwitterReturnEndpointContext(Context, model) var context = new SigningInContext(Context, model)
{ {
SignInScheme = Options.SignInScheme, SignInScheme = Options.SignInScheme,
RedirectUri = model.Properties.RedirectUri RedirectUri = model.Properties.RedirectUri
}; };
model.Properties.RedirectUri = null; model.Properties.RedirectUri = null;
await Options.Events.ReturnEndpoint(context); await Options.Events.SigningIn(context);
if (context.SignInScheme != null && context.Principal != null) if (context.SignInScheme != null && context.Principal != null)
{ {

View File

@ -59,9 +59,8 @@ namespace Microsoft.AspNet.Authentication.Twitter
var dataProtector = dataProtectionProvider.CreateProtector( var dataProtector = dataProtectionProvider.CreateProtector(
typeof(TwitterMiddleware).FullName, Options.AuthenticationScheme, "v1"); typeof(TwitterMiddleware).FullName, Options.AuthenticationScheme, "v1");
Options.StateDataFormat = new SecureDataFormat<RequestToken>( Options.StateDataFormat = new SecureDataFormat<RequestToken>(
Serializers.RequestToken, new RequestTokenSerializer(),
dataProtector, dataProtector);
TextEncodings.Base64Url);
} }
if (string.IsNullOrEmpty(Options.SignInScheme)) if (string.IsNullOrEmpty(Options.SignInScheme))

View File

@ -1,21 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
namespace Microsoft.AspNet.Authentication
{
public class Base64TextEncoder : ITextEncoder
{
public string Encode(byte[] data)
{
return Convert.ToBase64String(data);
}
public byte[] Decode(string text)
{
return Convert.FromBase64String(text);
}
}
}

View File

@ -1,20 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNet.Http.Authentication;
namespace Microsoft.AspNet.Authentication
{
public static class DataSerializers
{
static DataSerializers()
{
Properties = new PropertiesSerializer();
Ticket = new TicketSerializer();
}
public static IDataSerializer<AuthenticationProperties> Properties { get; private set; }
public static IDataSerializer<AuthenticationTicket> Ticket { get; private set; }
}
}

View File

@ -1,11 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.AspNet.Authentication
{
public interface ITextEncoder
{
string Encode(byte[] data);
byte[] Decode(string text);
}
}

View File

@ -9,7 +9,7 @@ namespace Microsoft.AspNet.Authentication
public class PropertiesDataFormat : SecureDataFormat<AuthenticationProperties> public class PropertiesDataFormat : SecureDataFormat<AuthenticationProperties>
{ {
public PropertiesDataFormat(IDataProtector protector) public PropertiesDataFormat(IDataProtector protector)
: base(DataSerializers.Properties, protector, TextEncodings.Base64Url) : base(new PropertiesSerializer(), protector)
{ {
} }
} }

View File

@ -1,6 +1,7 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.DataProtection;
@ -10,20 +11,18 @@ namespace Microsoft.AspNet.Authentication
{ {
private readonly IDataSerializer<TData> _serializer; private readonly IDataSerializer<TData> _serializer;
private readonly IDataProtector _protector; private readonly IDataProtector _protector;
private readonly ITextEncoder _encoder;
public SecureDataFormat(IDataSerializer<TData> serializer, IDataProtector protector, ITextEncoder encoder) public SecureDataFormat(IDataSerializer<TData> serializer, IDataProtector protector)
{ {
_serializer = serializer; _serializer = serializer;
_protector = protector; _protector = protector;
_encoder = encoder;
} }
public string Protect(TData data) public string Protect(TData data)
{ {
byte[] userData = _serializer.Serialize(data); byte[] userData = _serializer.Serialize(data);
byte[] protectedData = _protector.Protect(userData); byte[] protectedData = _protector.Protect(userData);
string protectedText = _encoder.Encode(protectedData); string protectedText = Base64UrlTextEncoder.Encode(protectedData);
return protectedText; return protectedText;
} }
@ -37,7 +36,7 @@ namespace Microsoft.AspNet.Authentication
return default(TData); return default(TData);
} }
byte[] protectedData = _encoder.Decode(protectedText); byte[] protectedData = Base64UrlTextEncoder.Decode(protectedText);
if (protectedData == null) if (protectedData == null)
{ {
return default(TData); return default(TData);

View File

@ -2,18 +2,17 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Authentication namespace Microsoft.AspNet.Authentication
{ {
public class Base64UrlTextEncoder : ITextEncoder public static class Base64UrlTextEncoder
{ {
public string Encode([NotNull] byte[] data) public static string Encode(byte[] data)
{ {
return Convert.ToBase64String(data).TrimEnd('=').Replace('+', '-').Replace('/', '_'); return Convert.ToBase64String(data).TrimEnd('=').Replace('+', '-').Replace('/', '_');
} }
public byte[] Decode([NotNull] string text) public static byte[] Decode(string text)
{ {
return Convert.FromBase64String(Pad(text.Replace('-', '+').Replace('_', '/'))); return Convert.FromBase64String(Pad(text.Replace('-', '+').Replace('_', '/')));
} }
@ -27,5 +26,6 @@ namespace Microsoft.AspNet.Authentication
} }
return text + new string('=', padding); return text + new string('=', padding);
} }
} }
} }

View File

@ -1,21 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.AspNet.Authentication
{
public static class TextEncodings
{
private static readonly ITextEncoder Base64Instance = new Base64TextEncoder();
private static readonly ITextEncoder Base64UrlInstance = new Base64UrlTextEncoder();
public static ITextEncoder Base64
{
get { return Base64Instance; }
}
public static ITextEncoder Base64Url
{
get { return Base64UrlInstance; }
}
}
}

View File

@ -7,7 +7,7 @@ namespace Microsoft.AspNet.Authentication
{ {
public class TicketDataFormat : SecureDataFormat<AuthenticationTicket> public class TicketDataFormat : SecureDataFormat<AuthenticationTicket>
{ {
public TicketDataFormat(IDataProtector protector) : base(DataSerializers.Ticket, protector, TextEncodings.Base64Url) public TicketDataFormat(IDataProtector protector) : base(new TicketSerializer(), protector)
{ {
} }
} }

View File

@ -1,22 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNet.Http;
namespace Microsoft.AspNet.Authentication
{
public abstract class EndpointContext : BaseContext
{
protected EndpointContext(HttpContext context)
: base(context)
{
}
public bool IsRequestCompleted { get; private set; }
public void RequestCompleted()
{
IsRequestCompleted = true;
}
}
}

View File

@ -1,36 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNet.Http;
namespace Microsoft.AspNet.Authentication
{
/// <summary>
/// Base class used for certain event contexts
/// </summary>
public abstract class EndpointContext<TOptions> : BaseContext<TOptions>
{
/// <summary>
/// Creates an instance of this context
/// </summary>
protected EndpointContext(HttpContext context, TOptions options)
: base(context, options)
{
}
/// <summary>
/// True if the request should not be processed further by other components.
/// </summary>
public bool IsRequestCompleted { get; private set; }
/// <summary>
/// Prevents the request from being processed further by other components.
/// IsRequestCompleted becomes true after calling.
/// </summary>
public void RequestCompleted()
{
IsRequestCompleted = true;
}
}
}

View File

@ -8,9 +8,12 @@ using Microsoft.AspNet.Http.Authentication;
namespace Microsoft.AspNet.Authentication namespace Microsoft.AspNet.Authentication
{ {
public abstract class ReturnEndpointContext : EndpointContext /// <summary>
/// Provides context information to middleware providers.
/// </summary>
public class SigningInContext : BaseContext
{ {
protected ReturnEndpointContext( public SigningInContext(
HttpContext context, HttpContext context,
AuthenticationTicket ticket) AuthenticationTicket ticket)
: base(context) : base(context)
@ -25,6 +28,13 @@ namespace Microsoft.AspNet.Authentication
public ClaimsPrincipal Principal { get; set; } public ClaimsPrincipal Principal { get; set; }
public AuthenticationProperties Properties { get; set; } public AuthenticationProperties Properties { get; set; }
public bool IsRequestCompleted { get; private set; }
public void RequestCompleted()
{
IsRequestCompleted = true;
}
public string SignInScheme { get; set; } public string SignInScheme { get; set; }
[SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Justification = "By design")] [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Justification = "By design")]

View File

@ -1,15 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.AspNet.Authentication
{
/// <summary>
/// The algorithm used to generate the subject public key information blob hashes.
/// </summary>
public enum SubjectPublicKeyInfoAlgorithm
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sha", Justification = "It is correct.")] Sha1,
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sha", Justification = "It is correct.")] Sha256
}
}

View File

@ -484,7 +484,7 @@ namespace Microsoft.AspNet.Authentication.Cookies
options.SlidingExpiration = false; options.SlidingExpiration = false;
options.Events = new CookieAuthenticationEvents() options.Events = new CookieAuthenticationEvents()
{ {
OnResponseSignIn = context => OnSigningIn = context =>
{ {
context.Properties.ExpiresUtc = clock.UtcNow.Add(TimeSpan.FromMinutes(5)); context.Properties.ExpiresUtc = clock.UtcNow.Add(TimeSpan.FromMinutes(5));
return Task.FromResult(0); return Task.FromResult(0);

View File

@ -10,7 +10,6 @@ namespace Microsoft.AspNet.Authentication
[Fact] [Fact]
public void DataOfVariousLengthRoundTripCorrectly() public void DataOfVariousLengthRoundTripCorrectly()
{ {
var encoder = new Base64UrlTextEncoder();
for (int length = 0; length != 256; ++length) for (int length = 0; length != 256; ++length)
{ {
var data = new byte[length]; var data = new byte[length];
@ -18,8 +17,8 @@ namespace Microsoft.AspNet.Authentication
{ {
data[index] = (byte)(5 + length + (index * 23)); data[index] = (byte)(5 + length + (index * 23));
} }
string text = encoder.Encode(data); string text = Base64UrlTextEncoder.Encode(data);
byte[] result = encoder.Decode(text); byte[] result = Base64UrlTextEncoder.Decode(text);
for (int index = 0; index != length; ++index) for (int index = 0; index != length; ++index)
{ {

View File

@ -35,7 +35,7 @@ namespace Microsoft.AspNet.Authentication.Facebook
options.AppSecret = "Test App Secret"; options.AppSecret = "Test App Secret";
options.Events = new OAuthEvents options.Events = new OAuthEvents
{ {
OnApplyRedirect = context => OnRedirectToAuthorizationEndpoint = context =>
{ {
context.Response.Redirect(context.RedirectUri + "&custom=test"); context.Response.Redirect(context.RedirectUri + "&custom=test");
return Task.FromResult(0); return Task.FromResult(0);

View File

@ -199,7 +199,7 @@ namespace Microsoft.AspNet.Authentication.Google
options.ClientSecret = "Test Secret"; options.ClientSecret = "Test Secret";
options.Events = new OAuthEvents options.Events = new OAuthEvents
{ {
OnApplyRedirect = context => OnRedirectToAuthorizationEndpoint = context =>
{ {
context.Response.Redirect(context.RedirectUri + "&custom=test"); context.Response.Redirect(context.RedirectUri + "&custom=test");
return Task.FromResult(0); return Task.FromResult(0);
@ -416,7 +416,7 @@ namespace Microsoft.AspNet.Authentication.Google
}; };
options.Events = new OAuthEvents options.Events = new OAuthEvents
{ {
OnAuthenticated = context => OnCreatingTicket = context =>
{ {
var refreshToken = context.RefreshToken; var refreshToken = context.RefreshToken;
context.Principal.AddIdentity(new ClaimsIdentity(new Claim[] { new Claim("RefreshToken", refreshToken, ClaimValueTypes.String, "Google") }, "Google")); context.Principal.AddIdentity(new ClaimsIdentity(new Claim[] { new Claim("RefreshToken", refreshToken, ClaimValueTypes.String, "Google") }, "Google"));
@ -457,7 +457,7 @@ namespace Microsoft.AspNet.Authentication.Google
options.AccessType = "offline"; options.AccessType = "offline";
options.Events = new OAuthEvents() options.Events = new OAuthEvents()
{ {
OnAuthenticated = context => OnCreatingTicket = context =>
{ {
Assert.NotNull(context.User); Assert.NotNull(context.User);
Assert.Equal(context.AccessToken, "Test Access Token"); Assert.Equal(context.AccessToken, "Test Access Token");

View File

@ -15,9 +15,9 @@ using Microsoft.AspNet.TestHost;
using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.DependencyInjection;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Authentication.JwtBearer namespace Microsoft.AspNet.Authentication.OpenIdConnectBearer
{ {
public class JwtBearerMiddlewareTests public class OpenIdConnectBearerMiddlewareTests
{ {
[Fact] [Fact]
public async Task BearerTokenValidation() public async Task BearerTokenValidation()
@ -27,7 +27,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
options.AutomaticAuthentication = true; options.AutomaticAuthentication = true;
options.Authority = "https://login.windows.net/tushartest.onmicrosoft.com"; options.Authority = "https://login.windows.net/tushartest.onmicrosoft.com";
options.Audience = "https://TusharTest.onmicrosoft.com/TodoListService-ManualJwt"; options.Audience = "https://TusharTest.onmicrosoft.com/TodoListService-ManualOpenIdConnect";
options.TokenValidationParameters.ValidateLifetime = false; options.TokenValidationParameters.ValidateLifetime = false;
}); });
@ -66,7 +66,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
{ {
options.AutomaticAuthentication = true; options.AutomaticAuthentication = true;
options.Events = new JwtBearerEvents() options.Events = new OpenIdConnectBearerEvents()
{ {
OnMessageReceived = context => OnMessageReceived = context =>
{ {
@ -116,7 +116,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
{ {
options.AutomaticAuthentication = true; options.AutomaticAuthentication = true;
options.Events = new JwtBearerEvents() options.Events = new OpenIdConnectBearerEvents()
{ {
OnSecurityTokenReceived = context => OnSecurityTokenReceived = context =>
{ {
@ -150,7 +150,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
{ {
options.AutomaticAuthentication = true; options.AutomaticAuthentication = true;
options.Events = new JwtBearerEvents() options.Events = new OpenIdConnectBearerEvents()
{ {
OnSecurityTokenValidated = context => OnSecurityTokenValidated = context =>
{ {
@ -187,7 +187,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
{ {
options.AutomaticAuthentication = true; options.AutomaticAuthentication = true;
options.Events = new JwtBearerEvents() options.Events = new OpenIdConnectBearerEvents()
{ {
OnMessageReceived = context => OnMessageReceived = context =>
{ {
@ -224,7 +224,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
{ {
var server = CreateServer(options => var server = CreateServer(options =>
{ {
options.Events = new JwtBearerEvents() options.Events = new OpenIdConnectBearerEvents()
{ {
OnSecurityTokenReceived = context => OnSecurityTokenReceived = context =>
{ {
@ -255,7 +255,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
{ {
var server = CreateServer(options => var server = CreateServer(options =>
{ {
options.Events = new JwtBearerEvents() options.Events = new OpenIdConnectBearerEvents()
{ {
OnSecurityTokenReceived = context => OnSecurityTokenReceived = context =>
{ {
@ -323,13 +323,13 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
} }
} }
private static TestServer CreateServer(Action<JwtBearerOptions> configureOptions, Func<HttpContext, bool> handler = null) private static TestServer CreateServer(Action<OpenIdConnectBearerOptions> configureOptions, Func<HttpContext, bool> handler = null)
{ {
return TestServer.Create(app => return TestServer.Create(app =>
{ {
if (configureOptions != null) if (configureOptions != null)
{ {
app.UseJwtBearerAuthentication(configureOptions); app.UseOpenIdConnectBearerAuthentication(configureOptions);
} }
app.Use(async (context, next) => app.Use(async (context, next) =>
@ -359,17 +359,17 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
else if (context.Request.Path == new PathString("/unauthorized")) else if (context.Request.Path == new PathString("/unauthorized"))
{ {
// Simulate Authorization failure // Simulate Authorization failure
var result = await context.Authentication.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme); var result = await context.Authentication.AuthenticateAsync(OpenIdConnectBearerDefaults.AuthenticationScheme);
await context.Authentication.ChallengeAsync(JwtBearerDefaults.AuthenticationScheme); await context.Authentication.ChallengeAsync(OpenIdConnectBearerDefaults.AuthenticationScheme);
} }
else if (context.Request.Path == new PathString("/signIn")) else if (context.Request.Path == new PathString("/signIn"))
{ {
await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignInAsync(JwtBearerDefaults.AuthenticationScheme, new ClaimsPrincipal())); await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignInAsync(OpenIdConnectBearerDefaults.AuthenticationScheme, new ClaimsPrincipal()));
} }
else if (context.Request.Path == new PathString("/signOut")) else if (context.Request.Path == new PathString("/signOut"))
{ {
await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignOutAsync(JwtBearerDefaults.AuthenticationScheme)); await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignOutAsync(OpenIdConnectBearerDefaults.AuthenticationScheme));
} }
else else
{ {

View File

@ -33,7 +33,7 @@ namespace Microsoft.AspNet.Authentication.Tests.MicrosoftAccount
options.ClientSecret = "Test Client Secret"; options.ClientSecret = "Test Client Secret";
options.Events = new OAuthEvents options.Events = new OAuthEvents
{ {
OnApplyRedirect = context => OnRedirectToAuthorizationEndpoint = context =>
{ {
context.Response.Redirect(context.RedirectUri + "&custom=test"); context.Response.Redirect(context.RedirectUri + "&custom=test");
return Task.FromResult(0); return Task.FromResult(0);
@ -146,7 +146,7 @@ namespace Microsoft.AspNet.Authentication.Tests.MicrosoftAccount
}; };
options.Events = new OAuthEvents options.Events = new OAuthEvents
{ {
OnAuthenticated = context => OnCreatingTicket = context =>
{ {
var refreshToken = context.RefreshToken; var refreshToken = context.RefreshToken;
context.Principal.AddIdentity(new ClaimsIdentity(new Claim[] { new Claim("RefreshToken", refreshToken, ClaimValueTypes.String, "Microsoft") }, "Microsoft")); context.Principal.AddIdentity(new ClaimsIdentity(new Claim[] { new Claim("RefreshToken", refreshToken, ClaimValueTypes.String, "Microsoft") }, "Microsoft"));

View File

@ -4,7 +4,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IdentityModel.Tokens; using System.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt; using System.IdentityModel.Tokens.OpenIdConnect;
using System.Linq; using System.Linq;
using System.Net.Http; using System.Net.Http;
using System.Security.Claims; using System.Security.Claims;
@ -26,8 +26,8 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
/// </summary> /// </summary>
public class OpenIdConnectHandlerTests public class OpenIdConnectHandlerTests
{ {
private const string nonceForJwt = "abc"; private const string nonceForOpenIdConnect = "abc";
private static SecurityToken specCompliantJwt = new JwtSecurityToken("issuer", "audience", new List<Claim> { new Claim("iat", EpochTime.GetIntDate(DateTime.UtcNow).ToString()), new Claim("nonce", nonceForJwt) }, DateTime.UtcNow, DateTime.UtcNow + TimeSpan.FromDays(1)); private static SecurityToken specCompliantOpenIdConnect = new OpenIdConnectSecurityToken("issuer", "audience", new List<Claim> { new Claim("iat", EpochTime.GetIntDate(DateTime.UtcNow).ToString()), new Claim("nonce", nonceForOpenIdConnect) }, DateTime.UtcNow, DateTime.UtcNow + TimeSpan.FromDays(1));
private const string ExpectedStateParameter = "expectedState"; private const string ExpectedStateParameter = "expectedState";
/// <summary> /// <summary>

View File

@ -25,7 +25,7 @@ namespace Microsoft.AspNet.Authentication.Twitter
options.ConsumerSecret = "Test Consumer Secret"; options.ConsumerSecret = "Test Consumer Secret";
options.Events = new TwitterEvents options.Events = new TwitterEvents
{ {
OnApplyRedirect = context => OnRedirectToAuthorizationEndpoint = context =>
{ {
context.Response.Redirect(context.RedirectUri + "&custom=test"); context.Response.Redirect(context.RedirectUri + "&custom=test");
return Task.FromResult(0); return Task.FromResult(0);

View File

@ -6,7 +6,7 @@
"Microsoft.AspNet.Authentication.Cookies": "1.0.0-*", "Microsoft.AspNet.Authentication.Cookies": "1.0.0-*",
"Microsoft.AspNet.Authentication.Facebook": "1.0.0-*", "Microsoft.AspNet.Authentication.Facebook": "1.0.0-*",
"Microsoft.AspNet.Authentication.Google": "1.0.0-*", "Microsoft.AspNet.Authentication.Google": "1.0.0-*",
"Microsoft.AspNet.Authentication.JwtBearer": "1.0.0-*", "Microsoft.AspNet.Authentication.OpenIdConnectBearer": "1.0.0-*",
"Microsoft.AspNet.Authentication.MicrosoftAccount": "1.0.0-*", "Microsoft.AspNet.Authentication.MicrosoftAccount": "1.0.0-*",
"Microsoft.AspNet.Authentication.OpenIdConnect": "1.0.0-*", "Microsoft.AspNet.Authentication.OpenIdConnect": "1.0.0-*",
"Microsoft.AspNet.Authentication.Twitter": "1.0.0-*", "Microsoft.AspNet.Authentication.Twitter": "1.0.0-*",