Giter Club home page Giter Club logo

security's People

Contributors

ajaybhargavb avatar aspnetci avatar bchavez avatar brennanconroy avatar brentschmaltz avatar bricelam avatar chengtian avatar davidfowl avatar dougbu avatar eilon avatar grabyourpitchforks avatar halter73 avatar haok avatar hishamco avatar javiercn avatar jkotalik avatar juntaoluo avatar kevinchalet avatar kichalla avatar mikeharder avatar muratg avatar natemcmaster avatar ntaylormullen avatar pakrym avatar pranavkm avatar ryanbrandenburg avatar sebastienros avatar tratcher avatar troydai avatar tushargupta51 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

security's Issues

Provide a default value for OAuthAuthenticationOptions.Notifications to avoid NRE exceptions

This commit introduced a regression: 3426034

Now, if you don't explicitly provide an instance for OAuthAuthenticationOptions.Notifications, none is automatically created by OAuthAuthenticationExtensions and a NRE occurs when the MW tries to trigger a notification.

https://github.com/aspnet/Security/blob/51c3dc98dc08a1e4a761bb77469a45b3b33271c2/src/Microsoft.AspNet.Security.OAuth/OAuthAuthenticationExtensions.cs
https://github.com/aspnet/Security/blob/dev/src/Microsoft.AspNet.Security.OAuth/OAuthAuthenticationExtensions.cs

Use more DI for Cookie options

ICookieManager, IAuthenticationSessionStore, INotifications should all provide something like:

    //options.UseNotification<GoogleAuthenticationNotifications>();
    //options.UseNotification(new GoogleAuthenticationNotifications());
    //options.UseNotification(services => return google);

Also Consider wrapping this pattern in some sugar struct

[Work around for mono]: ClaimsIdentity constructor used by TokenSerializer.Read is broken in mono

https://github.com/aspnet/Security/blob/dev/src/Microsoft.AspNet.Security/DataHandler/Serializer/TicketSerializer.cs#L89

public static AuthenticationTicket Read([NotNull] BinaryReader reader)
        {
            if (reader.ReadInt32() != FormatVersion)
            {
                return null;
            }

            string authenticationType = reader.ReadString();
            string nameClaimType = ReadWithDefault(reader, DefaultValues.NameClaimType);
            string roleClaimType = ReadWithDefault(reader, DefaultValues.RoleClaimType);
            int count = reader.ReadInt32();
            var claims = new Claim[count];
            for (int index = 0; index != count; ++index)
            {
                string type = ReadWithDefault(reader, nameClaimType);
                string value = reader.ReadString();
                string valueType = ReadWithDefault(reader, DefaultValues.StringValueType);
                string issuer = ReadWithDefault(reader, DefaultValues.LocalAuthority);
                string originalIssuer = ReadWithDefault(reader, issuer);
                claims[index] = new Claim(type, value, valueType, issuer, originalIssuer);
            }
            var identity = new ClaimsIdentity(claims, authenticationType, nameClaimType, roleClaimType); <--This constructor does not work. 
            var properties = PropertiesSerializer.Read(reader);
            return new AuthenticationTicket(identity, properties);
        }
var identity = new ClaimsIdentity(claims, authenticationType, nameClaimType, roleClaimType); <--This constructor does not work. 

When this constructor is used to pass in the claims, the claims are lost on mono. Until this bug is fixed in Mono can we apply a temporary work around for mono conditionally like below?

var identity = new ClaimsIdentity(authenticationType, nameClaimType, roleClaimType);
foreach (var claim in claims)
{
    identity.AddClaim(claim);
}

Abstract ApplyResponseGrant and ApplyResponseChallenge in AuthenticationHandler

ApplyResponseGrant and ApplyResponseChallenge methods in AuthenticationHandler are abstract and this means the derived authentication handler is forced to implement them, regardless of the usage. I'm overriding ApplyResponseCoreAsync and to me, these two methods are not needed. Even otherwise, every authentication handler need not implement these. Virtual methods with a default implementation will be nice, since I don't need to write those few lines myself. Those who want can override.

On Helios Cookies middleware does not do a 302 on Challenge

On Helios doing a Challenge - Cookies middleware does not automatically redirect (HTTP status 302) to the registered login path.

Repro code below:

