This commit is contained in:
Hao Kung 2015-09-21 14:56:05 -07:00
Родитель 081577e4f4
Коммит 59ccbdd8ca
68 изменённых файлов: 200 добавлений и 417 удалений

Просмотреть файл

@ -1,8 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<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="AzureAD" value="http://www.myget.org/F/azureadwebstacknightly"/>
<add key="AzureAD" value="http://www.myget.org/F/azureadwebstacknightly" />
</packageSources>
</configuration>

Просмотреть файл

@ -40,7 +40,7 @@ Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNet.Authentica
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}"
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
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

Просмотреть файл

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

Просмотреть файл

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

Просмотреть файл

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

Просмотреть файл

@ -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
/// to the client. This can be used to mitigate potential problems with very large identities.
/// </summary>
public IAuthenticationSessionStore SessionStore { get; set; }
public ITicketStore SessionStore { get; set; }
CookieAuthenticationOptions IOptions<CookieAuthenticationOptions>.Value
{

Просмотреть файл

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

Просмотреть файл

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

Просмотреть файл

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

Просмотреть файл

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

Просмотреть файл

@ -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.
/// </summary>
/// <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>
/// Called when an endpoint has provided sign in information after it is converted into a cookie.
/// </summary>
/// <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>
/// 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.
/// </summary>
/// <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>
/// Called when an exception occurs during request or response processing.

Просмотреть файл

@ -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
/// issues with serializing large identities into cookies.
/// </summary>
public interface IAuthenticationSessionStore
public interface ITicketStore
{
/// <summary>
/// Store the identity ticket and return the associated key.

Просмотреть файл

@ -62,7 +62,7 @@ namespace Microsoft.AspNet.Authentication.Facebook
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,
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));
}
await Options.Events.Authenticated(context);
await Options.Events.CreatingTicket(context);
return new AuthenticationTicket(context.Principal, context.Properties, context.Options.AuthenticationScheme);
}

Просмотреть файл

@ -32,7 +32,7 @@ namespace Microsoft.AspNet.Authentication.Google
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,
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));
}
await Options.Events.Authenticated(context);
await Options.Events.CreatingTicket(context);
return new AuthenticationTicket(context.Principal, context.Properties, context.Options.AuthenticationScheme);
}

Просмотреть файл

@ -3,11 +3,11 @@
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)
{
}

Просмотреть файл

@ -4,11 +4,11 @@
using System;
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)
{
}

Просмотреть файл

@ -4,14 +4,14 @@
using System.Threading.Tasks;
/// <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>
namespace Microsoft.AspNet.Authentication.JwtBearer
namespace Microsoft.AspNet.Authentication.OpenIdConnectBearer
{
/// <summary>
/// Jwt bearer token middleware events.
/// OpenIdConnect bearer token middleware events.
/// </summary>
public interface IJwtBearerEvents
public interface IOpenIdConnectBearerEvents
{
/// <summary>
/// Invoked if exceptions are thrown during request processing. The exceptions will be re-thrown after this event unless suppressed.

Просмотреть файл

@ -3,11 +3,11 @@
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)
{
}

Просмотреть файл

@ -6,14 +6,14 @@ using System.Threading.Tasks;
using Microsoft.AspNet.Http;
/// <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>
namespace Microsoft.AspNet.Authentication.JwtBearer
namespace Microsoft.AspNet.Authentication.OpenIdConnectBearer
{
/// <summary>
/// Jwt bearer token middleware events.
/// OpenIdConnect bearer token middleware events.
/// </summary>
public class JwtBearerEvents : IJwtBearerEvents
public class OpenIdConnectBearerEvents : IOpenIdConnectBearerEvents
{
/// <summary>
/// Invoked if exceptions are thrown during request processing. The exceptions will be re-thrown after this event unless suppressed.

Просмотреть файл

@ -3,11 +3,11 @@
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)
{
}

Просмотреть файл

@ -3,11 +3,11 @@
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)
{
}

Просмотреть файл

@ -2,16 +2,16 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.Authentication.JwtBearer;
using Microsoft.AspNet.Authentication.OpenIdConnectBearer;
using Microsoft.Framework.Internal;
using Microsoft.Framework.OptionsModel;
namespace Microsoft.AspNet.Builder
{
/// <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>
public static class JwtBearerAppBuilderExtensions
public static class OpenIdConnectBearerAppBuilderExtensions
{
/// <summary>
/// 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="options">Options which control the processing of the bearer header.</param>
/// <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>
@ -40,14 +40,14 @@ namespace Microsoft.AspNet.Builder
/// <param name="app">The application builder</param>
/// <param name="configureOptions">Used to configure Middleware options.</param>
/// <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)
{
configureOptions(options);
}
return app.UseJwtBearerAuthentication(options);
return app.UseOpenIdConnectBearerAuthentication(options);
}
}
}

