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

HttpSys => Auth 2.0 #354

Closed
wants to merge 8 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
141 changes: 35 additions & 106 deletions src/Microsoft.AspNetCore.Server.HttpSys/AuthenticationHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,148 +4,77 @@
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
{
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))
{
if (identity != null && identity.IsAuthenticated
&& string.Equals(authScheme, identity.AuthenticationType, StringComparison.Ordinal))
{
context.Authenticated(_requestContext.User, properties: null, description: null);
}
else
{
context.NotAuthenticated();
}
}
return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(_requestContext.User, properties: null, authenticationScheme: _scheme.Name)));
Copy link
Member

Choose a reason for hiding this comment

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

Since HttpSys pre-sets HttpContext.User, will AuthZ try to merge this Principal with itself?

Copy link
Member Author

Choose a reason for hiding this comment

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

Merging only happens when multiple schemes are requested for a policy, it doesn't actually merge with anything that already is on context.User either.

}
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;
break;
case ChallengeBehavior.Automatic:
var identity = (ClaimsIdentity)_requestContext.User?.Identity;
if (identity != null && identity.IsAuthenticated)
{
_requestContext.Response.StatusCode = 403;
}
else
{
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)))
{
_requestContext.Response.StatusCode = 403;
context.Accept();
}
else
{
_requestContext.Response.StatusCode = 401;
_customChallenges |= scheme;
context.Accept();
}
break;
default:
throw new NotSupportedException(context.Behavior.ToString());
_requestContext.Response.StatusCode = 401;
}
}
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.");
}

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

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

private IEnumerable<AuthenticationSchemes> ListEnabledAuthSchemes()
{
// Order by strength.
if ((_authSchemes & AuthenticationSchemes.Kerberos) == AuthenticationSchemes.Kerberos)
{
yield return AuthenticationSchemes.Kerberos;
}
if ((_authSchemes & AuthenticationSchemes.Negotiate) == AuthenticationSchemes.Negotiate)
{
yield return AuthenticationSchemes.Negotiate;
}
if ((_authSchemes & AuthenticationSchemes.NTLM) == AuthenticationSchemes.NTLM)
{
yield return AuthenticationSchemes.NTLM;
}
/*if ((_authSchemes & AuthenticationSchemes.Digest) == AuthenticationSchemes.Digest)
{
// TODO:
throw new NotImplementedException("Digest challenge generation has not been implemented.");
yield return AuthenticationSchemes.Digest;
}*/
if ((_authSchemes & AuthenticationSchemes.Basic) == AuthenticationSchemes.Basic)
{
yield return AuthenticationSchemes.Basic;
}
}
}
}
8 changes: 1 addition & 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,7 @@ ClaimsPrincipal IHttpAuthenticationFeature.User
set { _user = value; }
}

IAuthenticationHandler IHttpAuthenticationFeature.Handler
{
get { return _authHandler; }
set { _authHandler = value; }
}
IAuthenticationHandler IHttpAuthenticationFeature.Handler { get; set; }

string IHttpRequestIdentifierFeature.TraceIdentifier
{
Expand Down
13 changes: 13 additions & 0 deletions src/Microsoft.AspNetCore.Server.HttpSys/HttpSysDefaults.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// 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.AspNetCore.Server.HttpSys
{
public static class HttpSysDefaults
{
/// <summary>
/// The name of the authentication scheme used.
/// </summary>
public static readonly string AuthenticationScheme = "Windows";
}
}
10 changes: 8 additions & 2 deletions src/Microsoft.AspNetCore.Server.HttpSys/MessagePump.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Diagnostics.Contracts;
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 +31,7 @@ internal class MessagePump : IServer

private readonly ServerAddressesFeature _serverAddresses;

public MessagePump(IOptions<HttpSysOptions> options, ILoggerFactory loggerFactory)
public MessagePump(IOptions<HttpSysOptions> options, ILoggerFactory loggerFactory, IAuthenticationSchemeProvider authentication)
{
if (options == null)
{
Expand All @@ -40,10 +41,15 @@ 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)
{
authentication.AddScheme(new AuthenticationScheme(HttpSysDefaults.AuthenticationScheme, 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)" />
Copy link
Member

Choose a reason for hiding this comment

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

Why Core and not Abstractions?

Copy link
Member Author

Choose a reason for hiding this comment

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

Moot now that we are going to always AddAuthenticationCore

<PackageReference Include="Microsoft.AspNetCore.Hosting" Version="$(AspNetCoreVersion)" />
<PackageReference Include="Microsoft.Extensions.TaskCache.Sources" Version="$(AspNetCoreVersion)" PrivateAssets="All" />
<PackageReference Include="Microsoft.Net.Http.Headers" Version="$(AspNetCoreVersion)" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public static IWebHostBuilder UseHttpSys(this IWebHostBuilder hostBuilder)
{
return hostBuilder.ConfigureServices(services => {
services.AddSingleton<IServer, MessagePump>();
services.AddAuthenticationCore();
});
}

Expand Down
Loading