var serviceCollection = new ServiceCollection();
        serviceCollection.AddInstance<ILoggerFactory>(new NullLoggerFactory());
        var serviceProvider = serviceCollection.BuildServiceProvider(app.ServiceProvider);
        app.UseContainer(serviceProvider);

app.UseCookieAuthentication(new CookieAuthenticationOptions()
        {
            AuthenticationMode = AuthenticationMode.Active,
            AuthenticationType = "Application",
            LoginPath = new PathString("/Account/Login")
        });

        app.Run(context =>
            {
                if (context.Request.Path.Value.Contains("/Account/Login"))
                {
                    return context.Response.WriteAsync("Login page");
                }
                else
                {
                    context.Response.Challenge("Application");
                    //context.Response.StatusCode = 401;
                    return context.Response.WriteAsync("Authenticate..");
                }
            });

    private class NullLoggerFactory : ILoggerFactory
    {

        public ILogger Create(string name)
        {
            return new NullLongger();
        }
    }

    private class NullLongger : ILogger
    {
        public bool WriteCore(TraceType eventType, int eventId, object state, Exception exception, Func<object, Exception, string> formatter)
        {
            return false;
        }
    }

Google: Need better way to discover when google+ api not enabled

It would be helpful for the google middleware to handle the situation where just the google+ me request fails. Currently today this results in a 403, which is caught and swallowed. OnAuthenticated isn't called, and I had to debug into sources to see that it was the google plus me request failing here:

            // Get the Google user
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, UserInfoEndpoint);
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            HttpResponseMessage graphResponse = await _httpClient.SendAsync(request, Context.RequestAborted);
            graphResponse.EnsureSuccessStatusCode();

Do we need some kind of error callback? Instead of just getting called back with a null Identity in the authentication result?

Add support for HTTP Strict Transport Security

Continuing discussion from aspnet/Mvc#744 (comment)

I would like to propose adding an HTTP Strict Transport Security (HSTS) attribute into the core of ASP.NET. According to OWASP, HTTP Strict Transport Security (HSTS) protects users from a number of threats, in particular man-in-the-middle attacks by not only forcing encrypted sessions, but also stopping attackers who use invalid digital certificates.

Although developers can write middleware themselves, I believe a fully test implementation would be a benefit and prevent inconsistencies within developer code (for example, developers may overlook the ability to add the sub domains suffix).

Following the advice of the previously mentioned thread, I have created a NuGet package with a test implementation here, with the project site be located here.

If you think that this feature would add value, I will happily submit the code via a PR.

cc/ @yishaigalatzer

Port serialization for BootstrapContext. Make sure to increment TicketSerializer.FormatVersion.

Recent changes made in Katana to support BootstrapContext have not been ported yet to vNext. When porting them, make sure to increment TicketSerializer.FormatVersion to avoid this kind of issue: https://katanaproject.codeplex.com/workitem/347

Associated topic: https://katanaproject.codeplex.com/discussions/566815

Symptoms: tickets (and by extension, cookies) created by Katana 2.1 are not correctly deserialized under Katana 3 and lack the AuthenticationProperties element. This causes critical properties like IssuedUtc or ExpiresUtc to be absent from the final ticket. As a result, non-persistent cookies never expire.