Просмотреть файл

@ -1,16 +1,16 @@
// 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.JwtBearer
namespace Microsoft.AspNet.Authentication.OpenIdConnectBearer
{
/// <summary>
/// Default values used by authorization server and bearer authentication.
/// </summary>
public static class JwtBearerDefaults
public static class OpenIdConnectBearerDefaults
{
/// <summary>
/// Default value for AuthenticationScheme property in the JwtBearerAuthenticationOptions and
/// JwtAuthorizationServerOptions.
/// Default value for AuthenticationScheme property in the OpenIdConnectBearerAuthenticationOptions and
/// OpenIdConnectAuthorizationServerOptions.
/// </summary>
public const string AuthenticationScheme = "Bearer";
}

Просмотреть файл

@ -10,9 +10,9 @@ using Microsoft.AspNet.Http.Features.Authentication;
using Microsoft.Framework.Logging;
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;

Просмотреть файл

@ -6,35 +6,34 @@ using System.Net.Http;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.Internal;
using Microsoft.Framework.Logging;
using Microsoft.Framework.OptionsModel;
using Microsoft.Framework.WebEncoders;
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
namespace Microsoft.AspNet.Authentication.JwtBearer
namespace Microsoft.AspNet.Authentication.OpenIdConnectBearer
{
/// <summary>
/// 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.
/// </summary>
public class JwtBearerMiddleware : AuthenticationMiddleware<JwtBearerOptions>
public class OpenIdConnectBearerMiddleware : AuthenticationMiddleware<OpenIdConnectBearerOptions>
{
/// <summary>
/// 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.
/// </summary>
public JwtBearerMiddleware(
public OpenIdConnectBearerMiddleware(
[NotNull] RequestDelegate next,
[NotNull] ILoggerFactory loggerFactory,
[NotNull] IUrlEncoder encoder,
[NotNull] JwtBearerOptions options)
[NotNull] OpenIdConnectBearerOptions options)
: base(next, options, loggerFactory, encoder)
{
if (Options.Events == null)
{
Options.Events = new JwtBearerEvents();
Options.Events = new OpenIdConnectBearerEvents();
}
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.
/// </summary>
/// <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();
}
}
}

Просмотреть файл

@ -9,19 +9,19 @@ using System.Net.Http;
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
namespace Microsoft.AspNet.Authentication.JwtBearer
namespace Microsoft.AspNet.Authentication.OpenIdConnectBearer
{
/// <summary>
/// Options class provides information needed to control Bearer Authentication middleware behavior
/// </summary>
public class JwtBearerOptions : AuthenticationOptions
public class OpenIdConnectBearerOptions : AuthenticationOptions
{
/// <summary>
/// Creates an instance of bearer authentication options with default values.
/// </summary>
public JwtBearerOptions() : base()
public OpenIdConnectBearerOptions() : base()
{
AuthenticationScheme = JwtBearerDefaults.AuthenticationScheme;
AuthenticationScheme = OpenIdConnectBearerDefaults.AuthenticationScheme;
}
/// <summary>
@ -35,24 +35,24 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
public string Authority { get; set; }
/// <summary>
/// Gets or sets the audience for any received JWT token.
/// Gets or sets the audience for any received OpenIdConnect token.
/// </summary>
/// <value>
/// The expected audience for any received JWT token.
/// The expected audience for any received OpenIdConnect token.
/// </value>
public string Audience { get; set; }
/// <summary>
/// Gets or sets the challenge to put in the "WWW-Authenticate" header.
/// </summary>
public string Challenge { get; set; } = JwtBearerDefaults.AuthenticationScheme;
public string Challenge { get; set; } = OpenIdConnectBearerDefaults.AuthenticationScheme;
/// <summary>
/// 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.
/// </summary>
public IJwtBearerEvents Events { get; set; } = new JwtBearerEvents();
public IOpenIdConnectBearerEvents Events { get; set; } = new OpenIdConnectBearerEvents();
/// <summary>
/// The HttpMessageHandler used to retrieve metadata.

Просмотреть файл

@ -1,5 +1,5 @@
// <auto-generated />
namespace Microsoft.AspNet.Authentication.JwtBearer
namespace Microsoft.AspNet.Authentication.OpenIdConnectBearer
{
using System.Globalization;
using System.Reflection;
@ -8,7 +8,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
internal static class Resources
{
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>
/// The '{0}' option must be provided.

Просмотреть файл

@ -1,6 +1,6 @@
{
"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": {
"type": "git",
"url": "git://github.com/aspnet/security"

Просмотреть файл

@ -28,7 +28,7 @@ namespace Microsoft.AspNet.Authentication.MicrosoftAccount
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,
Principal = new ClaimsPrincipal(identity)
@ -54,7 +54,7 @@ namespace Microsoft.AspNet.Authentication.MicrosoftAccount
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);
}

Просмотреть файл

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

Просмотреть файл

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

Просмотреть файл

@ -14,17 +14,17 @@ namespace Microsoft.AspNet.Authentication.OAuth
/// <summary>
/// Gets or sets the function that is invoked when the Authenticated method is invoked.
/// </summary>
public Func<OAuthAuthenticatedContext, Task> OnAuthenticated { get; set; } = context => Task.FromResult(0);
public Func<OAuthCreatingTicketContext, Task> OnCreatingTicket { get; set; } = context => Task.FromResult(0);
/// <summary>
/// Gets or sets the function that is invoked when the ReturnEndpoint method is invoked.
/// </summary>
public Func<OAuthReturnEndpointContext, Task> OnReturnEndpoint { get; set; } = context => Task.FromResult(0);
public Func<SigningInContext, Task> OnSigningIn { get; set; } = context => Task.FromResult(0);
/// <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>
public Func<OAuthApplyRedirectContext, Task> OnApplyRedirect { get; set; } = context =>
public Func<OAuthRedirectToAuthorizationEndpointContext, Task> OnRedirectToAuthorizationEndpoint { get; set; } = context =>
{
context.Response.Redirect(context.RedirectUri);
return Task.FromResult(0);
@ -35,19 +35,19 @@ namespace Microsoft.AspNet.Authentication.OAuth
/// </summary>
/// <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>
public virtual Task Authenticated(OAuthAuthenticatedContext context) => OnAuthenticated(context);
public virtual Task CreatingTicket(OAuthCreatingTicketContext context) => OnCreatingTicket(context);
/// <summary>
/// Invoked prior to the <see cref="ClaimsIdentity"/> being saved in a local cookie and the browser being redirected to the originally requested URL.
/// </summary>
/// <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>
public virtual Task ReturnEndpoint(OAuthReturnEndpointContext context) => OnReturnEndpoint(context);
public virtual Task SigningIn(SigningInContext context) => OnSigningIn(context);
/// <summary>
/// Called when a Challenge causes a redirect to authorize endpoint in the OAuth middleware.
/// </summary>
/// <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);
}
}

Просмотреть файл

@ -7,9 +7,9 @@ using Microsoft.AspNet.Http.Authentication;
namespace Microsoft.AspNet.Authentication.OAuth
{
/// <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>
public class OAuthApplyRedirectContext : BaseContext<OAuthOptions>
public class OAuthRedirectToAuthorizationEndpointContext : BaseContext<OAuthOptions>
{
/// <summary>
/// Creates a new context object.
@ -17,7 +17,7 @@ namespace Microsoft.AspNet.Authentication.OAuth
/// <param name="context">The HTTP request context.</param>
/// <param name="properties">The authentication properties of the challenge.</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)
{
RedirectUri = redirectUri;

Просмотреть файл

@ -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; }
}
}

Просмотреть файл

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

Просмотреть файл

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

Просмотреть файл

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

Просмотреть файл

@ -72,7 +72,7 @@ namespace Microsoft.AspNet.Authentication.OpenIdConnect
Options.AuthenticationScheme,
"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

Просмотреть файл

@ -15,19 +15,19 @@ namespace Microsoft.AspNet.Authentication.Twitter
/// </summary>
/// <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>
Task Authenticated(TwitterAuthenticatedContext context);
Task CreatingTicket(TwitterCreatingTicketContext context);
/// <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.
/// </summary>
/// <param name="context"></param>
/// <returns>A <see cref="Task"/> representing the completed operation.</returns>
Task ReturnEndpoint(TwitterReturnEndpointContext context);
Task SigningIn(SigningInContext context);
/// <summary>
/// Called when a Challenge causes a redirect to authorize endpoint in the Twitter middleware
/// </summary>
/// <param name="context">Contains redirect URI and <see cref="AuthenticationProperties"/> of the challenge </param>
Task ApplyRedirect(TwitterApplyRedirectContext context);
Task RedirectToAuthorizationEndpoint(TwitterRedirectToAuthorizationEndpointContext context);
}
}

Просмотреть файл

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

Просмотреть файл

@ -14,17 +14,17 @@ namespace Microsoft.AspNet.Authentication.Twitter
/// <summary>
/// Gets or sets the function that is invoked when the Authenticated method is invoked.
/// </summary>
public Func<TwitterAuthenticatedContext, Task> OnAuthenticated { get; set; } = context => Task.FromResult(0);
public Func<TwitterCreatingTicketContext, Task> OnCreatingTicket { get; set; } = context => Task.FromResult(0);
/// <summary>
/// Gets or sets the function that is invoked when the ReturnEndpoint method is invoked.
/// </summary>
public Func<TwitterReturnEndpointContext, Task> OnReturnEndpoint { get; set; } = context => Task.FromResult(0);
public Func<SigningInContext, Task> OnSigningIn { get; set; } = context => Task.FromResult(0);
/// <summary>
/// Gets or sets the delegate that is invoked when the ApplyRedirect method is invoked.
/// </summary>
public Func<TwitterApplyRedirectContext, Task> OnApplyRedirect { get; set; } = context =>
public Func<TwitterRedirectToAuthorizationEndpointContext, Task> OnRedirectToAuthorizationEndpoint { get; set; } = context =>
{
context.Response.Redirect(context.RedirectUri);
return Task.FromResult(0);
@ -35,19 +35,19 @@ namespace Microsoft.AspNet.Authentication.Twitter
/// </summary>
/// <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>
public virtual Task Authenticated(TwitterAuthenticatedContext context) => OnAuthenticated(context);
public virtual Task CreatingTicket(TwitterCreatingTicketContext context) => OnCreatingTicket(context);
/// <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.
/// </summary>
/// <param name="context"></param>
/// <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>
/// Called when a Challenge causes a redirect to authorize endpoint in the Twitter middleware
/// </summary>
/// <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);
}
}

Просмотреть файл

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

Просмотреть файл

@ -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)
{
}
}
}

