Skip to content
This repository was archived by the owner on Mar 19, 2019. It is now read-only.

Prototype Auth 2.0 changes #325

Closed
wants to merge 10 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions global.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{ "sdk": { "version": "2.0.0-preview1-005783" } }
119 changes: 51 additions & 68 deletions src/Microsoft.AspNetCore.Server.HttpSys/AuthenticationHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http.Features.Authentication;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Internal;

namespace Microsoft.AspNetCore.Server.HttpSys
Expand All @@ -16,111 +16,94 @@ internal class AuthenticationHandler : IAuthenticationHandler
private RequestContext _requestContext;
private AuthenticationSchemes _authSchemes;
private AuthenticationSchemes _customChallenges;
private AuthenticationScheme _scheme;

internal AuthenticationHandler(RequestContext requestContext)
{
_requestContext = requestContext;
_authSchemes = requestContext.Response.AuthenticationChallenges;
_customChallenges = AuthenticationSchemes.None;
}

public Task AuthenticateAsync(AuthenticateContext context)
public Task<AuthenticateResult> AuthenticateAsync()
{
var identity = _requestContext.User?.Identity;

foreach (var authType in ListEnabledAuthSchemes())
if (identity != null && identity.IsAuthenticated)
{
var authScheme = authType.ToString();
if (string.Equals(authScheme, context.AuthenticationScheme, StringComparison.Ordinal))
foreach (var scheme in ListEnabledAuthSchemes())
{
if (identity != null && identity.IsAuthenticated
&& string.Equals(authScheme, identity.AuthenticationType, StringComparison.Ordinal))
{
context.Authenticated(_requestContext.User, properties: null, description: null);
}
else
if (string.Equals(scheme.ToString(), identity.AuthenticationType, StringComparison.Ordinal))
{
context.NotAuthenticated();
return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(_requestContext.User, properties: null, authenticationScheme: _scheme.Name)));
}
}
}
return TaskCache.CompletedTask;
return Task.FromResult(AuthenticateResult.None());
}

public Task ChallengeAsync(ChallengeContext context)
{
var automaticChallenge = string.Equals("Automatic", context.AuthenticationScheme, StringComparison.Ordinal);
foreach (var scheme in ListEnabledAuthSchemes())
switch (context.Behavior)
{
var authScheme = scheme.ToString();
// Not including any auth types means it's a blanket challenge for any auth type.
if (automaticChallenge || string.Equals(context.AuthenticationScheme, authScheme, StringComparison.Ordinal))
{
switch (context.Behavior)
case ChallengeBehavior.Forbidden:
_requestContext.Response.StatusCode = 403;
break;
case ChallengeBehavior.Unauthorized:
_requestContext.Response.StatusCode = 401;
foreach (var scheme in ListEnabledAuthSchemes())
{
case ChallengeBehavior.Forbidden:
_requestContext.Response.StatusCode = 403;
context.Accept();
break;
case ChallengeBehavior.Unauthorized:
_requestContext.Response.StatusCode = 401;
_customChallenges |= scheme;
context.Accept();
break;
case ChallengeBehavior.Automatic:
var identity = (ClaimsIdentity)_requestContext.User?.Identity;
if (identity != null && identity.IsAuthenticated
&& (automaticChallenge || string.Equals(identity.AuthenticationType, context.AuthenticationScheme, StringComparison.Ordinal)))
_customChallenges |= scheme;
}
break;
case ChallengeBehavior.Automatic:
var identity = (ClaimsIdentity)_requestContext.User?.Identity;
if (identity != null && identity.IsAuthenticated)
{
foreach (var scheme in ListEnabledAuthSchemes())
{
if (string.Equals(identity.AuthenticationType, scheme.ToString(), StringComparison.Ordinal))
{
_requestContext.Response.StatusCode = 403;
context.Accept();
}
else
{
_requestContext.Response.StatusCode = 401;
_customChallenges |= scheme;
context.Accept();
break;
}
break;
default:
throw new NotSupportedException(context.Behavior.ToString());
}
}
}
else
{
_requestContext.Response.StatusCode = 401;
foreach (var scheme in ListEnabledAuthSchemes())
{
_customChallenges |= scheme;
}
}
break;
default:
throw new NotSupportedException(context.Behavior.ToString());
}

// A challenge was issued, it overrides any pre-set auth types.
_requestContext.Response.AuthenticationChallenges = _customChallenges;
return TaskCache.CompletedTask;
}

public void GetDescriptions(DescribeSchemesContext context)
public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context)
{
// TODO: Caching, this data doesn't change per request.
foreach (var scheme in ListEnabledAuthSchemes())
_scheme = scheme;
_requestContext = context.Features.Get<RequestContext>();

if (_requestContext == null)
{
context.Accept(GetDescription(scheme.ToString()));
throw new InvalidOperationException("No RequestContext found.");
}

_authSchemes = _requestContext.Response.AuthenticationChallenges;
_customChallenges = AuthenticationSchemes.None;
return TaskCache.CompletedTask;
}