Root cause: when Brent Schmaltz added BootstrapContext support in TicketSerializer (https://katanaproject.codeplex.com/SourceControl/changeset/87f2be297e5b24cbbc2627cc5cac2ded41ddf822), he forgot to increment the version number to make sure tickets serialized before this change were ignored.

Explanation: when TicketSerializer tries to read old tickets, the new reader.ReadInt32() call inserted in TicketSerializer.Read makes the binary serializer going further than expected by trying to read an element that was not present in the serialized payload. Next line, when PropertiesSerializer.Read is called to deserialize the AuthenticationProperties, BinaryReader fails to read the correct version number associated with PropertiesSerializer, which causes the ticket to be returned without its AuthenticationProperties companion.

Solution: increment TicketSerializer.FormatVersion to make sure TicketSerializer won't try to deserialize incompatible tickets. This change will make every existing ticket/cookie unreadable. As a consequence, users would have to re-authenticate. In the meantime, end devs can implement their own TicketSerializer and fix this issue by incrementing the version number.

Port the JWT & AAD middleware from Katana

Depends on #39 (OAuth) and System.IdentityModel.Tokens.Jwt.

We'll need to re-work the IIssuerSecurityTokenProvider to use the new ConfigurationManager for retrieving metadata (See WsFederation).

For AAD, also fix #25

IAuthorizationService.Authorize should have an overload that accepts a single claim

There is no overload that accepts a single claim. Most of the times, in my code, I only check for a single claim. It would be nice to have an overload that doesn't require a collection (or at least make it params).

Same applies for AuthorizeAsync

Today's overloads:

    public interface IAuthorizationService
    {
        bool Authorize(IEnumerable<Claim> claims, ClaimsPrincipal user);
        bool Authorize(IEnumerable<Claim> claims, ClaimsPrincipal user, object resource);
        Task<bool> AuthorizeAsync(IEnumerable<Claim> claims, ClaimsPrincipal user);
        Task<bool> AuthorizeAsync(IEnumerable<Claim> claims, ClaimsPrincipal user, object resource);
    }

cc @sebastienros

Rationalize error handling

The original batch of social auth middleware (Facebook, Twitter, etc.) all swallowed exceptions. The second round (WsFed, ODIC) notified you (AuthenticationFailedNotification) and threw them. These should be rationalized.

Also, consider getting rid of EnsureSuccessStatusCode and offering a more useful error reporting by trying to build an exception using the JSON error payload when content type=app/json.

Exception when using the new DI activated options style cookie auth

After updating to newest security packages, I get the following exception:

System.AggregateException: One or more errors occurred ---> System.ArgumentNullException: Argument cannot be null.
Parameter name: provider
  at Microsoft.Framework.DependencyInjection.ServiceProviderExtensions.GetService[ILoggerFactory] (IServiceProvider provider) [0x00000] in <filename unknown>:0 
  at Microsoft.AspNet.Builder.RouterMiddleware.EnsureLogger (Microsoft.AspNet.Http.HttpContext context) [0x00000] in <filename unknown>:0 
  at Microsoft.AspNet.Builder.RouterMiddleware+<Invoke>d__1.MoveNext () [0x00000] in <filename unknown>:0 
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x00000] in <filename unknown>:0 
  at System.Runtime.CompilerServices.TaskAwaiter.GetResult () [0x00000] in <filename unknown>:0 
  at Microsoft.AspNet.Security.Infrastructure.AuthenticationMiddleware`1+<Invoke>d__1[Microsoft.AspNet.Security.Cookies.CookieAuthenticationOptions].MoveNext () [0x00000] in <filename unknown>:0 
  --- End of inner exception stack trace ---
 --> (Inner exception 0) System.ArgumentNullException: Argument cannot be null.
Parameter name: provider
  at Microsoft.Framework.DependencyInjection.ServiceProviderExtensions.GetService[ILoggerFactory] (IServiceProvider provider) [0x00000] in <filename unknown>:0 
  at Microsoft.AspNet.Builder.RouterMiddleware.EnsureLogger (Microsoft.AspNet.Http.HttpContext context) [0x00000] in <filename unknown>:0 
  at Microsoft.AspNet.Builder.RouterMiddleware+<Invoke>d__1.MoveNext () [0x00000] in <filename unknown>:0 
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x00000] in <filename unknown>:0 
  at System.Runtime.CompilerServices.TaskAwaiter.GetResult () [0x00000] in <filename unknown>:0 
  at Microsoft.AspNet.Security.Infrastructure.AuthenticationMiddleware`1+<Invoke>d__1[Microsoft.AspNet.Security.Cookies.CookieAuthenticationOptions].MoveNext () [0x00000] in <filename unknown>:0 

Authentication middleware fails on CoreCLR

While trying to authenticate a user using Google authentication, the Google middleware throws this exception. This seems like an issue with HttpClient which is possible to happen with all external middlewares.