Просмотреть файл

@ -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; }
}
}

Просмотреть файл

@ -117,13 +117,13 @@ namespace Microsoft.AspNet.Authentication.Twitter
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),
Properties = properties
};
await Options.Events.Authenticated(context);
await Options.Events.CreatingTicket(context);
if (context.Principal?.Identity == null)
{
@ -154,10 +154,10 @@ namespace Microsoft.AspNet.Authentication.Twitter
Response.Cookies.Append(StateCookie, Options.StateDataFormat.Protect(requestToken), cookieOptions);
var redirectContext = new TwitterApplyRedirectContext(
var redirectContext = new TwitterRedirectToAuthorizationEndpointContext(
Context, Options,
properties, twitterAuthenticationEndpoint);
await Options.Events.ApplyRedirect(redirectContext);
await Options.Events.RedirectToAuthorizationEndpoint(redirectContext);
return true;
}
else
@ -177,14 +177,14 @@ namespace Microsoft.AspNet.Authentication.Twitter
return true;
}
var context = new TwitterReturnEndpointContext(Context, model)
var context = new SigningInContext(Context, model)
{
SignInScheme = Options.SignInScheme,
RedirectUri = model.Properties.RedirectUri
};
model.Properties.RedirectUri = null;
await Options.Events.ReturnEndpoint(context);
await Options.Events.SigningIn(context);
if (context.SignInScheme != null && context.Principal != null)
{

Просмотреть файл

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

Просмотреть файл

@ -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);
}
}
}