public Task SignInAsync(SignInContext context)
{
// Not supported. AuthenticationManager will throw if !Accepted.
return TaskCache.CompletedTask;
throw new NotSupportedException();
}

public Task SignOutAsync(SignOutContext context)
{
// Not supported. AuthenticationManager will throw if !Accepted.
return TaskCache.CompletedTask;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These comments about !Accepted aren't true anymore. SignIn should throw NotSupportedException. SignOut is something we're discussing elsewhere.

}

private IDictionary<string, object> GetDescription(string authenticationScheme)
{
return new Dictionary<string, object>()
{
{ "AuthenticationScheme", authenticationScheme },
};
}

private IEnumerable<AuthenticationSchemes> ListEnabledAuthSchemes()
{
// Order by strength.
Expand Down
9 changes: 2 additions & 7 deletions src/Microsoft.AspNetCore.Server.HttpSys/FeatureContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ internal class FeatureContext :
private string _traceIdentitfier;
private X509Certificate2 _clientCert;
private ClaimsPrincipal _user;
private IAuthenticationHandler _authHandler;
private CancellationToken _disconnectToken;
private Stream _responseStream;
private IHeaderDictionary _responseHeaders;
Expand All @@ -68,7 +67,6 @@ internal FeatureContext(RequestContext requestContext, bool enableResponseCachin
{
_requestContext = requestContext;
_features = new FeatureCollection(new StandardFeatureCollection(this));
_authHandler = new AuthenticationHandler(requestContext);
_enableResponseCaching = enableResponseCaching;

// Pre-initialize any fields that are not lazy at the lower level.
Expand Down Expand Up @@ -446,11 +444,8 @@ ClaimsPrincipal IHttpAuthenticationFeature.User
set { _user = value; }
}

IAuthenticationHandler IHttpAuthenticationFeature.Handler
{
get { return _authHandler; }
set { _authHandler = value; }
}
[Obsolete("See https://go.microsoft.com/fwlink/?linkid=845470")]
IAuthenticationHandler IHttpAuthenticationFeature.Handler { get; set; }

string IHttpRequestIdentifierFeature.TraceIdentifier
{
Expand Down
18 changes: 16 additions & 2 deletions src/Microsoft.AspNetCore.Server.HttpSys/MessagePump.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Http.Features;
Expand All @@ -30,7 +33,7 @@ internal class MessagePump : IServer

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For this to work UseHttpSysServer has to register the service?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well maybe AddAuthentication needs to be added as part of hosting similar to options, its kinda required...

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's required for HttpSysServer, but only if auth is enabled. Same for IIS Integration. There are plenty of apps that don't need it though.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably need to factor the new auth stuff into the 'core stuff' (and the security base class stuff). Hosting should add the core stuff so everyone can add schemes...

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Resolve it as optional?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this mimics how anyone could hook their own IAuthenticationHandler on httpContext today, its always there today

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well do we really want context.AuthenticateAsync to throw due to no service found if AddAuthentication isn't called?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds fine. Why Authenticate without Authentication?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok so we are leaving it as an exercise for the user to ensure something is calling AddAuthentication, MVC/identity will do this, as well as all of our security projects

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated to resolve IAuthenticationSchemeProvider as enumerable and only throw if AuthentionSchemes for the server options is not none.

private readonly ServerAddressesFeature _serverAddresses;

public MessagePump(IOptions<HttpSysOptions> options, ILoggerFactory loggerFactory)
public MessagePump(IOptions<HttpSysOptions> options, ILoggerFactory loggerFactory, IEnumerable<IAuthenticationSchemeProvider> authentication)
{
if (options == null)
{
Expand All @@ -40,10 +43,21 @@ public MessagePump(IOptions<HttpSysOptions> options, ILoggerFactory loggerFactor
{
throw new ArgumentNullException(nameof(loggerFactory));
}

_options = options.Value;
Listener = new HttpSysListener(_options, loggerFactory);
_logger = LogHelper.CreateLogger(loggerFactory, typeof(MessagePump));

if (_options.Authentication.Schemes != AuthenticationSchemes.None)
{
var auth = authentication.FirstOrDefault();
if (auth == null)
{
throw new InvalidOperationException("AddAuthentication() is required to use Authentication.");
}

auth.AddScheme(new AuthenticationScheme("Windows", displayName: null, handlerType: typeof(AuthenticationHandler)));
}

Features = new FeatureCollection();
_serverAddresses = new ServerAddressesFeature();
Features.Set<IServerAddressesFeature>(_serverAddresses);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.Core" Version="$(AspNetCoreVersion)" />
<PackageReference Include="Microsoft.AspNetCore.Hosting" Version="$(AspNetCoreVersion)" />
<PackageReference Include="Microsoft.Extensions.RuntimeEnvironment.Sources" Version="$(AspNetCoreVersion)" PrivateAssets="All" />
<PackageReference Include="Microsoft.Extensions.TaskCache.Sources" Version="$(AspNetCoreVersion)" PrivateAssets="All" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Server.HttpSys;
using Microsoft.Extensions.DependencyInjection;
Expand Down
Loading