System.ObjectDisposedException occurred
  HResult=-2146232798
  Message=Safe handle has been closed
  Source=mscorlib
  ObjectName=""
  StackTrace:
       at System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean& success)
       at System.StubHelpers.StubHelpers.SafeHandleAddRef(SafeHandle pHandle, Boolean& success)
       at System.Net.Http.Interop.WinHttpSetOption(SafeInternetHandle handle, UInt32 option, UInt32& optionData, UInt32 optionLength)
       at System.Net.Http.WinHttpHandler.SetWinHttpOption(SafeInternetHandle handle, UInt32 option, UInt32& optionData)
       at System.Net.Http.WinHttpHandler.SetSessionHandleConnectionOptions()
       at System.Net.Http.WinHttpHandler.SetSessionHandleOptions()
       at System.Net.Http.WinHttpHandler.<StartRequest>d__1.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
       at Microsoft.AspNet.Security.Google.GoogleAuthenticationHandler.<GetUserInformationAsync>d__1.MoveNext() in d:\K\Security\src\Microsoft.AspNet.Security.Google\GoogleAuthenticationHandler.cs:line 30
  InnerException: 

@Tratcher

Replace any Task.Result calls with Task.GetAwaiter().GetResult()

There are several places where the auth handler has a sync and an async code path, but the sync path must call the async path and block (Task.Wait/Result).

"One last remark: you should avoid using Task.Result and Task.Wait as much as possible as they always encapsulate the inner exception in an AggregateException and replace the message by a generic one (One or more errors occurred), which makes debugging harder. Even if the synchronous version shouldn't be used that often, you should strongly consider using Task.GetAwaiter().GetResult() instead." - Pinpoint

Middleware backchannels should set User-Agent

Many of the security middleware have HttpClient instances they use for back-channel communication. Each middleware that does this should set the User-Agent header to facilitate tracking and debugging.

Recommended pattern: "ASP.NET Security (Twitter)"

Clean up notification extensibility model

The original batch of social auth middleware (Facebook, Twitter, etc.) all used three different extensibility models for their notifications (formerly Providers). There was an I*AuthenticationProvider interface with methods and a _AuthenticationProvider class defining both virtual methods to be overridden and On_ settable delegates. The second round (WsFed, ODIC) got rid of the interface and virtual methods, leaving only the settable delegates. Note you could still derive from the notification class, you would just need to set the delegates in your constructor.

Some methods in IAuthorizationService should be moved to extension methods

As @Eilon suggested, the overloads without a resource should be extension methods rather than methods on the interface. In most of the cases, whoever implements this service will just call the overload with the resource parameter with a "null" value.

namespace Microsoft.AspNet.Security.Authorization
{
    public interface IAuthorizationService
    {
        bool Authorize(IEnumerable<Claim> claims, ClaimsPrincipal user);
        bool Authorize(IEnumerable<Claim> claims, ClaimsPrincipal user, object resource);
        Task<bool> AuthorizeAsync(IEnumerable<Claim> claims, ClaimsPrincipal user);
        Task<bool> AuthorizeAsync(IEnumerable<Claim> claims, ClaimsPrincipal user, object resource);
    }
}

Consider using PathBase for CookiePath

"/" is used to by default in the CookieAuthenticationOptions ctor, but this causes issues (cookies exposed unnecessarily to other parts of the server). Can we get this to use the PathBase instead by default (which needs to be done dynamically)? This is hard to do now in Katana v2/v3. And then if people want "/" that's very east to then assign in the app startup.

Have social provider middlewares return subset of claims from external providers

In case of OAuth providers with external scopes requested, the additional claims are not present in the ClaimsIdentity object read from the external cookie in the request callback. This is the most common scenario for users currently and we could think about adding a subset of these claims in the individual providers when setting the external cookie.

Cookies middleware should not enforce need for ILoggerFactory

Currently when ILoggerFactory is not registered in the IoC container the Cookies middleware throws a null reference exception as this is a compulsory parameter. This has to be an optional parameter if the app does not want to do any logging.

Provide an empty/default implementation of IAuthorizationPolicy

In my code, I had to create my own empty implementation of the IAuthorizationPolicy because most of my policies need only 1-2 methods from that interface. It would be so much easier and the experience would be so much better if there would be a default implementation of that interface. Something like:

public abstract class EmptyAuthorizationPolicy : IAuthorizationPolicy
{
    public virtual int Order { get; set; }

    public virtual Task AppliedAsync(AuthorizationPolicyContext context)
    {
        return Task.FromResult(0);
    }

    public virtual Task ApplyAsync(AuthorizationPolicyContext context)
    {
        return Task.FromResult(0);
    }