Просмотреть файл

@ -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; }
}
}

Просмотреть файл

@ -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);
}
}

Просмотреть файл

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

Просмотреть файл

@ -1,6 +1,7 @@
// 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;
using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNet.DataProtection;
@ -10,20 +11,18 @@ namespace Microsoft.AspNet.Authentication
{
private readonly IDataSerializer<TData> _serializer;
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;
_protector = protector;
_encoder = encoder;
}
public string Protect(TData data)
{
byte[] userData = _serializer.Serialize(data);
byte[] protectedData = _protector.Protect(userData);
string protectedText = _encoder.Encode(protectedData);
string protectedText = Base64UrlTextEncoder.Encode(protectedData);
return protectedText;
}
@ -37,7 +36,7 @@ namespace Microsoft.AspNet.Authentication
return default(TData);
}
byte[] protectedData = _encoder.Decode(protectedText);
byte[] protectedData = Base64UrlTextEncoder.Decode(protectedText);
if (protectedData == null)
{
return default(TData);

Просмотреть файл

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

Просмотреть файл

@ -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; }
}
}
}

Просмотреть файл

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

Просмотреть файл

@ -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;
}
}
}

Просмотреть файл

@ -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;
}
}
}

Просмотреть файл

@ -8,9 +8,12 @@ using Microsoft.AspNet.Http.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,
AuthenticationTicket ticket)
: base(context)
@ -25,6 +28,13 @@ namespace Microsoft.AspNet.Authentication
public ClaimsPrincipal Principal { get; set; }
public AuthenticationProperties Properties { get; set; }
public bool IsRequestCompleted { get; private set; }
public void RequestCompleted()
{
IsRequestCompleted = true;
}
public string SignInScheme { get; set; }
[SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Justification = "By design")]

