/// <summary>
 /// Creates a new context object.
 /// </summary>
 /// <param name="context">The HTTP request context.</param>
 /// <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 TwitterRedirectToAuthorizationEndpointContext(HttpContext context, TwitterOptions options,
     AuthenticationProperties properties, string redirectUri)
     : base(context, options)
 {
     RedirectUri = redirectUri;
     Properties = properties;
 }
        public async Task ExecuteResultAsync_InvokesForbiddenAsyncOnAllConfiguredSchemes()
        {
            // Arrange
            var authProperties = new AuthenticationProperties();
            var authenticationManager = new Mock<AuthenticationManager>();
            authenticationManager
                .Setup(c => c.ForbidAsync("Scheme1", authProperties))
                .Returns(TaskCache.CompletedTask)
                .Verifiable();
            authenticationManager
                .Setup(c => c.ForbidAsync("Scheme2", authProperties))
                .Returns(TaskCache.CompletedTask)
                .Verifiable();
            var httpContext = new Mock<HttpContext>();
            httpContext.Setup(c => c.RequestServices).Returns(CreateServices());
            httpContext.Setup(c => c.Authentication).Returns(authenticationManager.Object);
            var result = new ForbidResult(new[] { "Scheme1", "Scheme2" }, authProperties);
            var routeData = new RouteData();

            var actionContext = new ActionContext(
                httpContext.Object,
                routeData,
                new ActionDescriptor());

            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            authenticationManager.Verify();
        }