    public virtual Task ApplyingAsync(AuthorizationPolicyContext context)
    {
        return Task.FromResult(0);
    }
}

Revisit Cookie's custom AJAX redirect

The cookies middleware has custom redirect logic for AJAX requests, where it sends a 200 and embeds the real status code and location header inside a custom response header. Everybody I've asked says this was done to support the first version of templates, but I can't find any reference to it there. The templates have since been modified. Do we still need this strange custom behavior?
RE: https://katanaproject.codeplex.com/workitem/264

Port OAuth Authorization Server from Katana

I saw the discussion about this on #39. @Tratcher suggested to open up a new issue for this and here it is ๐Ÿ˜„

I personally want to see OAuthAuthorizationServerMiddleware ported here because of my selfish reasons ๐Ÿ˜„ as I used this inside a project which we consider porting over to vNext. I also see questions, feedback, etc. for OAuthAuthorizationServerMiddleware which indicates that it's being used.

However, I agree with @leastprivilege here. It should live inside its own world.

Filter out empty scope parameters to social providers

For example if I don't configure any scopes in facebook (which does not have a default scope), we send an empty scope query url parameter to facebook. This does not bring an functionality issues, but just wondering if we can avoid sending empty scopes?

Note: This is not a regression from katana, but just a cleanup

Middleware Extensibility: Support "Multi-tenancy" In AuthenticationOptions (and more)

Copied from https://katanaproject.codeplex.com/discussions/561673 as I was advised this project is moving from CodePlex to GitHub.

Hello Katana team,

Problem

I've been unable to cleanly extend the "built-in" authentication middleware because of its dependency on a concrete instance of AuthenticationOptions (and subclasses per implementation).

Presently the auth middleware is initialized at start-up and any configuration (API KEY, API SECRET, etc) cannot be changed on a per-request or per-tenant basis. I've seen some suggestion of multiple middleware instances per tenant as a solution but this is not very efficient or (feasible) when you have N tenants.

In my case each of my customers has their own OAUTH api credentials for each service and I need to be able to set them per-request based on the tenant scope. My problem, although seemingly common, is not the only reason to consider my proposed change.

The current dependency on a concrete implementation of [Middleware]AuthenticationOptions and AuthenticationOptions limits extensibility to the point that many are forced to "roll their own" copies of existing middleware with minor changes for their individual needs.

Proposed Design Change

I propose a design change, of which I'd like to contribute code, to address this limitation and allow for an optional alternative way to load middleware AuthenticationOptions. To achieve this we would depend on an interface IAuthenticationOptions and I[MiddlewareName]AuthenticationOptions for each specific middleware implementation.

These interfaces would have default implementations for each middleware. For example, for Facebook there would be a DefaultFacebookAuthenticationOptions which would implement the interface and use the current (static) approach to loading AppId and AppSecret.

A second scenario-specific implementation (which would be left to someone else to implement) could be MultitenantFacebookAuthenticationOptions which also implements the interface and identifies the tenant based on the request and then uses a datastore to load the AppId and AppSecret.

It would probably make most sense to have a FacebookAuthenticationOptionsBase abstract class which contains most of the needed functionality. We would also need to modify the existing FacebookAuthenticationOptions class to support the new interface but without breaking backward compatibility.

I have already proven this concept in my own project. In order to implement this we would need to change several authentication middleware classes which have dependencies on AuthenticationOptions as well as existing middleware which has dependencies on concretes of their respective implementations (e.g. FacebookAuthenticationOptions). Likewise, Extension Methods related to adding middleware to the pipeline would be modified to depend on the aforementioned interfaces instead of concretes.

Backwards Compatibility

This design change would have no impact on existing implementations. Developers would still be able to use app.UseFacebookAuthentication (et al) as well as the existing FacebookAuthenticationOptions class.

A new option for developers will be to provide/inject an IAuthenticationOptions when adding the middleware to the pipeline. Typically that would be done as follows:

// Old approach still supported
app.UseFacebookAuthentication(appId, appSecret);

// A new approach to inject an IFacebookAuthenticationOptions implementation
app.UseFacebookAuthentication(new MultitenantFacebookAuthenticationOptions());

Both approaches would be supported under the hood as such:

