internal OpenIdConnectValidateClientRedirectUriContext(
     IOwinContext context,
     OpenIdConnectServerOptions options,
     OpenIdConnectMessage authorizationRequest)
     : base(context, options, authorizationRequest)
 {
 }
Beispiel #2
0
        protected override void AddNonceToMessage(OpenIdConnectMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            var properties = new AuthenticationProperties();
            var nonce = Options.ProtocolValidator.GenerateNonce();
            properties.Dictionary.Add(
                NonceProperty, nonce);
            message.Nonce = nonce;

            //computing the hash of nonce and appending it to the cookie name
            string nonceKey = GetNonceKey(nonce);
            var cookieOptions = new CookieOptions
            {
                HttpOnly = true,
                Secure = Request.IsSecure,
            };
            var nonceId = Convert.ToBase64String(Encoding.UTF8.GetBytes((Options.StateDataFormat.Protect(properties))));
            Response.Cookies.Append(
                nonceKey,
                nonceId,
                cookieOptions);
        }
        public void OpenIdConnectMessage_Defaults()
        {
            List<string> errors = new List<string>();
            OpenIdConnectMessage message = new OpenIdConnectMessage();
            
            if (message.AcrValues != null)
                errors.Add("message.ArcValues != null");

            if (message.ClientAssertion != null)
                errors.Add("message.ClientAssertion != null");

            if (message.ClientAssertionType != null)
                errors.Add("message.ClientAssertionType != null");

            if (message.ClaimsLocales != null)
                errors.Add("message.ClaimsLocales != null");

            if (message.ClientId != null)
                errors.Add("message.ClientId != null");

            if (message.ClientSecret != null)
                errors.Add("message.ClientSecret != null");

            if (message.Code != null)
                errors.Add("message.Code != null");

            if (message.Display != null)
                errors.Add("message.Display != null");

            if (message.IdTokenHint != null)
                errors.Add("message.IdTokenHint != null");

            if (message.LoginHint != null)
                errors.Add("message.LoginHint != null");

            if (message.MaxAge != null)
                errors.Add("message.MaxAge != null");

            if (message.Prompt != null)
                errors.Add("message.Prompt != null");

            if (message.RedirectUri != null)
                errors.Add("message.RedirectUri != null");

            if (message.State != null)
                errors.Add("message.State != null");

            if (message.UiLocales != null)
                errors.Add("message.UiLocales != null");

            if (errors.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                foreach (string error in errors)
                    sb.AppendLine(error);

                Assert.Fail("OpenIdConnectMessage_Defaults *** Test Failures:\n" + sb.ToString());
            }
        }
 public OpenIdConnectTokenEndpointResponse(JObject jsonResponse)
 {
     JsonResponse = jsonResponse;
     Message = new OpenIdConnectMessage()
     {
         AccessToken = JsonResponse.Value<string>(OpenIdConnectParameterNames.AccessToken),
         IdToken = JsonResponse.Value<string>(OpenIdConnectParameterNames.IdToken),
         TokenType = JsonResponse.Value<string>(OpenIdConnectParameterNames.TokenType),
         ExpiresIn = JsonResponse.Value<string>(OpenIdConnectParameterNames.ExpiresIn)
     };
 }
 public void OpenIdConnectMessage_Constructors()
 {
     OpenIdConnectMessage openIdConnectMessage = new OpenIdConnectMessage();
     Assert.AreEqual(openIdConnectMessage.IssuerAddress, string.Empty);
     openIdConnectMessage = new OpenIdConnectMessage("http://www.got.jwt.com");
     Assert.AreEqual(openIdConnectMessage.IssuerAddress, "http://www.got.jwt.com");
     ExpectedException expectedException = ExpectedException.ArgumentNullException("issuerAddress");
     try
     {
         openIdConnectMessage = new OpenIdConnectMessage((string)null);
         expectedException.ProcessNoException();
     }
     catch (Exception exception)
     {
         expectedException.ProcessException(exception);
     }
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="OpenIdConnectMessage"/> class.
        /// </summary>
        /// <param name="other"> an <see cref="OpenIdConnectMessage"/> to copy.</param>
        /// <exception cref="ArgumentNullException"> if 'other' is null.</exception>
        protected OpenIdConnectMessage(OpenIdConnectMessage other)
        {
            if (other == null)
            {
                throw new ArgumentNullException("other");
            }

            foreach (KeyValuePair<string, string> keyValue in other.Parameters)
            {
                SetParameter(keyValue.Key, keyValue.Value);
            }

            AuthorizationEndpoint = other.AuthorizationEndpoint;
            IssuerAddress = other.IssuerAddress;
            RequestType = other.RequestType;
            TokenEndpoint = other.TokenEndpoint;
        }
Beispiel #7
0
        protected override string RetrieveNonce(OpenIdConnectMessage message)
        {
            if (message.IdToken == null)
            {
                return null;
            }

            JwtSecurityToken token = new JwtSecurityToken(message.IdToken);
            if (token == null)
            {
                return null;
            }

            //computing the hash of nonce and appending it to the cookie name
            string nonceKey = GetNonceKey(token.Payload.Nonce);
            string nonceCookie = Request.Cookies[nonceKey];
            if (string.IsNullOrWhiteSpace(nonceCookie))
            {
                _logger.WriteWarning("The nonce cookie was not found.");
                return null;
            }

            var cookieOptions = new CookieOptions
            {
                HttpOnly = true,
                Secure = Request.IsSecure
            };

            Response.Cookies.Delete(nonceKey, cookieOptions);

            string nonce = null;
            AuthenticationProperties nonceProperties =
                Options.StateDataFormat.Unprotect(Encoding.UTF8.GetString(Convert.FromBase64String(nonceCookie)));
            if (nonceProperties != null)
            {
                nonceProperties.Dictionary.TryGetValue(NonceProperty, out nonce);
            }
            else
            {
                _logger.WriteWarning("Failed to un-protect the nonce cookie.");
            }

            return nonce;
        }
 /// <summary>
 /// Inserts the ambient <see cref="OpenIdConnectMessage"/> response in the OWIN context.
 /// </summary>
 /// <param name="context">The OWIN context.</param>
 /// <param name="response">The ambient <see cref="OpenIdConnectMessage"/>.</param>
 public static void SetOpenIdConnectResponse(this IOwinContext context, OpenIdConnectMessage response)
 {
     context.SetOpenIdConnectMessage(OpenIdConnectConstants.Environment.Response, response);
 }
        private static void SetOpenIdConnectMessage(this IOwinContext context, string key, OpenIdConnectMessage message)
        {
            if (context == null) {
                throw new ArgumentNullException("context");
            }

            if (string.IsNullOrWhiteSpace(key)) {
                throw new ArgumentException("key");
            }

            if (message == null) {
                context.Environment.Remove(key + OpenIdConnectConstants.Environment.Message);
                context.Environment.Remove(key + OpenIdConnectConstants.Environment.Parameters);

                return;
            }

            var parameters = new ReadOnlyDictionary<string, string[]>(
                message.Parameters.ToDictionary(
                    keySelector: parameter => parameter.Key,
                    elementSelector: parameter => new[] { parameter.Value }));

            context.Set(key + OpenIdConnectConstants.Environment.Message, message);
            context.Set(key + OpenIdConnectConstants.Environment.Parameters, parameters);
        }
 public async Task AuthenticateCoreState(Action<OpenIdConnectAuthenticationOptions> action, OpenIdConnectMessage message)
 {
     var handler = new OpenIdConnectAuthenticationHandlerForTestingAuthenticate();
     var server = CreateServer(new ConfigureOptions<OpenIdConnectAuthenticationOptions>(action), UrlEncoder.Default, handler);
     await server.CreateClient().PostAsync("http://localhost", new FormUrlEncodedContent(message.Parameters.Where(pair => pair.Value != null)));
 }
        public async Task AuthenticateCore(LogLevel logLevel, int[] expectedLogIndexes, Action<OpenIdConnectAuthenticationOptions> action, OpenIdConnectMessage message)
        {
            var errors = new List<Tuple<LogEntry, LogEntry>>();
            var expectedLogs = LoggingUtilities.PopulateLogEntries(expectedLogIndexes);
            var handler = new OpenIdConnectAuthenticationHandlerForTestingAuthenticate();
            var loggerFactory = new InMemoryLoggerFactory(logLevel);
            var server = CreateServer(new ConfigureOptions<OpenIdConnectAuthenticationOptions>(action), UrlEncoder.Default, loggerFactory, handler);

            await server.CreateClient().PostAsync("http://localhost", new FormUrlEncodedContent(message.Parameters));
            LoggingUtilities.CheckLogs(loggerFactory.Logger.Logs, expectedLogs, errors);
            Debug.WriteLine(LoggingUtilities.LoggingErrors(errors));
            Assert.True(errors.Count == 0, LoggingUtilities.LoggingErrors(errors));
        }
 public void OpenIdConnectMessage_NullFormParameters()
 {
     List<KeyValuePair<string, string[]>> formData = new List<KeyValuePair<string, string[]>>();
     formData.Add(new KeyValuePair<string, string[]>("key", new string[] { "data" }));
     formData.Add(new KeyValuePair<string, string[]>("nullData", new string[] { null }));
     formData.Add(new KeyValuePair<string, string[]>("emptyData", new string[] { string.Empty }));
     formData.Add(new KeyValuePair<string, string[]>(null, new string[] { null }));
     formData.Add(new KeyValuePair<string, string[]>(null, null));
     OpenIdConnectMessage msg = new OpenIdConnectMessage(formData);
     Assert.IsNotNull(msg);
 }
        public void OpenIdConnectMessage_IssuerAddressHasQuery()
        {
            List<string> errors = new List<string>();
            var address = "http://gotJwt.onmicrosoft.com/?foo=bar";
            var clientId = Guid.NewGuid().ToString();
            var message = new OpenIdConnectMessage(address);

            var url = message.BuildRedirectUrl();
            Report("1", errors, url, address);

            message.ClientId = clientId;
            url = message.BuildRedirectUrl();
            var expected = string.Format(CultureInfo.InvariantCulture, @"{0}&client_id={1}", address, clientId);

            Report("2", errors, url, expected);
        }
        public void OpenIdConnectMessage_GetSets()
        {
            OpenIdConnectMessage message = new OpenIdConnectMessage();
            Type type = typeof(OpenIdConnectMessage);
            PropertyInfo[] properties = type.GetProperties();
            if (properties.Length != 47)
                Assert.Fail("Number of public fields has changed from 47 to: " + properties.Length + ", adjust tests");

            GetSetContext context =
                new GetSetContext
                {
                    PropertyNamesAndSetGetValue = new List<KeyValuePair<string, List<object>>>
                    {
                        new KeyValuePair<string, List<object>>("IssuerAddress", new List<object>{string.Empty, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("AuthorizationEndpoint", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("AccessToken", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("AcrValues", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("ClaimsLocales", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("ClientAssertion", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("ClientAssertionType", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("ClientId", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("ClientSecret", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("Code", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("Display", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("DomainHint", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("Error",  new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("ErrorDescription",  new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("ErrorUri",  new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("ExpiresIn",  new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("GrantType", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("IdToken", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("IdTokenHint", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("IdentityProvider", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("MaxAge", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("Password", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("PostLogoutRedirectUri", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("Prompt", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("RedirectUri", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("RequestUri", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("ResponseMode", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("ResponseType", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("Resource", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("Scope", new List<object>{null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("SessionState", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("State", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("TargetLinkUri", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("Token", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("TokenEndpoint", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("TokenType", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("UiLocales", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("UserId", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("Username", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                    },

                    Object = message,
                };

            TestUtilities.GetSet(context);

            if (context.Errors.Count != 0)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine(Environment.NewLine);
                foreach (string str in context.Errors)
                    sb.AppendLine(str);

                Assert.Fail(sb.ToString());
            }
        }
        public void OpenIdConnectMessage_Publics()
        {
            string issuerAddress = "http://gotJwt.onmicrosoft.com";
            string customParameterName = "Custom Parameter Name";
            string customParameterValue = "Custom Parameter Value";
            string nonce = Guid.NewGuid().ToString();
            string redirectUri = "http://gotJwt.onmicrosoft.com/signedIn";
            string resource = "location data";

            List<string> errors = new List<string>();

            // Empty string
            OpenIdConnectMessage message = new OpenIdConnectMessage();

            string url = message.BuildRedirectUrl();
            string expected = string.Format(CultureInfo.InvariantCulture, @"");
            Report("1", errors, url, expected);

            message.ResponseMode = OpenIdConnectResponseModes.FormPost;
            message.ResponseType = OpenIdConnectResponseTypes.CodeIdToken;
            message.Scope = OpenIdConnectScopes.OpenIdProfile;

            url = message.BuildRedirectUrl();
            expected = string.Format(CultureInfo.InvariantCulture, @"?response_mode=form_post&response_type=code+id_token&scope=openid+profile");
            Report("1a", errors, url, expected);

            // Nonce added
            message.Nonce = nonce;
            url = message.BuildRedirectUrl();
            expected = string.Format(CultureInfo.InvariantCulture, @"?response_mode=form_post&response_type=code+id_token&scope=openid+profile&nonce={0}", nonce);
            Report("2", errors, url, expected);

            // IssuerAddress only
            message = new OpenIdConnectMessage(issuerAddress);
            message.ResponseMode = OpenIdConnectResponseModes.FormPost;
            message.ResponseType = OpenIdConnectResponseTypes.CodeIdToken;
            message.Scope = OpenIdConnectScopes.OpenIdProfile;
            message.Nonce = nonce;

            url = message.BuildRedirectUrl();
            expected = string.Format(CultureInfo.InvariantCulture, @"{0}?response_mode=form_post&response_type=code+id_token&scope=openid+profile&nonce={1}", issuerAddress, nonce);
            Report("3", errors, url, expected);

            // IssuerAdderss and Redirect_uri
            message.RedirectUri = redirectUri;
            url = message.BuildRedirectUrl();
            expected = string.Format(CultureInfo.InvariantCulture, @"{0}?response_mode=form_post&response_type=code+id_token&scope=openid+profile&nonce={1}&redirect_uri={2}", issuerAddress, message.Nonce, HttpUtility.UrlEncode(redirectUri));
            Report("4", errors, url, expected);

            // IssuerAdderss empty and Redirect_uri
            message.IssuerAddress = string.Empty;
            url = message.BuildRedirectUrl();
            expected = string.Format(CultureInfo.InvariantCulture, @"?response_mode=form_post&response_type=code+id_token&scope=openid+profile&nonce={0}&redirect_uri={1}", message.Nonce, HttpUtility.UrlEncode(redirectUri));
            Report("5", errors, url, expected);

            // IssuerAdderss, Redirect_uri, Response
            message = new OpenIdConnectMessage(issuerAddress);
            message.ResponseMode = OpenIdConnectResponseModes.FormPost;
            message.ResponseType = OpenIdConnectResponseTypes.CodeIdToken;
            message.Scope = OpenIdConnectScopes.OpenIdProfile;
            message.Nonce = nonce;
            message.RedirectUri = redirectUri;
            message.Resource = resource;
            url = message.BuildRedirectUrl();
            expected = string.Format(CultureInfo.InvariantCulture, @"{0}?response_mode=form_post&response_type=code+id_token&scope=openid+profile&nonce={1}&redirect_uri={2}&resource={3}", issuerAddress, message.Nonce, HttpUtility.UrlEncode(redirectUri), HttpUtility.UrlEncode(resource));
            Report("6", errors, url, expected);

            // IssuerAdderss, Redirect_uri, Response, customParam
            message = new OpenIdConnectMessage(issuerAddress);
            message.ResponseMode = OpenIdConnectResponseModes.FormPost;
            message.ResponseType = OpenIdConnectResponseTypes.CodeIdToken;
            message.Scope = OpenIdConnectScopes.OpenIdProfile;
            message.Nonce = nonce;
            message.Parameters.Add(customParameterName, customParameterValue);
            message.RedirectUri = redirectUri;
            message.Resource = resource;
            url = message.BuildRedirectUrl();
            expected = string.Format(CultureInfo.InvariantCulture, @"{0}?response_mode=form_post&response_type=code+id_token&scope=openid+profile&nonce={1}&{2}={3}&redirect_uri={4}&resource={5}", issuerAddress, message.Nonce, HttpUtility.UrlEncode(customParameterName), HttpUtility.UrlEncode(customParameterValue), HttpUtility.UrlEncode(redirectUri), HttpUtility.UrlEncode(resource));
            Report("7", errors, url, expected);

            if (errors.Count != 0)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine(Environment.NewLine);
                foreach (string str in errors)
                    sb.AppendLine(str);

                Assert.Fail(sb.ToString());
            }
        }
 /// <summary>
 /// Inserts the ambient <see cref="OpenIdConnectMessage"/> request in the OWIN context.
 /// </summary>
 /// <param name="context">The OWIN context.</param>
 /// <param name="request">The ambient <see cref="OpenIdConnectMessage"/>.</param>
 public static void SetOpenIdConnectRequest(this IOwinContext context, OpenIdConnectMessage request)
 {
     context.SetOpenIdConnectMessage(OpenIdConnectConstants.Environment.Request, request);
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="OpenIdConnectMessage"/> class.
        /// </summary>
        /// <param name="other"> an <see cref="OpenIdConnectMessage"/> to copy.</param>
        /// <exception cref="ArgumentNullException"> if 'other' is null.</exception>
        protected OpenIdConnectMessage(OpenIdConnectMessage other)
        {
            if (other == null)
            {
                throw new ArgumentNullException("other");
            }

            foreach (KeyValuePair<string, string> keyValue in other.Parameters)
            {
                SetParameter(keyValue.Key, keyValue.Value);
            }

            IssuerAddress = other.IssuerAddress;
        }
        protected override async Task ApplyResponseChallengeAsync()
        {
            if (Response.StatusCode == 401)
            {
                AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);
                if (challenge == null)
                {
                    return;
                }

                AuthenticationProperties properties = challenge.Properties;
                if (string.IsNullOrEmpty(properties.RedirectUri))
                {
                    properties.RedirectUri = CurrentUri;
                }

                if (!string.IsNullOrWhiteSpace(Options.RedirectUri))
                {
                    properties.Dictionary.Add(OpenIdConnectAuthenticationDefaults.RedirectUriUsedForCodeKey, Options.RedirectUri);
                }

                // Enable Per-Policy Metadata Retreival
                string policy;
                if (properties.Dictionary.TryGetValue(PolicyParameter, out policy))
                {
                    B2CConfigurationManager mgr = Options.ConfigurationManager as B2CConfigurationManager;
                    _configuration = await mgr.GetConfigurationAsync(Context.Request.CallCancelled, policy);
                }
                else 
                {
                    throw new Exception("For B2C, you must pass a policy parameter in every challenge.");
                    return;
                }

                OpenIdConnectMessage openIdConnectMessage = new OpenIdConnectMessage
                {
                    ClientId = Options.ClientId,
                    IssuerAddress = _configuration.AuthorizationEndpoint ?? string.Empty,
                    RedirectUri = Options.RedirectUri,
                    RequestType = OpenIdConnectRequestType.AuthenticationRequest,
                    Resource = Options.Resource,
                    ResponseMode = OpenIdConnectResponseModes.FormPost,
                    ResponseType = Options.ResponseType,
                    Scope = Options.Scope,
                    State = AuthenticationPropertiesKey + "=" + Uri.EscapeDataString(Options.StateDataFormat.Protect(properties)),
                };

                if (Options.ProtocolValidator.RequireNonce)
                {
                    AddNonceToMessage(openIdConnectMessage);
                }

                var notification = new RedirectToIdentityProviderNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions>(Context, Options)
                {
                    ProtocolMessage = openIdConnectMessage
                };

                await Options.Notifications.RedirectToIdentityProvider(notification);

                if (!notification.HandledResponse)
                {
                    string redirectUri = notification.ProtocolMessage.CreateAuthenticationRequestUrl();
                    if (!Uri.IsWellFormedUriString(redirectUri, UriKind.Absolute))
                    {
                        _logger.WriteWarning("The authenticate redirect URI is malformed: " + redirectUri);
                    }
                    Response.Redirect(redirectUri);
                }
            }

            return;
        }
        public void OpenIdConnectMessage_Defaults()
        {
            List<string> errors = new List<string>();

            OpenIdConnectMessage message = new OpenIdConnectMessage();

            if (message.AcrValues != null)
                errors.Add("message.ArcValues != null");

            if (message.ClientAssertion != null)
                errors.Add("message.ClientAssertion != null");

            if (message.ClientAssertionType != null)
                errors.Add("message.ClientAssertionType != null");

            if (message.ClaimsLocales != null)
                errors.Add("message.ClaimsLocales != null");

            if (message.ClientId != null)
                errors.Add("message.ClientId != null");

            if (message.ClientSecret != null)
                errors.Add("message.ClientSecret != null");

            if (message.Code != null)
                errors.Add("message.Code != null");

            if (message.Display != null)
                errors.Add("message.Display != null");

            if (message.IdTokenHint != null)
                errors.Add("message.IdTokenHint != null");

            if (message.LoginHint != null)
                errors.Add("message.LoginHint != null");

            if (message.MaxAge != null)
                errors.Add("message.MaxAge != null");

            if (string.IsNullOrWhiteSpace(message.Nonce))
                errors.Add("message.Nonce was null or whitespace.");

            if (message.Prompt != null)
                errors.Add("message.Prompt != null");

            if (message.RedirectUri != null)
                errors.Add("message.RedirectUri != null");

            if (message.ResponseMode != OpenIdConnectMessage.DefaultResponseMode)
                errors.Add(string.Format(CultureInfo.InvariantCulture, "message.ResponseMode: '{0}' != OpenIdConnectMessage.DefaultResponseMode: '{1}'", message.ResponseMode, OpenIdConnectMessage.DefaultResponseMode));

            if (message.ResponseType != OpenIdConnectMessage.DefaultResponseType)
                errors.Add(string.Format(CultureInfo.InvariantCulture, "message.ResponseType: '{0}' != OpenIdConnectMessage.DefaultResponseType: '{1}'", message.ResponseMode, OpenIdConnectMessage.DefaultResponseType));

            if (message.Scope != OpenIdConnectMessage.DefaultScope)
                errors.Add(string.Format(CultureInfo.InvariantCulture, "message.Scope: '{0}' != OpenIdConnectMessage.DefaultScope: '{1}'", message.Scope, OpenIdConnectMessage.DefaultScope));

            if (message.State != null)
                errors.Add("message.State != null");

            if (message.UiLocales != null)
                errors.Add("message.UiLocales != null");

            if (errors.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                foreach (string error in errors)
                    sb.AppendLine(error);

                Assert.Fail("OpenIdConnectMessage_Defaults *** Test Failures:\n" + sb.ToString());
            }
        }
        protected override async Task ApplyResponseGrantAsync()
        {
            AuthenticationResponseRevoke signout = Helper.LookupSignOut(Options.AuthenticationType, Options.AuthenticationMode);
            if (signout != null)
            {
                AuthenticationProperties properties = signout.Properties;

                // Enable Per-Policy Metadata Retreival
                string policy;
                if (properties.Dictionary.TryGetValue(PolicyParameter, out policy))
                {
                    B2CConfigurationManager mgr = Options.ConfigurationManager as B2CConfigurationManager;
                    _configuration = await mgr.GetConfigurationAsync(Context.Request.CallCancelled, policy);
                }
                else
                {
                    throw new Exception("For B2C, you must pass a policy parameter in every sign out request.");
                }

                OpenIdConnectMessage openIdConnectMessage = new OpenIdConnectMessage()
                {
                    IssuerAddress = _configuration.EndSessionEndpoint ?? string.Empty,
                    RequestType = OpenIdConnectRequestType.LogoutRequest,
                };

                string redirect = string.Empty;
                if (properties != null && !string.IsNullOrEmpty(properties.RedirectUri))
                {
                    openIdConnectMessage.PostLogoutRedirectUri = properties.RedirectUri;
                    redirect = properties.RedirectUri;
                }
                else if (!string.IsNullOrWhiteSpace(Options.PostLogoutRedirectUri))
                {
                    openIdConnectMessage.PostLogoutRedirectUri = Options.PostLogoutRedirectUri;
                    redirect = Options.RedirectUri;
                }

                if (string.IsNullOrWhiteSpace(openIdConnectMessage.PostLogoutRedirectUri))
                {
                    throw new Exception("For B2C, the PostLogoutRedirectUri is required.");
                }
                if (string.IsNullOrWhiteSpace(redirect))
                {
                    throw new Exception("For B2C, the RedirectUri is required.");
                }

                var notification = new RedirectToIdentityProviderNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions>(Context, Options)
                {
                    ProtocolMessage = openIdConnectMessage
                };
                await Options.Notifications.RedirectToIdentityProvider(notification);

                if (!notification.HandledResponse)
                {
                    string redirectUri = notification.ProtocolMessage.CreateLogoutRequestUrl();
                    redirectUri = redirectUri + "&" +  OpenIdConnectParameterNames.RedirectUri + "=" + HttpUtility.UrlEncode(redirect) + "&" + OpenIdConnectParameterNames.ClientId + "=" + Options.ClientId;
                    if (!Uri.IsWellFormedUriString(redirectUri, UriKind.Absolute))
                    {
                        _logger.WriteWarning("The logout redirect URI is malformed: " + redirectUri);
                    }
                    Response.Redirect(redirectUri);
                }
            }
        }
        protected override async Task<AuthenticationTicket> AuthenticateCoreAsync()
        {
            if (Options.CallbackPath.HasValue && Options.CallbackPath != (Request.PathBase + Request.Path))
            {
                return null;
            }

            OpenIdConnectMessage openIdConnectMessage = null;

            if (string.Equals(Request.Method, "POST", StringComparison.OrdinalIgnoreCase)
              && !string.IsNullOrWhiteSpace(Request.ContentType)
              && Request.ContentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase)
              && Request.Body.CanRead)
            {
                if (!Request.Body.CanSeek)
                {
                    _logger.WriteVerbose("Buffering request body");
                    MemoryStream memoryStream = new MemoryStream();
                    await Request.Body.CopyToAsync(memoryStream);
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    Request.Body = memoryStream;
                }

                IFormCollection form = await Request.ReadFormAsync();
                Request.Body.Seek(0, SeekOrigin.Begin);

                openIdConnectMessage = new OpenIdConnectMessage(form);
            }

            if (openIdConnectMessage == null)
            {
                return null;
            }

            ExceptionDispatchInfo authFailedEx = null;
            string policy = string.Empty;
            try
            {
                var messageReceivedNotification = new MessageReceivedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions>(Context, Options)
                {
                    ProtocolMessage = openIdConnectMessage
                };
                await Options.Notifications.MessageReceived(messageReceivedNotification);
                if (messageReceivedNotification.HandledResponse)
                {
                    return GetHandledResponseTicket();
                }
                if (messageReceivedNotification.Skipped)
                {
                    return null;
                }

                AuthenticationProperties properties = GetPropertiesFromState(openIdConnectMessage.State);
                if (properties == null)
                {
                    _logger.WriteWarning("The state field is missing or invalid.");
                    return null;
                }

                string nonce = null;
                if (Options.ProtocolValidator.RequireNonce)
                {
                    nonce = RetrieveNonce(openIdConnectMessage);
                }

                if (!string.IsNullOrWhiteSpace(openIdConnectMessage.Error))
                {
                    throw new OpenIdConnectProtocolException(
                        string.Format(CultureInfo.InvariantCulture,
                                      openIdConnectMessage.Error,
                                      "", openIdConnectMessage.ErrorDescription ?? string.Empty, openIdConnectMessage.ErrorUri ?? string.Empty));
                }

                if (string.IsNullOrWhiteSpace(openIdConnectMessage.IdToken))
                {
                    _logger.WriteWarning("The id_token is missing.");
                    return null;
                }

                var securityTokenReceivedNotification = new SecurityTokenReceivedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions>(Context, Options)
                {
                    ProtocolMessage = openIdConnectMessage,
                };
                await Options.Notifications.SecurityTokenReceived(securityTokenReceivedNotification);
                if (securityTokenReceivedNotification.HandledResponse)
                {
                    return GetHandledResponseTicket();
                }
                if (securityTokenReceivedNotification.Skipped)
                {
                    return null;
                }

                // Enable Per-Policy Metadata Retreival
                if (properties.Dictionary.TryGetValue(PolicyParameter, out policy))
                {
                    B2CConfigurationManager mgr = Options.ConfigurationManager as B2CConfigurationManager;
                    _configuration = await mgr.GetConfigurationAsync(Context.Request.CallCancelled, policy);
                }
                else
                {
                    _logger.WriteWarning("No policy identifier was found in the Authentication Properties of the request.");
                    return null;
                }

                TokenValidationParameters tvp = Options.TokenValidationParameters.Clone();
                IEnumerable<string> issuers = new[] { _configuration.Issuer };
                tvp.ValidIssuers = (tvp.ValidIssuers == null ? issuers : tvp.ValidIssuers.Concat(issuers));
                tvp.IssuerSigningTokens = (tvp.IssuerSigningTokens == null ? _configuration.SigningTokens : tvp.IssuerSigningTokens.Concat(_configuration.SigningTokens));

                SecurityToken validatedToken;
                ClaimsPrincipal principal = Options.SecurityTokenHandlers.ValidateToken(openIdConnectMessage.IdToken, tvp, out validatedToken);
                ClaimsIdentity claimsIdentity = principal.Identity as ClaimsIdentity;

                JwtSecurityToken jwt = validatedToken as JwtSecurityToken;
                AuthenticationTicket ticket = new AuthenticationTicket(claimsIdentity, properties);

                if (!string.IsNullOrWhiteSpace(openIdConnectMessage.SessionState))
                {
                    ticket.Properties.Dictionary[OpenIdConnectSessionProperties.SessionState] = openIdConnectMessage.SessionState;
                }

                if (!string.IsNullOrWhiteSpace(_configuration.CheckSessionIframe))
                {
                    ticket.Properties.Dictionary[OpenIdConnectSessionProperties.CheckSessionIFrame] = _configuration.CheckSessionIframe;
                }

                if (Options.UseTokenLifetime)
                {
                    DateTime issued = jwt.ValidFrom;
                    if (issued != DateTime.MinValue)
                    {
                        ticket.Properties.IssuedUtc = issued.ToUniversalTime();
                    }
                    DateTime expires = jwt.ValidTo;
                    if (expires != DateTime.MinValue)
                    {
                        ticket.Properties.ExpiresUtc = expires.ToUniversalTime();
                    }
                    ticket.Properties.AllowRefresh = false;
                }

                var securityTokenValidatedNotification = new SecurityTokenValidatedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions>(Context, Options)
                {
                    AuthenticationTicket = ticket,
                    ProtocolMessage = openIdConnectMessage,
                };
                await Options.Notifications.SecurityTokenValidated(securityTokenValidatedNotification);
                if (securityTokenValidatedNotification.HandledResponse)
                {
                    return GetHandledResponseTicket();
                }
                if (securityTokenValidatedNotification.Skipped)
                {
                    return null;
                }
                ticket = securityTokenValidatedNotification.AuthenticationTicket;

                var protocolValidationContext = new OpenIdConnectProtocolValidationContext
                {
                    AuthorizationCode = openIdConnectMessage.Code,
                    Nonce = nonce,
                };

                Options.ProtocolValidator.Validate(jwt, protocolValidationContext);
                if (openIdConnectMessage.Code != null)
                {
                    var authorizationCodeReceivedNotification = new AuthorizationCodeReceivedNotification(Context, Options)
                    {
                        AuthenticationTicket = ticket,
                        Code = openIdConnectMessage.Code,
                        JwtSecurityToken = jwt,
                        ProtocolMessage = openIdConnectMessage,
                        RedirectUri = ticket.Properties.Dictionary.ContainsKey(OpenIdConnectAuthenticationDefaults.RedirectUriUsedForCodeKey) ?
                            ticket.Properties.Dictionary[OpenIdConnectAuthenticationDefaults.RedirectUriUsedForCodeKey] : string.Empty,
                    };
                    await Options.Notifications.AuthorizationCodeReceived(authorizationCodeReceivedNotification);
                    if (authorizationCodeReceivedNotification.HandledResponse)
                    {
                        return GetHandledResponseTicket();
                    }
                    if (authorizationCodeReceivedNotification.Skipped)
                    {
                        return null;
                    }
                    ticket = authorizationCodeReceivedNotification.AuthenticationTicket;
                }

                return ticket;
            }
            catch (Exception exception)
            {
                authFailedEx = ExceptionDispatchInfo.Capture(exception);
            }

            if (authFailedEx != null)
            {
                _logger.WriteError("Exception occurred while processing message: '" + authFailedEx.ToString());

                if (Options.RefreshOnIssuerKeyNotFound && authFailedEx.SourceException.GetType().Equals(typeof(SecurityTokenSignatureKeyNotFoundException)))
                {
                    B2CConfigurationManager mgr = Options.ConfigurationManager as B2CConfigurationManager;
                    mgr.RequestRefresh(policy);
                }

                var authenticationFailedNotification = new AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions>(Context, Options)
                {
                    ProtocolMessage = openIdConnectMessage,
                    Exception = authFailedEx.SourceException
                };
                await Options.Notifications.AuthenticationFailed(authenticationFailedNotification);
                if (authenticationFailedNotification.HandledResponse)
                {
                    return GetHandledResponseTicket();
                }
                if (authenticationFailedNotification.Skipped)
                {
                    return null;
                }

                authFailedEx.Throw();
            }

            return null;
        }
 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);
 }