public void Authenticate(AuthenticateContext context)
 {
     if (PriorHandler != null)
     {
         PriorHandler.Authenticate(context);
         ApplyTransform(context);
     }
 }
 public async Task AuthenticateAsync(AuthenticateContext context)
 {
     if (PriorHandler != null)
     {
         await PriorHandler.AuthenticateAsync(context);
         ApplyTransform(context);
     }
 }
        public virtual async Task<ClaimsPrincipal> AuthenticateAsync(string authenticationScheme)
        {
            if (authenticationScheme == null)
            {
                throw new ArgumentNullException(nameof(authenticationScheme));
            }

            var context = new AuthenticateContext(authenticationScheme);
            await AuthenticateAsync(context);
            return context.Principal;
        }
        public Task AuthenticateAsync(AuthenticateContext context)
        {
            if (User == null)
            {
                context.NotAuthenticated();
            }
            else if (Scheme == null || Scheme == context.AuthenticationScheme)
            {
                context.Authenticated(User, new Dictionary<string, string>(), new Dictionary<string, object>());
            }

            return Task.FromResult(0);
        }
 public async Task AuthenticateAsync(AuthenticateContext context)
 {
     if (PriorHandler != null)
     {
         await PriorHandler.AuthenticateAsync(context);
         if (_transform != null && context?.Principal != null)
         {
             context.Authenticated(
                 await _transform.TransformAsync(context.Principal),
                 context.Properties,
                 context.Description);
         }
     }
 }
        private void ApplyTransform(AuthenticateContext context)
        {
            if (_transform != null)
            {
                // REVIEW: this cast seems really bad (missing interface way to get the result back out?)
                var authContext = context as AuthenticateContext;
                if (authContext?.Principal != null)
                {
                    context.Authenticated(
                        _transform.Invoke(authContext.Principal),
                        authContext.Properties,
                        authContext.Description);
                }
            }

        }
        public override async Task AuthenticateAsync(AuthenticateContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var handler = HttpAuthenticationFeature.Handler;
            if (handler != null)
            {
                await handler.AuthenticateAsync(context);
            }

            if (!context.Accepted)
            {
                throw new InvalidOperationException($"No authentication handler is configured to authenticate for the scheme: {context.AuthenticationScheme}");
            }
        }
        public override async Task AuthenticateAsync(AuthenticateContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var handler = HttpAuthenticationFeature.Handler;

            if (handler != null)
            {
                await handler.AuthenticateAsync(context);
            }

            if (!context.Accepted)
            {
                throw new InvalidOperationException($"The following authentication scheme was not accepted: {context.AuthenticationScheme}");
            }
        }
        public Task AuthenticateAsync(AuthenticateContext context)
        {
            if (ShouldHandleScheme(context.AuthenticationScheme))
            {
                if (User != null)
                {
                    context.Authenticated(User, properties: null,
                        description: Options.AuthenticationDescriptions.Where(descrip =>
                            string.Equals(User.Identity.AuthenticationType, descrip.AuthenticationScheme, StringComparison.Ordinal)).FirstOrDefault()?.Items);
                }
                else
                {
                    context.NotAuthenticated();
                }
            }

            if (PriorHandler != null)
            {
                return PriorHandler.AuthenticateAsync(context);
            }
            return Task.FromResult(0);
        }
 public Task AuthenticateAsync(AuthenticateContext context)
 {
     throw new NotImplementedException();
 }
 public Task AuthenticateAsync(AuthenticateContext context)
 {
     context.NotAuthenticated();
     return Task.FromResult(0);
 }
 public void Authenticate(AuthenticateContext context)
 {
     context.NotAuthenticated();
 }
Ejemplo n.º 13
0
 private static void Describe(HttpResponse res, AuthenticateContext result)
 {
     res.StatusCode = 200;
     res.ContentType = "text/xml";
     var xml = new XElement("xml");
     if (result != null && result.Principal != null)
     {
         xml.Add(result.Principal.Claims.Select(claim => new XElement("claim", new XAttribute("type", claim.Type), new XAttribute("value", claim.Value))));
     }
     if (result != null && result.Properties != null)
     {
         xml.Add(result.Properties.Select(extra => new XElement("extra", new XAttribute("type", extra.Key), new XAttribute("value", extra.Value))));
     }
     using (var memory = new MemoryStream())
     {
         using (var writer = new XmlTextWriter(memory, Encoding.UTF8))
         {
             xml.WriteTo(writer);
         }
         res.Body.Write(memory.ToArray(), 0, memory.ToArray().Length);
     }
 }