public static class FacebookAuthenticationExtensions
{
    public static IAppBuilder UseFacebookAuthentication(this IAppBuilder app, IFacebookAuthenticationOptions options)
    {
        if(app == null) throw new ArgumentNullException("app");
        if(options == null) throw new ArgumentNullException("options");

        app.Use(typeof (FacebookAuthenticationMiddleware), app, options);

        return app;
    }

    public static IAppBuilder UseFacebookAuthentication(this IAppBuilder app, string appId, string appSecret)
    {
        return UseFacebookAuthentication(
            app,
            new DefaultFacebookAuthenticationOptions
            {
                AppId = appId,
                AppSecret = appSecret,
            });
    }
}

Existing custom middleware, such as those provided by the owin-middleware/OwinOAuthProviders project should continue to work but will need to update their Microsoft.Owin.Security dependencies if they want to stay current. I believe this is the only burden added by my proposed design.

Finally...

I'm eager to see this implemented as I believe it is a design improvement which makes authentication middleware much more extensible without making it more complex. I wanted to get buy-in before I started the code changes required to implement the change.

So, Katana team, what do you think? :)

NotImplemented exception when doing a challenge for cookies middleware

Looks like K10 has a IdnMapping class stub with no implementation.

An unhandled exception occurred while processing the request.

NotImplementedException: The method or operation is not implemented.
Microsoft.AspNet.Abstractions.HostString.IdnMapping.GetAscii(String unicode, Int32 index, Int32 count)

Stack Query Cookies Headers Environment
NotImplementedException: The method or operation is not implemented.
Microsoft.AspNet.Abstractions.HostString.IdnMapping.GetAscii(String unicode, Int32 index, Int32 count)
Microsoft.AspNet.Abstractions.HostString.ToUriComponent()
Microsoft.AspNet.Abstractions.HostString.ToString()
System.String.Concat(Object[] args)
Microsoft.AspNet.Security.Cookies.CookieAuthenticationHandler.ApplyResponseChallenge()
Microsoft.AspNet.Security.Infrastructure.AuthenticationHandler.ApplyResponseCore()
Microsoft.AspNet.Security.Infrastructure.AuthenticationHandler.b__6()
System.Threading.LazyInitializer.EnsureInitializedCore[T](T& target, Boolean& initialized, Object& syncLock, Func1 valueFactory) System.Threading.LazyInitializer.EnsureInitialized[T](T& target, Boolean& initialized, Object& syncLock, Func1 valueFactory)
Microsoft.AspNet.Security.Infrastructure.AuthenticationHandler.ApplyResponse()
Microsoft.AspNet.Security.Infrastructure.AuthenticationHandler.OnSendingHeaderCallback(Object state)
Microsoft.AspNet.Server.WebListener.Response.NotifyOnSendingHeaders()
Microsoft.AspNet.Server.WebListener.Response.ComputeHeaders(Boolean endOfRequest)
Microsoft.AspNet.Server.WebListener.ResponseStream.ComputeLeftToWrite(Boolean endOfRequest)
Microsoft.AspNet.Server.WebListener.ResponseStream.WriteAsync(Byte[] buffer, Int32 offset, Int32 size, CancellationToken cancel)
System.IO.Stream.WriteAsync(Byte[] buffer, Int32 offset, Int32 count)
Microsoft.AspNet.PipelineCore.DefaultHttpResponse.WriteAsync(String data)
Startup.b__0(HttpContext context) in Startup.cs
return context.Response.WriteAsync("Authenticate..");

Rationalize notification context patterns

The original batch of social auth middleware (Facebook, Twitter, etc.) all used notification contexts derived from BaseContext. The second round (WsFed, ODIC) tried to provide more direct shared context objects (AuthenticationFailedNotification). These should be rationalized.

Re-evaluate sync vs async extension points in AuthenticationHandler

AuthenticatoinHandler has several abstract/virtial APIs where it has both a sync and async overload, and the developer can choose to implement one or the other. It's very common for the sync implementation to call the async method and block. The base handler calls the sync and async overloads in different circumstances, such as sync calls from OnSendingHeaders.

Theory 1: Get rid of the sync calls, make OnSendingHeaders async.
Theory 2: Get rid of any async calls that are only called from OnSendingHeaders. Make sure there is only one overload of each extension point, be it sync or async.