Просмотреть файл

@ -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
}
}

Просмотреть файл

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

Просмотреть файл

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

Просмотреть файл

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

Просмотреть файл

@ -199,7 +199,7 @@ namespace Microsoft.AspNet.Authentication.Google
options.ClientSecret = "Test Secret";
options.Events = new OAuthEvents
{
OnApplyRedirect = context =>
OnRedirectToAuthorizationEndpoint = context =>
{
context.Response.Redirect(context.RedirectUri + "&custom=test");
return Task.FromResult(0);
@ -416,7 +416,7 @@ namespace Microsoft.AspNet.Authentication.Google
};
options.Events = new OAuthEvents
{
OnAuthenticated = context =>
OnCreatingTicket = context =>
{
var refreshToken = context.RefreshToken;
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.Events = new OAuthEvents()
{
OnAuthenticated = context =>
OnCreatingTicket = context =>
{
Assert.NotNull(context.User);
Assert.Equal(context.AccessToken, "Test Access Token");

Просмотреть файл

@ -15,9 +15,9 @@ using Microsoft.AspNet.TestHost;
using Microsoft.Framework.DependencyInjection;
using Xunit;
namespace Microsoft.AspNet.Authentication.JwtBearer
namespace Microsoft.AspNet.Authentication.OpenIdConnectBearer
{
public class JwtBearerMiddlewareTests
public class OpenIdConnectBearerMiddlewareTests
{
[Fact]
public async Task BearerTokenValidation()
@ -27,7 +27,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
options.AutomaticAuthentication = true;
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;
});
@ -66,7 +66,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
{
options.AutomaticAuthentication = true;
options.Events = new JwtBearerEvents()
options.Events = new OpenIdConnectBearerEvents()
{
OnMessageReceived = context =>
{
@ -116,7 +116,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
{
options.AutomaticAuthentication = true;
options.Events = new JwtBearerEvents()
options.Events = new OpenIdConnectBearerEvents()
{
OnSecurityTokenReceived = context =>
{
@ -150,7 +150,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
{
options.AutomaticAuthentication = true;
options.Events = new JwtBearerEvents()
options.Events = new OpenIdConnectBearerEvents()
{
OnSecurityTokenValidated = context =>
{
@ -187,7 +187,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
{
options.AutomaticAuthentication = true;
options.Events = new JwtBearerEvents()
options.Events = new OpenIdConnectBearerEvents()
{
OnMessageReceived = context =>
{
@ -224,7 +224,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
{
var server = CreateServer(options =>
{
options.Events = new JwtBearerEvents()
options.Events = new OpenIdConnectBearerEvents()
{
OnSecurityTokenReceived = context =>
{
@ -255,7 +255,7 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
{
var server = CreateServer(options =>
{
options.Events = new JwtBearerEvents()
options.Events = new OpenIdConnectBearerEvents()
{
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 =>
{
if (configureOptions != null)
{
app.UseJwtBearerAuthentication(configureOptions);
app.UseOpenIdConnectBearerAuthentication(configureOptions);
}
app.Use(async (context, next) =>
@ -359,17 +359,17 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
else if (context.Request.Path == new PathString("/unauthorized"))
{
// Simulate Authorization failure
var result = await context.Authentication.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme);
await context.Authentication.ChallengeAsync(JwtBearerDefaults.AuthenticationScheme);
var result = await context.Authentication.AuthenticateAsync(OpenIdConnectBearerDefaults.AuthenticationScheme);
await context.Authentication.ChallengeAsync(OpenIdConnectBearerDefaults.AuthenticationScheme);
}
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"))
{
await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignOutAsync(JwtBearerDefaults.AuthenticationScheme));
await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignOutAsync(OpenIdConnectBearerDefaults.AuthenticationScheme));
}
else
{

Просмотреть файл

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

Просмотреть файл

@ -4,7 +4,7 @@
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.IdentityModel.Tokens.OpenIdConnect;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
@ -26,8 +26,8 @@ namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
/// </summary>
public class OpenIdConnectHandlerTests
{
private const string nonceForJwt = "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 const string nonceForOpenIdConnect = "abc";
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";
/// <summary>

Просмотреть файл

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

Просмотреть файл

@ -6,7 +6,7 @@
"Microsoft.AspNet.Authentication.Cookies": "1.0.0-*",
"Microsoft.AspNet.Authentication.Facebook": "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.OpenIdConnect": "1.0.0-*",
"Microsoft.AspNet.Authentication.Twitter": "1.0.0-*",