Ejemplo n.º 14
0
 private static TestServer CreateServer(Action<IServiceCollection> configureServices = null, Func<HttpContext, Task> testpath = null, Uri baseAddress = null)
 {
     var server = TestServer.Create(app =>
     {
         app.UseIdentity();
         app.Use(async (context, next) =>
         {
             var req = context.Request;
             var res = context.Response;
             var userManager = context.RequestServices.GetRequiredService<UserManager<TestUser>>();
             var signInManager = context.RequestServices.GetRequiredService<SignInManager<TestUser>>();
             PathString remainder;
             if (req.Path == new PathString("/normal"))
             {
                 res.StatusCode = 200;
             }
             else if (req.Path == new PathString("/createMe"))
             {
                 var result = await userManager.CreateAsync(new TestUser("hao"), TestPassword);
                 res.StatusCode = result.Succeeded ? 200 : 500;
             }
             else if (req.Path == new PathString("/createSimple"))
             {
                 var result = await userManager.CreateAsync(new TestUser("simple"), "aaaaaa");
                 res.StatusCode = result.Succeeded ? 200 : 500;
             }
             else if (req.Path == new PathString("/protected"))
             {
                 res.StatusCode = 401;
             }
             else if (req.Path.StartsWithSegments(new PathString("/pwdLogin"), out remainder))
             {
                 var isPersistent = bool.Parse(remainder.Value.Substring(1));
                 var result = await signInManager.PasswordSignInAsync("hao", TestPassword, isPersistent, false);
                 res.StatusCode = result.Succeeded ? 200 : 500;
             }
             else if (req.Path == new PathString("/twofactorRememeber"))
             {
                 var user = await userManager.FindByNameAsync("hao");
                 await signInManager.RememberTwoFactorClientAsync(user);
                 res.StatusCode = 200;
             }
             else if (req.Path == new PathString("/isTwoFactorRememebered"))
             {
                 var user = await userManager.FindByNameAsync("hao");
                 var result = await signInManager.IsTwoFactorClientRememberedAsync(user);
                 res.StatusCode = result ? 200 : 500;
             }
             else if (req.Path == new PathString("/twofactorSignIn"))
             {
             }
             else if (req.Path == new PathString("/me"))
             {
                 var auth = new AuthenticateContext("Application");
                 auth.Authenticated(context.User, new AuthenticationProperties().Items, new AuthenticationDescription().Items);
                 Describe(res, auth);
             }
             else if (req.Path.StartsWithSegments(new PathString("/me"), out remainder))
             {
                 var auth = new AuthenticateContext(remainder.Value.Substring(1));
                 await context.Authentication.AuthenticateAsync(auth);
                 Describe(res, auth);
             }
             else if (req.Path == new PathString("/testpath") && testpath != null)
             {
                 await testpath(context);
             }
             else
             {
                 await next();
             }
         });
     },
     services =>
     {
         services.AddIdentity<TestUser, TestRole>();
         services.AddSingleton<IUserStore<TestUser>, InMemoryUserStore<TestUser>>();
         services.AddSingleton<IRoleStore<TestRole>, InMemoryRoleStore<TestRole>>();
         if (configureServices != null)
         {
             configureServices(services);
         }
     });
     server.BaseAddress = baseAddress;
     return server;
 }
Ejemplo n.º 15
0
        public async Task AuthenticateAsync(AuthenticateContext context)
        {
            if (ShouldHandleScheme(context.AuthenticationScheme))
            {
                // Calling Authenticate more than once should always return the original value. 
                var ticket = await HandleAuthenticateOnceAsync();
                if (ticket?.Principal != null)
                {
                    context.Authenticated(ticket.Principal, ticket.Properties.Items, BaseOptions.Description.Items);
                }
                else
                {
                    context.NotAuthenticated();
                }
            }

            if (PriorHandler != null)
            {
                await PriorHandler.AuthenticateAsync(context);
            }
        }
 public abstract Task AuthenticateAsync(AuthenticateContext context);
Ejemplo n.º 17
0
        public virtual async Task AuthenticateAsync(AuthenticateContext context)
        {
            if (ShouldHandleScheme(context.AuthenticationScheme))
            {
                var ticket = await AuthenticateAsync();
                if (ticket?.Principal != null)
                {
                    AuthenticateCalled = true;
                    context.Authenticated(ticket.Principal, ticket.Properties.Items, BaseOptions.Description.Items);
                }
                else
                {
                    context.NotAuthenticated();
                }
            }

            if (PriorHandler != null)
            {
                await PriorHandler.AuthenticateAsync(context);
            }
        }
Ejemplo n.º 18
0
 private static void Describe(HttpResponse res, AuthenticateContext result)
 {
     res.StatusCode = 200;
     res.ContentType = "text/xml";
     var xml = new XElement("xml");
     if (result != null && result.Principal != null)
     {
         xml.Add(result.Principal.Claims.Select(claim => new XElement("claim", new XAttribute("type", claim.Type), new XAttribute("value", claim.Value))));
     }
     if (result != null && result.Properties != null)
     {
         xml.Add(result.Properties.Select(extra => new XElement("extra", new XAttribute("type", extra.Key), new XAttribute("value", extra.Value))));
     }
     var xmlBytes = Encoding.UTF8.GetBytes(xml.ToString());
     res.Body.Write(xmlBytes, 0, xmlBytes.Length);
 }