Beispiel #3
0
        public async Task<IActionResult> Auth(string token)
        {
            var access = _userService.Auth(token);

            if (access.Type == AuthType.Invalid || access.Type == AuthType.NotFound)
            {
                return View("NoAccess", access);
            }

            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, access.Email),
                new Claim(ClaimTypes.Email, access.Email)
            };

            var authProperties = new AuthenticationProperties { IssuedUtc = DateTimeOffset.UtcNow };

            if (access.Type == AuthType.Cookie)
            {
                authProperties.ExpiresUtc = GetAccessExpireTime(access.ValidUntil);
                authProperties.IsPersistent = true;
            }

            var identity = new ClaimsIdentity(claims, "custom");
            await HttpContext.Authentication.SignInAsync(Constants.Auth.AuthenticationScheme, new ClaimsPrincipal(identity), authProperties);
            return RedirectToAction(nameof(Watchlist));
        }
 /// <summary>
 /// Creates a new context object.
 /// </summary>
 /// <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 OAuthRedirectToAuthorizationContext(HttpContext context, OAuthOptions options, AuthenticationProperties properties, string redirectUri)
     : base(context)
 {
     RedirectUri = redirectUri;
     Properties = properties;
     Options = options;
 }
        public IActionResult External(string provider)
        {
            var props = new AuthenticationProperties
            {
                RedirectUri = "/account/externalCallback"
            };

            return new ChallengeResult(provider, props);
        }
        public IActionResult Google()
        {
            var props = new AuthenticationProperties
            {
                RedirectUri = "/account/callback"
            };

            return new ChallengeResult("Google", props);
        }
        public IActionResult External(string provider)
        {
            var props = new AuthenticationProperties
            {
                RedirectUri = "/home/secure"
            };

            return new ChallengeResult(provider, props);
        }
        // Leave it up to authentication handler to do the right thing for the challenge
        public virtual Task ChallengeAsync(string authenticationScheme, AuthenticationProperties properties)
        {
            if (string.IsNullOrEmpty(authenticationScheme))
            {
                throw new ArgumentException(nameof(authenticationScheme));
            }

            return ChallengeAsync(authenticationScheme, properties, ChallengeBehavior.Automatic);
        }
        public IActionResult Google()
        {
            var props = new AuthenticationProperties
            {
                RedirectUri = "/home/secure"
            };

            return new ChallengeResult("Google", props);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="AuthenticationTicket"/> class
 /// </summary>
 /// <param name="principal">the <see cref="ClaimsPrincipal"/> that represents the authenticated user.</param>
 /// <param name="properties">additional properties that can be consumed by the user or runtime.</param>
 /// <param name="authenticationScheme">the authentication middleware that was responsible for this ticket.</param>
 public AuthenticationTicket(ClaimsPrincipal principal, AuthenticationProperties properties, string authenticationScheme)
 {
     if (principal == null)
     {
         throw new ArgumentNullException(nameof(principal));
     }
     AuthenticationScheme = authenticationScheme;
     Principal = principal;
     Properties = properties ?? new AuthenticationProperties();
 }
        public IActionResult ExternalLogin(string provider, string returnUrl = null)
        {
            // Request a redirect to the external login provider.
            var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
            var props = new AuthenticationProperties
            {
                RedirectUri = redirectUrl
            };
            return new ChallengeResult(provider, props);

        }
        /// <summary>
        /// Initializes a new instance of the <see cref="AuthenticationResponseGrant"/> class.
        /// </summary>
        /// <param name="principal"></param>
        /// <param name="properties"></param>
        public AuthenticationResponseGrant(ClaimsPrincipal principal, AuthenticationProperties properties)
        {
            if (principal == null)
            {
                throw new ArgumentNullException("principal");
            }

            Principal = principal;
            Identity = principal.Identities.FirstOrDefault();
            Properties = properties;
        }
 /// <summary>
 /// Creates a new instance of the context object.
 /// </summary>
 /// <param name="context">The HTTP request context</param>
 /// <param name="options">The middleware options</param>
 /// <param name="authenticationScheme">Initializes AuthenticationScheme property</param>
 /// <param name="principal">Initializes Principal property</param>
 /// <param name="properties">Initializes Properties property</param>
 public CookieSignedInContext(
     HttpContext context,
     CookieAuthenticationOptions options,
     string authenticationScheme,
     ClaimsPrincipal principal,
     AuthenticationProperties properties)
     : base(context, options)
 {
     AuthenticationScheme = authenticationScheme;
     Principal = principal;
     Properties = properties;
 }
        public IActionResult Get(string provider)
        {
            var queryStrings = Context.Request.Query;

            var props = new AuthenticationProperties
            {
                RedirectUri = string.Format("/api/linkedaccount/callback?provider={0}&response_type{1}&client_id={2}&redirect_uri={3}", 
                queryStrings.Get("provider"),
                queryStrings.Get("response_type"),
                queryStrings.Get("client_id"),
                queryStrings.Get("redirect_uri"))
            };

            return new ChallengeResult(provider, props);
        }
        public void CanRoundTripBootstrapContext()
        {
            var serializer = new TicketSerializer();
            var properties = new AuthenticationProperties();

            var ticket = new AuthenticationTicket(new ClaimsPrincipal(), properties, "Hello");
            ticket.Principal.AddIdentity(new ClaimsIdentity("misc") { BootstrapContext = "bootstrap" });

            using (var stream = new MemoryStream())
            using (var writer = new BinaryWriter(stream))
            using (var reader = new BinaryReader(stream))
            {
                serializer.Write(writer, ticket);
                stream.Position = 0;
                var readTicket = serializer.Read(reader);
                Assert.Equal(1, readTicket.Principal.Identities.Count());
                Assert.Equal("misc", readTicket.Principal.Identity.AuthenticationType);
                Assert.Equal("bootstrap", readTicket.Principal.Identities.First().BootstrapContext);
            }
        }
        public override async Task GrantResourceOwnerCredentials(GrantResourceOwnerCredentialsNotification notification)
        {
            string roleType;
            if (!UserAuthenticatedSimple(notification, out roleType))
                return;

            //authenticate
            var identity = new ClaimsIdentity(OpenIdConnectDefaults.AuthenticationScheme);
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, notification.UserName));
            identity.AddClaim(new Claim(ClaimTypes.Role, roleType));

            // create metadata to pass on to refresh token provider
            var props = new AuthenticationProperties(new Dictionary<string, string>
                {
                    { "as:client_id", notification.ClientId },
                    {"userName", notification.UserName }
                });
            var principal = new ClaimsPrincipal(identity);
            var ticket = new AuthenticationTicket(principal, props, OpenIdConnectDefaults.AuthenticationScheme);
            notification.Validated(ticket);
        }
        public async Task OnValidatePrincipalTestSuccess(bool isPersistent)
        {
            var user = new TestUser("test");
            var userManager = MockHelpers.MockUserManager<TestUser>();
            var claimsManager = new Mock<IUserClaimsPrincipalFactory<TestUser>>();
            var identityOptions = new IdentityOptions { SecurityStampValidationInterval = TimeSpan.Zero };
            var options = new Mock<IOptions<IdentityOptions>>();
            options.Setup(a => a.Value).Returns(identityOptions);
            var httpContext = new Mock<HttpContext>();
            var contextAccessor = new Mock<IHttpContextAccessor>();
            contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object);
            var id = new ClaimsIdentity(identityOptions.Cookies.ApplicationCookieAuthenticationScheme);
            id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));
            var principal = new ClaimsPrincipal(id);

            var properties = new AuthenticationProperties { IssuedUtc = DateTimeOffset.UtcNow, IsPersistent = isPersistent };
            var signInManager = new Mock<SignInManager<TestUser>>(userManager.Object,
                contextAccessor.Object, claimsManager.Object, options.Object, null);
            signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny<ClaimsPrincipal>(), user.Id)).ReturnsAsync(user).Verifiable();
            signInManager.Setup(s => s.CreateUserPrincipalAsync(user)).ReturnsAsync(principal).Verifiable();
            var services = new ServiceCollection();
            services.AddInstance(options.Object);
            services.AddInstance(signInManager.Object);
            services.AddInstance<ISecurityStampValidator>(new SecurityStampValidator<TestUser>());
            httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider());

            var ticket = new AuthenticationTicket(principal, 
                properties, 
                identityOptions.Cookies.ApplicationCookieAuthenticationScheme);
            var context = new CookieValidatePrincipalContext(httpContext.Object, ticket, new CookieAuthenticationOptions());
            Assert.NotNull(context.Properties);
            Assert.NotNull(context.Options);
            Assert.NotNull(context.Principal);
            await
                SecurityStampValidator.ValidatePrincipalAsync(context);
            Assert.NotNull(context.Principal);
            signInManager.VerifyAll();
        }
        public async Task<IActionResult> Login(string userName = null)
        {
            //fake login with roles to demonstrate role based menu filtering
            AuthenticationProperties authProperties = new AuthenticationProperties();
            ClaimsPrincipal user;
            switch(userName)
            {
                case "Administrator":
                    user = GetAdminClaimsPrincipal();
                    break;

                case "Member":
                default:
                    user = GetMemberClaimsPrincipal();
                    break;
            }
            await HttpContext.Authentication.SignInAsync("application", user, authProperties);

            return RedirectToAction(nameof(HomeController.Index), "Home");


            //return View("Index");
        }
        public void CanRoundTripActorIdentity()
        {
            var serializer = new TicketSerializer();
            var properties = new AuthenticationProperties();

            var actor = new ClaimsIdentity("actor");
            var ticket = new AuthenticationTicket(new ClaimsPrincipal(), properties, "Hello");
            ticket.Principal.AddIdentity(new ClaimsIdentity("misc") { Actor = actor });

            using (var stream = new MemoryStream())
            using (var writer = new BinaryWriter(stream))
            using (var reader = new BinaryReader(stream))
            {
                serializer.Write(writer, ticket);
                stream.Position = 0;
                var readTicket = serializer.Read(reader);
                Assert.Equal(1, readTicket.Principal.Identities.Count());
                Assert.Equal("misc", readTicket.Principal.Identity.AuthenticationType);

                var identity = (ClaimsIdentity) readTicket.Principal.Identity;
                Assert.NotNull(identity.Actor);
                Assert.Equal(identity.Actor.AuthenticationType, "actor");
            }
        }
        public async Task ValidateAuthenticatedContext()
        {
            var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider().CreateProtector("GoogleTest"));
            var server = CreateServer(options =>
            {
                options.ClientId = "Test Id";
                options.ClientSecret = "Test Secret";
                options.StateDataFormat = stateFormat;
                options.AccessType = "offline";
                options.Events = new OAuthEvents()
                {
                    OnCreatingTicket = context =>
                    {
                        Assert.NotNull(context.User);
                        Assert.Equal(context.AccessToken, "Test Access Token");
                        Assert.Equal(context.RefreshToken, "Test Refresh Token");
                        Assert.Equal(context.ExpiresIn, TimeSpan.FromSeconds(3600));
                        Assert.Equal(GoogleHelper.GetEmail(context.User), "Test email");
                        Assert.Equal(GoogleHelper.GetId(context.User), "Test User ID");
                        Assert.Equal(GoogleHelper.GetName(context.User), "Test Name");
                        Assert.Equal(GoogleHelper.GetFamilyName(context.User), "Test Family Name");
                        Assert.Equal(GoogleHelper.GetGivenName(context.User), "Test Given Name");
                        return Task.FromResult(0);
                    }
                };
                options.BackchannelHttpHandler = new TestHttpMessageHandler
                {
                    Sender = req =>
                    {
                        if (req.RequestUri.AbsoluteUri == "https://accounts.google.com/o/oauth2/token")
                        {
                            return ReturnJsonResponse(new
                            {
                                access_token = "Test Access Token",
                                expires_in = 3600,
                                token_type = "Bearer",
                                refresh_token = "Test Refresh Token"
                            });
                        }
                        else if (req.RequestUri.GetLeftPart(UriPartial.Path) == "https://www.googleapis.com/plus/v1/people/me")
                        {
                            return ReturnJsonResponse(new
                            {
                                id = "Test User ID",
                                displayName = "Test Name",
                                name = new
                                {
                                    familyName = "Test Family Name",
                                    givenName = "Test Given Name"
                                },
                                url = "Profile link",
                                emails = new[]
                                    {
                                        new
                                        {
                                            value = "Test email",
                                            type = "account"
                                        }
                                    }
                            });
                        }

                        return null;
                    }
                };
            });

            var properties = new AuthenticationProperties();
            var correlationKey = ".AspNet.Correlation.Google";
            var correlationValue = "TestCorrelationId";
            properties.Items.Add(correlationKey, correlationValue);
            properties.RedirectUri = "/foo";
            var state = stateFormat.Protect(properties);

            //Post a message to the Google middleware
            var transaction = await server.SendAsync(
                "https://example.com/signin-google?code=TestCode&state=" + UrlEncoder.Default.UrlEncode(state),
                correlationKey + "=" + correlationValue);

            Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
            Assert.Equal("/foo", transaction.Response.Headers.GetValues("Location").First());
        }
        public async Task AuthenticatedEventCanGetRefreshToken()
        {
            var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider().CreateProtector("GoogleTest"));
            var server = CreateServer(options =>
            {
                options.ClientId = "Test Id";
                options.ClientSecret = "Test Secret";
                options.StateDataFormat = stateFormat;
                options.BackchannelHttpHandler = new TestHttpMessageHandler
                {
                    Sender = req =>
                    {
                        if (req.RequestUri.AbsoluteUri == "https://accounts.google.com/o/oauth2/token")
                        {
                            return ReturnJsonResponse(new
                            {
                                access_token = "Test Access Token",
                                expires_in = 3600,
                                token_type = "Bearer",
                                refresh_token = "Test Refresh Token"
                            });
                        }
                        else if (req.RequestUri.GetLeftPart(UriPartial.Path) == "https://www.googleapis.com/plus/v1/people/me")
                        {
                            return ReturnJsonResponse(new
                            {
                                id = "Test User ID",
                                displayName = "Test Name",
                                name = new
                                {
                                    familyName = "Test Family Name",
                                    givenName = "Test Given Name"
                                },
                                url = "Profile link",
                                emails = new[]
                                    {
                                        new
                                        {
                                            value = "Test email",
                                            type = "account"
                                        }
                                    }
                            });
                        }

                        return null;
                    }
                };
                options.Events = new OAuthEvents
                {
                    OnCreatingTicket = context =>
                    {
                        var refreshToken = context.RefreshToken;
                        context.Principal.AddIdentity(new ClaimsIdentity(new Claim[] { new Claim("RefreshToken", refreshToken, ClaimValueTypes.String, "Google") }, "Google"));
                        return Task.FromResult<object>(null);
                    }
                };
            });
            var properties = new AuthenticationProperties();
            var correlationKey = ".AspNet.Correlation.Google";
            var correlationValue = "TestCorrelationId";
            properties.Items.Add(correlationKey, correlationValue);
            properties.RedirectUri = "/me";
            var state = stateFormat.Protect(properties);
            var transaction = await server.SendAsync(
                "https://example.com/signin-google?code=TestCode&state=" + UrlEncoder.Default.UrlEncode(state),
                correlationKey + "=" + correlationValue);
            Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
            Assert.Equal("/me", transaction.Response.Headers.GetValues("Location").First());
            Assert.Equal(2, transaction.SetCookie.Count);
            Assert.Contains(correlationKey, transaction.SetCookie[0]);
            Assert.Contains(".AspNet." + TestExtensions.CookieAuthenticationScheme, transaction.SetCookie[1]);

            var authCookie = transaction.AuthenticationCookieValue;
            transaction = await server.SendAsync("https://example.com/me", authCookie);
            Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
            Assert.Equal("Test Refresh Token", transaction.FindClaimValue("RefreshToken"));
        }
 public async Task ReplyPathWillRejectIfAccessTokenIsMissing()
 {
     var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider().CreateProtector("GoogleTest"));
     var server = CreateServer(options =>
     {
         options.ClientId = "Test Id";
         options.ClientSecret = "Test Secret";
         options.StateDataFormat = stateFormat;
         options.BackchannelHttpHandler = new TestHttpMessageHandler
         {
             Sender = req =>
             {
                 return ReturnJsonResponse(new object());
             }
         };
     });
     var properties = new AuthenticationProperties();
     var correlationKey = ".AspNet.Correlation.Google";
     var correlationValue = "TestCorrelationId";
     properties.Items.Add(correlationKey, correlationValue);
     properties.RedirectUri = "/me";
     var state = stateFormat.Protect(properties);
     var transaction = await server.SendAsync(
         "https://example.com/signin-google?code=TestCode&state=" + UrlEncoder.Default.UrlEncode(state),
         correlationKey + "=" + correlationValue);
     Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
     Assert.Contains("error=access_denied", transaction.Response.Headers.Location.ToString());
 }
        public async Task ReplyPathWillAuthenticateValidAuthorizeCodeAndState(string claimsIssuer)
        {
            var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider().CreateProtector("GoogleTest"));
            var server = CreateServer(options =>
            {
                options.ClientId = "Test Id";
                options.ClientSecret = "Test Secret";
                options.StateDataFormat = stateFormat;
                options.ClaimsIssuer = claimsIssuer;
                options.BackchannelHttpHandler = new TestHttpMessageHandler
                {
                    Sender = req =>
                    {
                        if (req.RequestUri.AbsoluteUri == "https://accounts.google.com/o/oauth2/token")
                        {
                            return ReturnJsonResponse(new
                            {
                                access_token = "Test Access Token",
                                expires_in = 3600,
                                token_type = "Bearer"
                            });
                        }
                        else if (req.RequestUri.GetLeftPart(UriPartial.Path) == "https://www.googleapis.com/plus/v1/people/me")
                        {
                            return ReturnJsonResponse(new
                            {
                                id = "Test User ID",
                                displayName = "Test Name",
                                name = new
                                {
                                    familyName = "Test Family Name",
                                    givenName = "Test Given Name"
                                },
                                url = "Profile link",
                                emails = new[]
                                {
                                    new
                                    {
                                        value = "Test email",
                                        type = "account"
                                    }
                                }
                            });
                        }

                        return null;
                    }
                };
            });
            var properties = new AuthenticationProperties();
            var correlationKey = ".AspNet.Correlation.Google";
            var correlationValue = "TestCorrelationId";
            properties.Items.Add(correlationKey, correlationValue);
            properties.RedirectUri = "/me";
            var state = stateFormat.Protect(properties);
            var transaction = await server.SendAsync(
                "https://example.com/signin-google?code=TestCode&state=" + UrlEncoder.Default.UrlEncode(state),
                correlationKey + "=" + correlationValue);
            Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
            Assert.Equal("/me", transaction.Response.Headers.GetValues("Location").First());
            Assert.Equal(2, transaction.SetCookie.Count);
            Assert.Contains(correlationKey, transaction.SetCookie[0]);
            Assert.Contains(".AspNet." + TestExtensions.CookieAuthenticationScheme, transaction.SetCookie[1]);

            var authCookie = transaction.AuthenticationCookieValue;
            transaction = await server.SendAsync("https://example.com/me", authCookie);
            Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
            var expectedIssuer = claimsIssuer ?? GoogleDefaults.AuthenticationScheme;
            Assert.Equal("Test Name", transaction.FindClaimValue(ClaimTypes.Name, expectedIssuer));
            Assert.Equal("Test User ID", transaction.FindClaimValue(ClaimTypes.NameIdentifier, expectedIssuer));
            Assert.Equal("Test Given Name", transaction.FindClaimValue(ClaimTypes.GivenName, expectedIssuer));
            Assert.Equal("Test Family Name", transaction.FindClaimValue(ClaimTypes.Surname, expectedIssuer));
            Assert.Equal("Test email", transaction.FindClaimValue(ClaimTypes.Email, expectedIssuer));

            // Ensure claims transformation 
            Assert.Equal("yup", transaction.FindClaimValue("xform"));
        }
        public override void SignOut(string authenticationScheme, AuthenticationProperties properties)
        {
            var handler = HttpAuthenticationFeature.Handler;

            var signOutContext = new SignOutContext(authenticationScheme, properties?.Dictionary);
            if (handler != null)
            {
                handler.SignOut(signOutContext);
            }

            // Verify all types ack'd
            if (!string.IsNullOrWhiteSpace(authenticationScheme) && !signOutContext.Accepted)
            {
                throw new InvalidOperationException("The following authentication scheme was not accepted: " + authenticationScheme);
            }
        }
        public override void SignIn(string authenticationScheme, [NotNull] ClaimsPrincipal principal, AuthenticationProperties properties)
        {
            var handler = HttpAuthenticationFeature.Handler;

            var signInContext = new SignInContext(authenticationScheme, principal, properties == null ? null : properties.Dictionary);
            if (handler != null)
            {
                handler.SignIn(signInContext);
            }

            // Verify all types ack'd
            if (!signInContext.Accepted)
            {
                throw new InvalidOperationException("The following authentication scheme was not accepted: " + authenticationScheme);
            }
        }
        public override void Challenge(AuthenticationProperties properties, [NotNull] IEnumerable<string> authenticationSchemes)
        {
            HttpResponseFeature.StatusCode = 401;
            var handler = HttpAuthenticationFeature.Handler;

            var challengeContext = new ChallengeContext(authenticationSchemes, properties == null ? null : properties.Dictionary);
            if (handler != null)
            {
                handler.Challenge(challengeContext);
            }

            // Verify all types ack'd
            IEnumerable<string> leftovers = authenticationSchemes.Except(challengeContext.Accepted);
            if (leftovers.Any())
            {
                throw new InvalidOperationException("The following authentication types were not accepted: " + string.Join(", ", leftovers));
            }
        }
        public async Task AuthenticatedEventCanGetRefreshToken()
        {
            ISecureDataFormat<AuthenticationProperties> stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider().CreateProtector("MsftTest"));
            var server = CreateServer(
                options =>
                {
                    options.ClientId = "Test Client Id";
                    options.ClientSecret = "Test Client Secret";
                    options.StateDataFormat = stateFormat;
                    options.BackchannelHttpHandler = new TestHttpMessageHandler
                    {
                        Sender = req =>
                        {
                            if (req.RequestUri.AbsoluteUri == "https://login.live.com/oauth20_token.srf")
                            {
                                return ReturnJsonResponse(new
                                {
                                    access_token = "Test Access Token",
                                    expire_in = 3600,
                                    token_type = "Bearer",
                                    refresh_token = "Test Refresh Token"
                                });
                            }
                            else if (req.RequestUri.GetLeftPart(UriPartial.Path) == "https://apis.live.net/v5.0/me")
                            {
                                return ReturnJsonResponse(new
                                {
                                    id = "Test User ID",
                                    name = "Test Name",
                                    first_name = "Test Given Name",
                                    last_name = "Test Family Name",
                                    emails = new
                                    {
                                        preferred = "Test email"
                                    }
                                });
                            }

                            return null;
                        }
                    };
                    options.Notifications = new MicrosoftAccountAuthenticationNotifications
                    {
                        OnAuthenticated = context =>
                        {
                            var refreshToken = context.RefreshToken;
                            context.Principal.AddIdentity(new ClaimsIdentity(new Claim[] { new Claim("RefreshToken", refreshToken) }));
                            return Task.FromResult<object>(null);
                        }
                    };
                },
                context =>
                {
                    Describe(context.Response, context.User);
                    return true;
                });
            var properties = new AuthenticationProperties();
            var correlationKey = ".AspNet.Correlation.Microsoft";
            var correlationValue = "TestCorrelationId";
            properties.Dictionary.Add(correlationKey, correlationValue);
            properties.RedirectUri = "/me";
            var state = stateFormat.Protect(properties);
            var transaction = await SendAsync(server,
                "https://example.com/signin-microsoft?code=TestCode&state=" + Uri.EscapeDataString(state),
                correlationKey + "=" + correlationValue);
            transaction.Response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
            transaction.Response.Headers.Location.ToString().ShouldBe("/me");
            transaction.SetCookie.Count.ShouldBe(2);
            transaction.SetCookie[0].ShouldContain(correlationKey);
            transaction.SetCookie[1].ShouldContain(".AspNet.External");

            var authCookie = transaction.AuthenticationCookieValue;
            transaction = await SendAsync(server, "https://example.com/me", authCookie);
            transaction.Response.StatusCode.ShouldBe(HttpStatusCode.OK);
            transaction.FindClaimValue("RefreshToken").ShouldBe("Test Refresh Token");
        }
        public void NullPrincipalThrows()
        {
            var properties = new AuthenticationProperties();
            properties.RedirectUri = "bye";
            var ticket = new AuthenticationTicket(properties, "Hello");

            using (var stream = new MemoryStream())
            using (var writer = new BinaryWriter(stream))
            using (var reader = new BinaryReader(stream))
            {
                Assert.Throws<ArgumentNullException>(() => TicketSerializer.Write(writer, ticket));
            }
        }
        public void CanRoundTripEmptyPrincipal()
        {
            var properties = new AuthenticationProperties();
            properties.RedirectUri = "bye";
            var ticket = new AuthenticationTicket(new ClaimsPrincipal(), properties, "Hello");

            using (var stream = new MemoryStream())
            using (var writer = new BinaryWriter(stream))
            using (var reader = new BinaryReader(stream))
            {
                TicketSerializer.Write(writer, ticket);
                stream.Position = 0;
                var readTicket = TicketSerializer.Read(reader);
                readTicket.Principal.Identities.Count().ShouldBe(0);
                readTicket.Properties.RedirectUri.ShouldBe("bye");
                readTicket.AuthenticationScheme.ShouldBe("Hello");
            }
        }
 protected override async Task<AuthenticationTicket> GetUserInformationAsync(AuthenticationProperties properties, OpenIdConnectMessage message, AuthenticationTicket ticket)
 {
     var claimsIdentity = (ClaimsIdentity)ticket.Principal.Identity;
     if (claimsIdentity == null)
     {
         claimsIdentity = new ClaimsIdentity();
     }
     claimsIdentity.AddClaim(new Claim("test claim", "test value"));
     return new AuthenticationTicket(new ClaimsPrincipal(claimsIdentity), ticket.Properties, ticket.AuthenticationScheme);
 }