Eliminate unnecessary async operations when parsing JSON

Suggestion from @PinpointTownes regarding the change at 13adde6#commitcomment-7735513

My 2 cents: these Task -returning methods have been removed for a reason: they were not really asynchronous and used Task.Factory.StartNew / Task.Run internally. Offloading pure CPU-bound operations to the thread pool is generally not a good idea and often incur a little overhead, and that's why this kind of practices should be limited to UI, where responsiveness is essential. Don't miss this topic if you want more information: JamesNK/Newtonsoft.Json#66

Even if these methods are only used in unit tests, I'd suggest removing Task.Factory.StartNew and making ReturnJsonResponse synchronous (or using Task.FromResult if you wanna keep it async) to reduce the cost of thread switching and limit its impact on the execution duration.

Extract common OAuth2 middleware base class

Facebook, MicrosoftAccount, Google, all use OAuth2 and should derive from an OAuth package with shared base classes for middleware, notifications, notification contexts, etc..

Specific items of concern: Shared base class for *AutehnticatedContext with shared OAuth fields like AccessToken, RefreshToken, Id, etc.. See @blowdart for specific fields.

Stretch: Can this work for Twitter also? They use OAuth1 but many of the shared fields are the same.

FYI: There are also all of these 3rd party implementations that could be simplified:
https://github.com/owin-middleware/OwinOAuthProviders/tree/master/Owin.Security.Providers

Cookies middleware fails on mono as it depends on GZipStream

Cookies middleware does not work on mono as the TicketSerializer it uses compresses the cookie response using GZipStream.

System.NotImplementedException: The requested feature is not implemented.
  at System.IO.Compression.GZipStream..ctor (System.IO.Stream stream, CompressionLevel compressionLevel) [0x00000] in <filename unknown>:0 
  at (wrapper remoting-invoke-with-check) System.IO.Compression.GZipStream:.ctor (System.IO.Stream,System.IO.Compression.CompressionLevel)
  at Microsoft.AspNet.Security.DataHandler.Serializer.TicketSerializer.Serialize (Microsoft.AspNet.Security.AuthenticationTicket model) [0x00000] in <filename unknown>:0 
  at Microsoft.AspNet.Security.DataHandler.SecureDataFormat`1[Microsoft.AspNet.Security.AuthenticationTicket].Protect (Microsoft.AspNet.Security.AuthenticationTicket data) [0x00000] in <filename unknown>:0 
  at Microsoft.AspNet.Security.Cookies.CookieAuthenticationHandler+<ApplyResponseGrantAsync>d__1.MoveNext () [0x00000] in <filename unknown>:0 
System.NotImplementedException: The requested feature is not implemented.
  at System.IO.Compression.GZipStream..ctor (System.IO.Stream stream, CompressionLevel compressionLevel) [0x00000] in <filename unknown>:0 
  at (wrapper remoting-invoke-with-check) System.IO.Compression.GZipStream:.ctor (System.IO.Stream,System.IO.Compression.CompressionLevel)
  at Microsoft.AspNet.Security.DataHandler.Serializer.TicketSerializer.Serialize (Microsoft.AspNet.Security.AuthenticationTicket model) [0x00000] in <filename unknown>:0 
  at Microsoft.AspNet.Security.DataHandler.SecureDataFormat`1[Microsoft.AspNet.Security.AuthenticationTicket].Protect (Microsoft.AspNet.Security.AuthenticationTicket data) [0x00000] in <filename unknown>:0 
  at Microsoft.AspNet.Security.Cookies.CookieAuthenticationHandler+<ApplyResponseGrantAsync>d__1.MoveNext () [0x00000] in <filename unknown>:0 

AuthenticationHandler.TeardownCoreAsync - Not getting called on exception

In my derived authentication handler, I'm taking some action during request processing and it requires a compensating action during response processing. I would like to do this compensating action in TeardownCoreAsync. But then the problem is TeardownCoreAsync is not guaranteed to be called. For example, if a downstream middleware throws an exception, TeardownCoreAsync does not get called. Is this by design? In authentication middleware, you could have a try-finally and call TeardownAsync in the finally block. If TeardownCoreAsync is not guaranteed to be called by design, please let me know the recommended way of ensuring a block code to be called during response processing from my derived authentication handler.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.