Ejemplo n.º 19
0
        public async Task CanSpecifyAndShareDataProtector()
        {

            var dp = new NoOpDataProtector();
            var server1 = TestServer.Create(app =>
            {
                app.UseCookieAuthentication(options =>
                {
                    options.TicketDataFormat = new TicketDataFormat(dp);
                    options.CookieName = "Cookie";
                });
                app.Use((context, next) =>
                    context.Authentication.SignInAsync("Cookies",
                                    new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies"))),
                                    new AuthenticationProperties()));
            },
            services => services.AddAuthentication());

            var transaction = await SendAsync(server1, "http://example.com/stuff");
            transaction.SetCookie.ShouldNotBe(null);

            var server2 = TestServer.Create(app =>
            {
                app.UseCookieAuthentication(options =>
                {
                    options.AuthenticationScheme = "Cookies";
                    options.CookieName = "Cookie";
                    options.TicketDataFormat = new TicketDataFormat(dp);
                });
                app.Use(async (context, next) =>
                {
                    var authContext = new AuthenticateContext("Cookies");
                    await context.Authentication.AuthenticateAsync(authContext);
                    Describe(context.Response, authContext);
                });
            },
            services => services.AddAuthentication());
            var transaction2 = await SendAsync(server2, "http://example.com/stuff", transaction.CookieNameValue);
            FindClaimValue(transaction2, ClaimTypes.Name).ShouldBe("Alice");
        }
 public virtual async Task<ClaimsPrincipal> AuthenticateAsync([NotNull] string authenticationScheme)
 {
     var context = new AuthenticateContext(authenticationScheme);
     await AuthenticateAsync(context);
     return context.Principal;
 }
Ejemplo n.º 21
0
        private static TestServer CreateServer(Action<CookieAuthenticationOptions> configureOptions, Func<HttpContext, Task> testpath = null, Uri baseAddress = null, Action<ClaimsTransformationOptions> claimsTransform = null)
        {
            var server = TestServer.Create(app =>
            {
                app.UseCookieAuthentication(configureOptions);

                if (claimsTransform != null)
                {
                    app.UseClaimsTransformation();
                }
                app.Use(async (context, next) =>
                {
                    var req = context.Request;
                    var res = context.Response;
                    PathString remainder;
                    if (req.Path == new PathString("/normal"))
                    {
                        res.StatusCode = 200;
                    }
                    else if (req.Path == new PathString("/protected"))
                    {
                        res.StatusCode = 401;
                    }
                    else if (req.Path == new PathString("/forbid")) // Simulate forbidden 
                    {
                        await context.Authentication.ForbidAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                    }
                    else if (req.Path == new PathString("/challenge"))
                    {
                        await context.Authentication.ChallengeAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                    }
                    else if (req.Path == new PathString("/unauthorized"))
                    {
                        await context.Authentication.ChallengeAsync(CookieAuthenticationDefaults.AuthenticationScheme, new AuthenticationProperties(), ChallengeBehavior.Unauthorized);
                    }
                    else if (req.Path == new PathString("/protected/CustomRedirect"))
                    {
                        await context.Authentication.ChallengeAsync(new AuthenticationProperties() { RedirectUri = "/CustomRedirect" });
                    }
                    else if (req.Path == new PathString("/me"))
                    {
                        var authContext = new AuthenticateContext(CookieAuthenticationDefaults.AuthenticationScheme);
                        authContext.Authenticated(context.User, properties: null, description: null);
                        Describe(res, authContext);
                    }
                    else if (req.Path.StartsWithSegments(new PathString("/me"), out remainder))
                    {
                        var authContext = new AuthenticateContext(remainder.Value.Substring(1));
                        await context.Authentication.AuthenticateAsync(authContext);
                        Describe(res, authContext);
                    }
                    else if (req.Path == new PathString("/testpath") && testpath != null)
                    {
                        await testpath(context);
                    }
                    else
                    {
                        await next();
                    }
                });
            },
            services =>
            {
                services.AddAuthentication();
                if (claimsTransform != null)
                {
                    services.ConfigureClaimsTransformation(claimsTransform);
                }
            });
            server.BaseAddress = baseAddress;
            return server;
        }
Ejemplo n.º 22
0
 public async Task AuthenticateWillFail()
 {
     var server = CreateServer(options =>
     {
         options.ClientId = "Test Id";
         options.ClientSecret = "Test Secret";
     },
     async context => 
     {
         var req = context.Request;
         var res = context.Response;
         if (req.Path == new PathString("/auth"))
         {
             var auth = new AuthenticateContext("Google");
             await context.Authentication.AuthenticateAsync(auth);
             Assert.NotNull(auth.Error);
         }
     });
     var transaction = await server.SendAsync("https://example.com/auth");
     Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
 }
Ejemplo n.º 23
0
 public Task<ClaimsPrincipal> GetExternalIdentity(string authenticationScheme)
 {
     var auth = new AuthenticateContext(authenticationScheme);
     return Context.Authentication.AuthenticateAsync(auth.AuthenticationScheme);
 }