public async Task SendAsync_SuppressesAuthenticationChallenges_WhenNoChallengeIsSet()
        {
            // Arrange
            HttpMessageHandler inner   = CreateStubHandler();
            HttpMessageHandler handler = CreateProductUnderTest(inner);
            IOwinContext       context = CreateOwinContext();

            using (HttpRequestMessage request = CreateRequestWithOwinContextAndRequestContext(context))
            {
                // Act
                HttpResponseMessage ignore = await handler.SendAsync(request, CancellationToken.None);
            }

            // Assert
            IAuthenticationManager          authenticationManager = context.Authentication;
            AuthenticationResponseChallenge challenge             = authenticationManager.AuthenticationResponseChallenge;

            Assert.NotNull(challenge);
            string[] authenticationTypes = challenge.AuthenticationTypes;
            Assert.NotNull(authenticationTypes);
            string authenticationType = Assert.Single(authenticationTypes);

            Assert.Null(authenticationType);
        }
コード例 #2
0
        protected override Task ApplyResponseChallengeAsync()
        {
            if (Response.StatusCode != 401)
            {
                return(Task.FromResult <object>(null));
            }

            AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);

            if (challenge != null)
            {
                string baseUri =
                    Request.Scheme +
                    Uri.SchemeDelimiter +
                    Request.Host +
                    Request.PathBase;

                string currentUri =
                    baseUri +
                    Request.Path +
                    Request.QueryString;

                string redirectUri =
                    baseUri +
                    Options.CallbackPath;

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

                // OAuth2 10.12 CSRF
                GenerateCorrelationId(properties);

                // comma separated
                string scope = string.Join(" ", Options.Scope);

                string state = Options.StateDataFormat.Protect(properties);

                string authorizationEndpoint =
                    "https://accounts.google.com/o/oauth2/auth" +
                    "?response_type=code" +
                    "&client_id=" + Uri.EscapeDataString(Options.ClientId) +
                    "&redirect_uri=" + Uri.EscapeDataString(redirectUri) +
                    "&scope=" + Uri.EscapeDataString(scope) +
                    "&state=" + Uri.EscapeDataString(state);

                // Check if offline access was requested
                if (Options.RequestOfflineAccess)
                {
                    authorizationEndpoint += "&access_type=offline";
                }

                // Request the moment types
                if (Options.MomentTypes.Count > 0)
                {
                    authorizationEndpoint += String.Format("&request_visible_actions={0}",
                                                           String.Join(" ", Options.MomentTypes));
                }

                Response.Redirect(authorizationEndpoint);
            }

            return(Task.FromResult <object>(null));
        }
コード例 #3
0
        ///// <summary>
        ///// Handles Signout
        ///// </summary>
        ///// <returns></returns>
        //protected override async Task ApplyResponseGrantAsync()
        //{
        //    AuthenticationResponseRevoke signout = Helper.LookupSignOut(Options.AuthenticationType, Options.AuthenticationMode);
        //    if (signout == null)
        //    {
        //        return;
        //    }

        //    if (_configuration == null)
        //    {
        //        _configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.Request.CallCancelled);
        //    }

        //    SAML2Message wsFederationMessage = new SAML2Message()
        //    {
        //        IssuerAddress = _configuration.TokenEndpoint ?? string.Empty,
        //       // Wtrealm = Options.Wtrealm,
        //        //Wa = SAMLActions.SignOut,
        //    };

        //    // Set Wreply in order:
        //    // 1. properties.Redirect
        //    // 2. Options.SignOutWreply
        //    // 3. Options.Wreply
        //    AuthenticationProperties properties = signout.Properties;
        //    if (properties != null && !string.IsNullOrEmpty(properties.RedirectUri))
        //    {
        //       // wsFederationMessage.Wreply = properties.RedirectUri;
        //    }
        //    else if (!string.IsNullOrWhiteSpace(Options.SignOutWreply))
        //    {
        //       // wsFederationMessage.Wreply = Options.SignOutWreply;
        //    }
        //    else if (!string.IsNullOrWhiteSpace(Options.Wreply))
        //    {
        //       // wsFederationMessage.Wreply = Options.Wreply;
        //    }

        //    var notification = new RedirectToIdentityProviderNotification<SAML2Message, SAML2AuthenticationOptions>(Context, Options)
        //    {
        //        ProtocolMessage = wsFederationMessage
        //    };
        //    await Options.Notifications.RedirectToIdentityProvider(notification);

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

        /// <summary>
        /// Handles Challenge
        /// </summary>
        /// <returns></returns>
        protected override async Task ApplyResponseChallengeAsync()
        {
            if (Response.StatusCode != 401)
            {
                return;
            }

            AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);

            if (challenge == null)
            {
                return;
            }

            if (_configuration == null)
            {
                _configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.Request.CallCancelled);
            }

            string baseUri =
                Request.Scheme +
                Uri.SchemeDelimiter +
                Request.Host +
                Request.PathBase;

            string currentUri =
                baseUri +
                Request.Path +
                Request.QueryString;

            // Save the original challenge URI so we can redirect back to it when we're done.
            AuthenticationProperties properties = challenge.Properties;

            if (string.IsNullOrEmpty(properties.RedirectUri))
            {
                properties.RedirectUri = currentUri;
            }

            SAML2Message wsFederationMessage = new SAML2Message()
            {
                IssuerAddress = _configuration.TokenEndpoint ?? string.Empty,
                //  Wtrealm = Options.Wtrealm,
                //  Wctx = SAML2AuthenticationDefaults.WctxKey + "=" + Uri.EscapeDataString(Options.StateDataFormat.Protect(properties)),
                //Wa = SAMLActions.SignIn,

                //   PartnerSpId = "CN_WeChat_Ent",
                //  IdpAdapterId = "LoginForm",
                TargetResource = properties.RedirectUri
            };

            if (!string.IsNullOrWhiteSpace(Options.Wreply))
            {
                //wsFederationMessage.Wreply = Options.Wreply;
            }

            var notification = new RedirectToIdentityProviderNotification <SAML2Message, SAML2AuthenticationOptions>(Context, Options)
            {
                ProtocolMessage = wsFederationMessage
            };
            await Options.Notifications.RedirectToIdentityProvider(notification);

            if (!notification.HandledResponse)
            {
                string redirectUri = notification.ProtocolMessage.CreateSignInUrl();
                if (!Uri.IsWellFormedUriString(redirectUri, UriKind.Absolute))
                {
                    _logger.WriteWarning("The sign-in redirect URI is malformed: " + redirectUri);
                }
                Response.Redirect(redirectUri);
            }
        }
コード例 #4
0
        protected async override Task ApplyResponseChallengeAsync()
        {
            if (Response.StatusCode != 401)
            {
                return;
            }

            AuthenticationResponseChallenge challenge =
                Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);

            if (challenge != null)
            {
                var beforeRedirectContext = new AzureADBeforeRedirectContext(Context, Options);
                Options.Provider.BeforeRedirect(beforeRedirectContext);

                string baseUri =
                    Request.Scheme +
                    Uri.SchemeDelimiter +
                    Request.Host +
                    Request.PathBase;

                string currentUri =
                    baseUri +
                    Request.Path +
                    Request.QueryString;

                string redirectUri =
                    baseUri +
                    Options.CallbackPath;

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

                // OAuth2 10.12 CSRF
                GenerateCorrelationId(properties);

                var body = new List <KeyValuePair <string, string> >
                {
                    new KeyValuePair <string, string>("response_type", "code"),
                    new KeyValuePair <string, string>("client_id", Options.ClientId),
                    new KeyValuePair <string, string>("redirect_uri", redirectUri)
                };

                // AzureAD requires a specific resource to be used as the token audience
                if (String.IsNullOrEmpty(Options.Resource))
                {
                    Options.Resource = GraphResource;
                }

                AddToQueryString(body, properties, "resource", Options.Resource);
                AddToQueryString(body, properties, "prompt");
                AddToQueryString(body, properties, "login_hint");
                AddToQueryString(body, properties, "domain_hint");
                // Microsoft-specific parameter
                // msafed=0 forces the interpretation of login_hint as an organizational accoount
                // and does not present to user the Work vs. Personal account picker
                AddToQueryString(body, properties, "msafed");

                string state = Options.StateDataFormat.Protect(properties);
                body.Add(new KeyValuePair <string, string>("state", state));
                body.Add(new KeyValuePair <string, string>("nonce", state));

                var    queryString           = await new FormUrlEncodedContent(body).ReadAsStringAsync();
                string authorizationEndpoint = $"{String.Format(AuthorizeEndpointFormat, DetermineTenant(properties))}?{queryString}";

                if (Options.RequestLogging)
                {
                    _logger.WriteVerbose(String.Format("GET {0}", authorizationEndpoint));
                }

                var redirectContext = new AzureADApplyRedirectContext(Context, Options, properties, authorizationEndpoint);
                Options.Provider.ApplyRedirect(redirectContext);
            }

            return;
        }
コード例 #5
0
        protected override Task ApplyResponseChallengeAsync()
        {
            if (Response.StatusCode != 401)
            {
                return(Task.FromResult <object>(null));
            }

            AuthenticationResponseChallenge challenge =
                Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);

            if (challenge != null)
            {
                string baseUri =
                    Request.Scheme +
                    Uri.SchemeDelimiter +
                    Request.Host +
                    Request.PathBase;

                string currentUri =
                    baseUri +
                    Request.Path +
                    Request.QueryString;

                string redirectUri =
                    baseUri +
                    Options.CallbackPath;

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

                // OAuth2 10.12 CSRF
                GenerateCorrelationId(properties);

                var queryStrings = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
                // TODO: Live (MSA) doesn't yet support OpenID Connect i.e. id_token
                // when it does, switch to asking for id_token in addition to access_token and refresh_token
                //queryStrings.Add("response_type", "id_token code");
                queryStrings.Add("response_type", "code");
                queryStrings.Add("client_id", Options.ClientId);
                queryStrings.Add("redirect_uri", redirectUri);

                AddQueryString(queryStrings, properties, "scope", string.Join(" ", Options.Scope));
                AddQueryString(queryStrings, properties, "response_mode");
                AddQueryString(queryStrings, properties, "prompt");
                AddQueryString(queryStrings, properties, "login_hint");
                AddQueryString(queryStrings, properties, "domain_hint");

                string state = Options.StateDataFormat.Protect(properties);
                queryStrings.Add("state", state);
                //queryStrings.Add("nonce", state);

                string authorizationEndpoint =
                    WebUtilities.AddQueryString(String.Format(AuthorizeEndpointFormat, Options.Tenant), queryStrings);
                if (Options.RequestLogging)
                {
                    _logger.WriteInformation(String.Format("GET {0}", authorizationEndpoint));
                }
                Response.Redirect(authorizationEndpoint);
            }

            return(Task.FromResult <object>(null));
        }
        /// <summary>
        /// Handles SignIn
        /// </summary>
        /// <returns></returns>
        protected override async Task ApplyResponseChallengeAsync()
        {
            if (Response.StatusCode == 401)
            {
                AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);
                if (challenge == null)
                {
                    return;
                }

                // order for redirect_uri
                // 1. challenge.Properties.RedirectUri
                // 2. CurrentUri
                AuthenticationProperties properties = challenge.Properties;
                if (string.IsNullOrEmpty(properties.RedirectUri))
                {
                    properties.RedirectUri = CurrentUri;
                }

                // this value will be passed to the AuthorizationCodeReceivedNotification
                if (!string.IsNullOrWhiteSpace(Options.RedirectUri))
                {
                    properties.Dictionary.Add(OpenIdConnectAuthenticationDefaults.RedirectUriUsedForCodeKey, Options.RedirectUri);
                }

                if (_configuration == null)
                {
                    _configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.Request.CallCancelled);
                }

                OpenIdConnectMessage openIdConnectMessage = new OpenIdConnectMessage
                {
                    ClientId      = Options.ClientId,
                    IssuerAddress = _configuration.AuthorizationEndpoint ?? string.Empty,
                    RedirectUri   = Options.RedirectUri,
                    RequestType   = OpenIdConnectRequestType.Authentication,
                    Resource      = Options.Resource,
                    ResponseMode  = OpenIdConnectResponseMode.FormPost,
                    ResponseType  = Options.ResponseType,
                    Scope         = Options.Scope,
                    State         = OpenIdConnectAuthenticationDefaults.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;
        }
コード例 #7
0
        protected override Task ApplyResponseChallengeAsync()
        {
            if (Response.StatusCode != 401)
            {
                return(Task.FromResult <object>(null));
            }

            AuthenticationResponseChallenge challenge =
                Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);

            if (challenge != null)
            {
                var beforeRedirectContext = new MicrosoftOnlineBeforeRedirectContext(Context, Options);
                Options.Provider.BeforeRedirect(beforeRedirectContext);

                string baseUri =
                    Request.Scheme +
                    Uri.SchemeDelimiter +
                    Request.Host +
                    Request.PathBase;

                string currentUri =
                    baseUri +
                    Request.Path +
                    Request.QueryString;

                string redirectUri =
                    baseUri +
                    Options.CallbackPath;

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

                // OAuth2 10.12 CSRF
                GenerateCorrelationId(properties);

                var queryStrings = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase)
                {
                    { "response_type", "code" },
                    { "client_id", Options.ClientId },
                    { "redirect_uri", redirectUri }
                };
                AddQueryString(queryStrings, properties, "response_mode");
                AddQueryString(queryStrings, properties, "prompt");
                AddQueryString(queryStrings, properties, "login_hint");
                AddQueryString(queryStrings, properties, "domain_hint");

                // if AuthenticationProperties for this session specifies a scope property
                // it should take precedence over the value in AuthenticationOptions
                string scopeProperty;
                if (properties.Dictionary.TryGetValue(Constants.ScopeAuthenticationProperty, out scopeProperty) &&
                    !String.IsNullOrWhiteSpace(scopeProperty))
                {
                    // Assumption that scopeProperty is correctly formatted
                    AddQueryString(queryStrings, properties, "scope", scopeProperty);
                }
                else
                {
                    AddQueryString(queryStrings, properties, "scope", String.Join(" ", Options.Scope));
                }

                string state = Options.StateDataFormat.Protect(properties);
                queryStrings.Add("state", state);

                string authorizeEndpoint = WebUtilities.AddQueryString(ComposeAuthorizeEndpoint(properties), queryStrings);
                if (Options.RequestLogging)
                {
                    _logger.WriteVerbose(String.Format("GET {0}", authorizeEndpoint));
                }

                var redirectContext = new MicrosoftOnlineApplyRedirectContext(Context, Options, properties, authorizeEndpoint);
                Options.Provider.ApplyRedirect(redirectContext);
            }

            return(Task.FromResult <object>(null));
        }
コード例 #8
0
        protected override Task ApplyResponseChallengeAsync()
        {
            if (Response.StatusCode != 401)
            {
                return(Task.FromResult <object>(null));
            }

            AuthenticationResponseChallenge challenge =
                Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);

            if (challenge != null)
            {
                var beforeRedirectContext = new ZoomBeforeRedirectContext(Context, Options);
                Options.Provider.BeforeRedirect(beforeRedirectContext);

                string baseUri =
                    Request.Scheme +
                    Uri.SchemeDelimiter +
                    Request.Host +
                    Request.PathBase;

                string currentUri =
                    baseUri +
                    Request.Path +
                    Request.QueryString;

                string redirectUri =
                    baseUri +
                    Options.CallbackPath;

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

                // OAuth2 10.12 CSRF
                GenerateCorrelationId(properties);

                var queryStrings = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
                queryStrings.Add("response_type", "code");
                queryStrings.Add("client_id", Options.ClientId);
                queryStrings.Add("redirect_uri", redirectUri);

                string scope = string.Join(" ", Options.Scope);
                if (string.IsNullOrEmpty(scope))
                {
                    // default scope if app hasn't requested one
                    scope = "user:read";
                }
                queryStrings.Add("scope", scope);

                string state = Options.StateDataFormat.Protect(properties);
                queryStrings.Add("state", state);

                string authorizationEndpoint = WebUtilities.AddQueryString(AuthorizeEndpoint, queryStrings);

                var redirectContext =
                    new ZoomApplyRedirectContext(Context, Options, properties, authorizationEndpoint);
                Options.Provider.ApplyRedirect(redirectContext);
            }

            return(Task.FromResult <object>(null));
        }
コード例 #9
0
        /// <summary>
        /// Handles SignIn
        /// </summary>
        /// <returns></returns>
        protected override async Task ApplyResponseChallengeAsync()
        {
            if (Response.StatusCode == 401)
            {
                AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);
                if (challenge == null)
                {
                    return;
                }

                // order for redirect_uri
                // 1. challenge.Properties.RedirectUri
                // 2. CurrentUri
                AuthenticationProperties properties = challenge.Properties;
                if (string.IsNullOrEmpty(properties.RedirectUri))
                {
                    properties.RedirectUri = CurrentUri;
                }

                // this value will be passed to the AuthorizationCodeReceivedNotification
                if (!string.IsNullOrWhiteSpace(Options.RedirectUri))
                {
                    properties.Dictionary.Add(OpenIdConnectAuthenticationDefaults.RedirectUriUsedForCodeKey, Options.RedirectUri);
                }

                if (_configuration == null)
                {
                    _configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.Request.CallCancelled);
                }

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

                // Omitting the response_mode parameter when it already corresponds to the default
                // response_mode used for the specified response_type is recommended by the specifications.
                // See http://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#ResponseModes
                if (!string.Equals(Options.ResponseType, OpenIdConnectResponseType.Code, StringComparison.Ordinal) ||
                    !string.Equals(Options.ResponseMode, OpenIdConnectResponseMode.Query, StringComparison.Ordinal))
                {
                    openIdConnectMessage.ResponseMode = Options.ResponseMode;
                }

                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;
        }
コード例 #10
0
 public StubOwinMiddleware(int statusCode, AuthenticationResponseChallenge challenge)
     : base(null)
 {
     this.statusCode = statusCode;
     this.challenge  = challenge;
 }
コード例 #11
0
        protected override Task ApplyResponseChallengeAsync()
        {
            if (Response.StatusCode != 401)
            {
                return(Task.FromResult <object>(null));
            }

            AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);

            if (challenge != null)
            {
                string baseUri =
                    Request.Scheme +
                    Uri.SchemeDelimiter +
                    Request.Host +
                    Request.PathBase;

                string currentUri =
                    baseUri +
                    Request.Path +
                    Request.QueryString;

                string redirectUri =
                    baseUri +
                    Options.CallbackPath;

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

                // OAuth2 10.12 CSRF
                GenerateCorrelationId(Options.CookieManager, properties);

                // comma separated
                //string scope = string.Join(",", Options.Scope);

                string state = Options.StateDataFormat.Protect(properties);

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

                Response.Cookies.Append(StateCookie, Options.StateDataFormat.Protect(properties), cookieOptions);

                string authorizationEndpoint =
                    Options.AuthorizationEndpoint +
                    "?response_type=code" +
                    "&client_id=" + Uri.EscapeDataString(Options.AppId) +
                    "&redirect_uri=" + Uri.EscapeDataString(redirectUri) +
                    "&state=" + Uri.EscapeDataString(state);

                var redirectContext = new PurecloudApplyRedirectContext(
                    Context, Options,
                    properties, authorizationEndpoint);
                Options.Provider.ApplyRedirect(redirectContext);
            }

            return(Task.FromResult <object>(null));
        }
        protected override Task ApplyResponseChallengeAsync()
        {
            if (Response.StatusCode != 401)
            {
                return(Task.FromResult <object>(null));
            }

            AuthenticationResponseChallenge challenge =
                Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);

            if (challenge != null)
            {
                string baseUri =
                    Request.Scheme +
                    Uri.SchemeDelimiter +
                    Request.Host +
                    Request.PathBase;

                string currentUri =
                    baseUri +
                    Request.Path +
                    Request.QueryString;

                string redirectUri =
                    baseUri +
                    Options.CallbackPath;

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

                // OAuth2 10.12 CSRF
                GenerateCorrelationId(properties);

                var queryStrings = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
                queryStrings.Add("response_type", "code");
                queryStrings.Add("client_id", Options.ClientId);
                queryStrings.Add("redirect_uri", redirectUri);

                // concatenate with spaces for now, like scope, although this option isn't clearly documented
                string resource = string.Join(" ", Options.Resource);
                if (string.IsNullOrEmpty(resource))
                {
                    // AzureAD asks for at least one resource.
                    // If user didn't set it, set default resource to the AD Graph API.
                    resource = "https://graph.windows.net";
                }
                AddQueryString(queryStrings, properties, "resource", resource);
                AddQueryString(queryStrings, properties, "prompt");
                AddQueryString(queryStrings, properties, "login_hint");
                AddQueryString(queryStrings, properties, "domain_hint");
                // Microsoft-specific parameter
                // msafed=0 forces the interpretation of login_hint as an organizational accoount
                // and does not present to user the Work vs. Personal account picker
                AddQueryString(queryStrings, properties, "msafed");

                string state = Options.StateDataFormat.Protect(properties);
                queryStrings.Add("state", state);

                string authorizationEndpoint = WebUtilities.AddQueryString(AuthorizeEndpoint, queryStrings);
                if (Options.RequestLogging)
                {
                    _logger.WriteInformation(String.Format("GET {0}", authorizationEndpoint));
                }
                Response.Redirect(authorizationEndpoint);
            }

            return(Task.FromResult <object>(null));
        }
コード例 #13
0
        protected override Task ApplyResponseChallengeAsync()
        {
            logger.WriteInformation("ApplyResponseChallengeAsync::::Start");

            if (Response.StatusCode != 401)
            {
                logger.WriteInformation("ApplyResponseChallengeAsync::::if (Response.StatusCode != 401)");
                logger.WriteInformation("ApplyResponseChallengeAsync::::return Task.FromResult<object>(null);");
                logger.WriteInformation("ApplyResponseChallengeAsync::::End");
                return(Task.FromResult <object>(null));
            }

            AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);

            if (challenge != null)
            {
                //string requestPrefix = Request.Scheme + "://" + Request.Host;
                //string currentQueryString = Request.QueryString.Value;
                //string currentUri = string.IsNullOrEmpty(currentQueryString)
                //    ? requestPrefix + Request.PathBase + Request.Path
                //    : requestPrefix + Request.PathBase + Request.Path + "?" + currentQueryString;

                string baseUri =
                    Request.Scheme +
                    Uri.SchemeDelimiter +
                    Request.Host +
                    Request.PathBase;

                string currentUri =
                    baseUri +
                    Request.Path +
                    Request.QueryString;

                string redirectUri =
                    baseUri +
                    Options.CallbackPath;


                AuthenticationProperties properties = challenge.Properties;

                if (string.IsNullOrEmpty(properties.RedirectUri))
                {
                    logger.WriteInformation("ApplyResponseChallengeAsync::::properties.RedirectUri  is IsNullOrEmpty");

                    logger.WriteInformation("ApplyResponseChallengeAsync::::Set properties.RedirectUri = currentUri; currentUri:" + currentUri);

                    properties.RedirectUri = currentUri;
                }

                // OAuth2 10.12 CSRF
                GenerateCorrelationId(properties);

                // comma separated
                string scope = string.Join(" ", Options.Scope);

                string state = Options.StateDataFormat.Protect(properties);

                string authorizationEndpoint =
                    "https://api.weibo.com/oauth2/authorize" +
                    "?client_id=" + Uri.EscapeDataString(Options.AppId ?? string.Empty)
                    + "&redirect_uri=" + Uri.EscapeDataString(redirectUri)
                    + "&scope=" + Uri.EscapeDataString(scope)
                    + "&state=" + Uri.EscapeDataString(state)
                ;

                logger.WriteInformation("ApplyResponseChallengeAsync::::Response.Redirect(authorizationEndpoint);authorizationEndpoint:" + authorizationEndpoint);

                Response.Redirect(authorizationEndpoint);
            }

            logger.WriteInformation("ApplyResponseChallengeAsync::::return Task.FromResult<object>(null)");

            logger.WriteInformation("ApplyResponseChallengeAsync::::END");

            return(Task.FromResult <object>(null));
        }
        private async Task <bool> HandleChallengeAsync(AuthenticationResponseChallenge context)
        {
            // Extract the OpenID Connect request from the OWIN/Katana context.
            // If it cannot be found or doesn't correspond to an authorization
            // or a token request, throw an InvalidOperationException.
            var request = Context.GetOpenIdConnectRequest();

            if (request == null || (!request.IsAuthorizationRequest() && !request.IsTokenRequest()))
            {
                throw new InvalidOperationException("An OpenID Connect response cannot be returned from this endpoint.");
            }

            // Note: if an OpenID Connect response was already generated, throw an exception.
            var response = Context.GetOpenIdConnectResponse();

            if (response != null)
            {
                throw new InvalidOperationException("An OpenID Connect response has already been sent.");
            }

            // Create a new ticket containing an empty identity and
            // the authentication properties extracted from the challenge.
            var ticket = new AuthenticationTicket(new ClaimsIdentity(), context.Properties);

            // Prepare a new OpenID Connect response.
            response = new OpenIdConnectResponse
            {
                Error            = ticket.GetProperty(OpenIdConnectConstants.Properties.Error),
                ErrorDescription = ticket.GetProperty(OpenIdConnectConstants.Properties.ErrorDescription),
                ErrorUri         = ticket.GetProperty(OpenIdConnectConstants.Properties.ErrorUri)
            };

            // Remove the error/error_description/error_uri properties from the ticket.
            ticket.RemoveProperty(OpenIdConnectConstants.Properties.Error)
            .RemoveProperty(OpenIdConnectConstants.Properties.ErrorDescription)
            .RemoveProperty(OpenIdConnectConstants.Properties.ErrorUri);

            // If the request is an authorization request, attach the
            // redirect_uri and the state to the OpenID Connect response.
            if (request.IsAuthorizationRequest())
            {
                response.RedirectUri = request.GetProperty <string>(OpenIdConnectConstants.Properties.RedirectUri);
                response.State       = request.State;
            }

            if (string.IsNullOrEmpty(response.Error))
            {
                response.Error = request.IsAuthorizationRequest() ?
                                 OpenIdConnectConstants.Errors.AccessDenied :
                                 OpenIdConnectConstants.Errors.InvalidGrant;
            }

            if (string.IsNullOrEmpty(response.ErrorDescription))
            {
                response.ErrorDescription = request.IsAuthorizationRequest() ?
                                            "The authorization grant has been denied by the resource owner." :
                                            "The token request was rejected by the authorization server.";
            }

            if (request.IsAuthorizationRequest())
            {
                return(await SendAuthorizationResponseAsync(response, ticket));
            }

            return(await SendTokenResponseAsync(response, ticket));
        }
コード例 #15
0
        protected override async Task ApplyResponseChallengeAsync()
        {
            if (Response.StatusCode != 401)
            {
                return;
            }

            AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);

            if (challenge != null)
            {
                if (string.IsNullOrEmpty(Options.ProviderLoginUri))
                {
                    await DoYadisDiscoveryAsync();
                }

                if (!string.IsNullOrEmpty(Options.ProviderLoginUri))
                {
                    string requestPrefix = Request.Scheme + Uri.SchemeDelimiter + Request.Host;

                    var state = challenge.Properties;
                    if (String.IsNullOrEmpty(state.RedirectUri))
                    {
                        state.RedirectUri = requestPrefix + Request.PathBase + Request.Path + Request.QueryString;
                    }

                    // Anti-CSRF
                    GenerateCorrelationId(state);

                    string returnTo = BuildReturnTo(Options.StateDataFormat.Protect(state));

                    string authorizationEndpoint =
                        Options.ProviderLoginUri +
                        "?openid.ns=" + Uri.EscapeDataString("http://specs.openid.net/auth/2.0") +
                        "&openid.mode=" + Uri.EscapeDataString("checkid_setup") +
                        "&openid.claimed_id=" + Uri.EscapeDataString("http://specs.openid.net/auth/2.0/identifier_select") +
                        "&openid.identity=" + Uri.EscapeDataString("http://specs.openid.net/auth/2.0/identifier_select") +
                        "&openid.return_to=" + Uri.EscapeDataString(returnTo) +
                        "&openid.realm=" + Uri.EscapeDataString(requestPrefix) +

                        "&openid.ns.ax=" + Uri.EscapeDataString("http://openid.net/srv/ax/1.0") +
                        "&openid.ax.mode=" + Uri.EscapeDataString("fetch_request") +

                        "&openid.ax.type.email=" + Uri.EscapeDataString("http://axschema.org/contact/email") +
                        "&openid.ax.type.name=" + Uri.EscapeDataString("http://axschema.org/namePerson") +
                        "&openid.ax.type.first=" + Uri.EscapeDataString("http://axschema.org/namePerson/first") +
                        "&openid.ax.type.last=" + Uri.EscapeDataString("http://axschema.org/namePerson/last") +

                        "&openid.ax.type.email2=" + Uri.EscapeDataString("http://schema.openid.net/contact/email") +
                        "&openid.ax.type.name2=" + Uri.EscapeDataString("http://schema.openid.net/namePerson") +
                        "&openid.ax.type.first2=" + Uri.EscapeDataString("http://schema.openid.net/namePerson/first") +
                        "&openid.ax.type.last2=" + Uri.EscapeDataString("http://schema.openid.net/namePerson/last") +

                        "&openid.ax.required=" + Uri.EscapeDataString("email,name,first,last,email2,name2,first2,last2");

                    // allow protocol extensions to add their own attributes to the endpoint URL
                    var endpoint = new OpenIDAuthorizationEndpointInfo()
                    {
                        Url = authorizationEndpoint
                    };
                    foreach (var protocolExtension in Options.ProtocolExtensions)
                    {
                        await protocolExtension.OnChallengeAsync(challenge, endpoint);
                    }

                    Response.StatusCode = 302;
                    Response.Headers.Set("Location", endpoint.Url);
                }
            }
        }
 private Task <bool> HandleChallengeAsync(AuthenticationResponseChallenge context)
 => HandleChallengeAsync(context.Properties);
        protected override Task ApplyResponseChallengeAsync()
        {
            if (Response.StatusCode != 401)
            {
                return(Task.FromResult <object>(null));
            }

            AuthenticationResponseChallenge challenge =
                Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);

            if (challenge != null)
            {
                string baseUri =
                    Request.Scheme +
                    Uri.SchemeDelimiter +
                    Request.Host +
                    Request.PathBase;

                string currentUri =
                    baseUri +
                    Request.Path +
                    Request.QueryString;

                string redirectUri =
                    baseUri +
                    Options.CallbackPath;

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

                // OAuth2 10.12 CSRF
                GenerateCorrelationId(properties);

                var queryStrings = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
                queryStrings.Add("responseType", "code");
                queryStrings.Add("clientId", Options.ClientId);
                queryStrings.Add("redirectUri", redirectUri);

                // default scope
                if (Options.Scope.Count == 0)
                {
                    Options.Scope.Add(DefaultScope);
                }
                AddQueryString(queryStrings, properties, "scope", string.Join(",", Options.Scope));

                if (!String.IsNullOrEmpty(Options.AppName))
                {
                    AddQueryString(queryStrings, properties, "appName", Options.AppName);
                }
                if (!String.IsNullOrEmpty(Options.AppLogoUrl))
                {
                    AddQueryString(queryStrings, properties, "appLogoUrl", Options.AppLogoUrl);
                }

                string state = Options.StateDataFormat.Protect(properties);
                queryStrings.Add("state", state);

                string authorizationEndpoint = WebUtilities.AddQueryString(AuthorizeEndpoint, queryStrings);

                var redirectContext = new BlueJeansApplyRedirectContext(
                    Context, Options,
                    properties, authorizationEndpoint);
                Options.Provider.ApplyRedirect(redirectContext);
            }

            return(Task.FromResult <object>(null));
        }
コード例 #18
0
        protected override Task ApplyResponseChallengeAsync()
        {
            if (Response.StatusCode != 401)
            {
                return(Task.FromResult <object>(null));
            }

            AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);

            if (challenge != null)
            {
                string baseUri =
                    Request.Scheme +
                    Uri.SchemeDelimiter +
                    Request.Host +
                    Request.PathBase;

                string currentUri =
                    baseUri +
                    Request.Path +
                    Request.QueryString;

                string redirectUri =
                    baseUri +
                    Options.CallbackPath;

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

                // OAuth2 10.12 CSRF
                GenerateCorrelationId(properties);

                // comma separated
                string scope = string.Join(",", Options.Scope);

                string state = Options.StateDataFormat.Protect(properties);

                var client = new OAuthRequest
                {
                    ConsumerKey     = Options.ClientId,
                    ConsumerSecret  = Options.ClientSecret,
                    Type            = OAuthRequestType.RequestToken,
                    SignatureMethod = OAuthSignatureMethod.HmacSha1,
                    RequestUrl      = RequestTokenEndpoint,
                    Version         = "1.0",
                    Method          = "POST"
                };
                var auth = client.GetAuthorizationHeader().Replace("OAuth ", "");
                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth", auth);
                var response = _httpClient.PostAsync(client.RequestUrl, null).Result;
                response.EnsureSuccessStatusCode();
                var textArray  = response.Content.ReadAsStringAsync().Result.Split('&');
                var parameters = "?" + textArray.First(i => i.Contains("oauth_token="));

                OAuthState       = state;
                OAuthTokenSecret = textArray.First(i => i.Contains("oauth_token_secret=")).Replace("oauth_token_secret=", "");

                Response.Redirect(AuthenticateEndpoint + parameters);
            }

            return(Task.FromResult <object>(null));
        }
コード例 #19
0
ファイル: OwinResponse.net45.cs プロジェクト: zhangrl/katana
 public void Challenge(string[] authenticationTypes, AuthenticationExtra extra)
 {
     StatusCode = 401;
     AuthenticationResponseChallenge = new AuthenticationResponseChallenge(authenticationTypes, extra);
 }
コード例 #20
0
        /// <summary>
        /// Handles SignIn
        /// </summary>
        /// <returns></returns>
        protected override async Task ApplyResponseChallengeAsync()
        {
            if (Response.StatusCode == 401)
            {
                AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);
                if (challenge == null)
                {
                    return;
                }

                // order for redirect_uri
                // 1. challenge.Properties.RedirectUri
                // 2. CurrentUri
                AuthenticationProperties properties = challenge.Properties;
                if (string.IsNullOrEmpty(properties.RedirectUri))
                {
                    properties.RedirectUri = CurrentUri;
                }

                // this value will be passed to the AuthorizationCodeReceivedNotification
                if (!string.IsNullOrWhiteSpace(Options.RedirectUri))
                {
                    properties.Dictionary.Add(OpenIdConnectAuthenticationDefaults.RedirectUriUsedForCodeKey, Options.RedirectUri);
                }

                if (_configuration == null)
                {
                    _configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.Request.CallCancelled);
                }

                OpenIdConnectMessage openIdConnectMessage = new OpenIdConnectMessage
                {
                    ClientId      = Options.ClientId,
                    IssuerAddress = _configuration.AuthorizationEndpoint ?? string.Empty,
                    RedirectUri   = Options.RedirectUri,
                    RequestType   = OpenIdConnectRequestType.Authentication,
                    Resource      = Options.Resource,
                    ResponseType  = Options.ResponseType,
                    Scope         = Options.Scope
                };

                // https://tools.ietf.org/html/rfc7636
                if (Options.UsePkce && Options.ResponseType == OpenIdConnectResponseType.Code)
                {
                    using (RandomNumberGenerator randomNumberGenerator = RandomNumberGenerator.Create())
                        using (HashAlgorithm hash = SHA256.Create())
                        {
                            byte[] bytes = new byte[32];
                            randomNumberGenerator.GetBytes(bytes);
                            string codeVerifier = TextEncodings.Base64Url.Encode(bytes);

                            // Store this for use during the code redemption.
                            properties.Dictionary.Add(OAuthConstants.CodeVerifierKey, codeVerifier);
                            byte[] challengeBytes = hash.ComputeHash(Encoding.UTF8.GetBytes(codeVerifier));
                            string codeChallenge  = TextEncodings.Base64Url.Encode(challengeBytes);

                            openIdConnectMessage.Parameters.Add(OAuthConstants.CodeChallengeKey, codeChallenge);
                            openIdConnectMessage.Parameters.Add(OAuthConstants.CodeChallengeMethodKey, OAuthConstants.CodeChallengeMethodS256);
                        }
                }

                openIdConnectMessage.State = OpenIdConnectAuthenticationDefaults.AuthenticationPropertiesKey + "=" + Uri.EscapeDataString(Options.StateDataFormat.Protect(properties));

                // Omitting the response_mode parameter when it already corresponds to the default
                // response_mode used for the specified response_type is recommended by the specifications.
                // See http://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#ResponseModes
                if (!string.Equals(Options.ResponseType, OpenIdConnectResponseType.Code, StringComparison.Ordinal) ||
                    !string.Equals(Options.ResponseMode, OpenIdConnectResponseMode.Query, StringComparison.Ordinal))
                {
                    openIdConnectMessage.ResponseMode = Options.ResponseMode;
                }

                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;
        }
コード例 #21
0
        protected override Task ApplyResponseChallengeAsync()
        {
            if (Response.StatusCode != 401)
            {
                return(Task.FromResult <object>(null));
            }

            AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);

            if (challenge != null)
            {
                string baseUri =
                    Request.Scheme +
                    Uri.SchemeDelimiter +
                    Request.Host +
                    Request.PathBase;

                string currentUri =
                    baseUri +
                    Request.Path +
                    Request.QueryString;

                string redirectUri =
                    baseUri +
                    Options.CallbackPath;

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

                GenerateCorrelationId(properties);

                string scope = string.Join(",", Options.Scope);

                string state = Options.StateDataFormat.Protect(properties);

                //storing the original state value in a cookie and add it to the cookie collection
                HttpCookie stateCookie = new HttpCookie("state", state);
                HttpContext.Current.Response.Cookies.Add(stateCookie);

                //shortening the state string as Dropbox API generates an error for strings longer than 200 bytes
                string csrf_state = state.Substring(0, 200);

                //storing the shortened state value in a cookie and add it to the cookie collection
                HttpCookie csrfStateCookie = new HttpCookie("csrf_state", csrf_state);
                HttpContext.Current.Response.Cookies.Add(csrfStateCookie);

                string authorizationEndpoint =
                    "https://www.dropbox.com/1/oauth2/authorize" +
                    "?response_type=code" +
                    "&client_id=" + Uri.EscapeDataString(Options.AppKey) +
                    "&redirect_uri=" + Uri.EscapeDataString(redirectUri) +
                    "&scope=" + Uri.EscapeDataString(scope) +
                    "&state=" + Uri.EscapeDataString(csrf_state);

                Response.Redirect(authorizationEndpoint);
            }

            return(Task.FromResult <object>(null));
        }
コード例 #22
0
        protected override Task ApplyResponseChallengeAsync()
        {
            if (Response.StatusCode != 401)
            {
                return(Task.FromResult <object>(null));
            }

            AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);

            if (challenge != null)
            {
                string baseUri =
                    Request.Scheme +
                    Uri.SchemeDelimiter +
                    Request.Host +
                    Request.PathBase;

                string currentUri =
                    baseUri +
                    Request.Path +
                    Request.QueryString;

                string redirectUri =
                    baseUri +
                    Options.CallbackPath;

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

                // OAuth2 10.12 CSRF
                GenerateCorrelationId(properties);

                var queryStrings = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
                queryStrings.Add("response_type", "code");
                queryStrings.Add("client_id", Options.ClientId);
                queryStrings.Add("redirect_uri", redirectUri);

                // space separated
                string scope = string.Join(" ", Options.Scope);
                if (string.IsNullOrEmpty(scope))
                {
                    // Google OAuth 2.0 asks for non-empty scope. If user didn't set it, set default scope to
                    // "openid profile email" to get basic user information.
                    scope = "openid profile email";
                }
                AddQueryString(queryStrings, properties, "scope", scope);

                AddQueryString(queryStrings, properties, "access_type", Options.AccessType);
                AddQueryString(queryStrings, properties, "approval_prompt");
                AddQueryString(queryStrings, properties, "login_hint");

                string state = Options.StateDataFormat.Protect(properties);
                queryStrings.Add("state", state);

                string authorizationEndpoint = WebUtilities.AddQueryString(AuthorizeEndpoint,
                                                                           queryStrings);

                var redirectContext = new GoogleOAuth2ApplyRedirectContext(
                    Context, Options,
                    properties, authorizationEndpoint);
                Options.Provider.ApplyRedirect(redirectContext);
            }

            return(Task.FromResult <object>(null));
        }
コード例 #23
0
        /// <summary>
        /// Handles Challenge
        /// </summary>
        /// <returns></returns>
        protected override async Task ApplyResponseChallengeAsync()
        {
            if (Response.StatusCode == 401)
            {
                AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);
                if (challenge == null)
                {
                    return;
                }

                string baseUri =
                    Request.Scheme +
                    Uri.SchemeDelimiter +
                    Request.Host +
                    Request.PathBase;

                string currentUri =
                    baseUri +
                    Request.Path +
                    Request.QueryString;

                // Save the original challenge URI so we can redirect back to it when we're done.
                AuthenticationProperties properties = challenge.Properties;
                if (string.IsNullOrEmpty(properties.RedirectUri))
                {
                    properties.RedirectUri = currentUri;
                }

                WsFederationMessage wsFederationMessage = new WsFederationMessage()
                {
                    IssuerAddress = Options.IssuerAddress ?? string.Empty,
                    Wtrealm       = Options.Wtrealm,
                    Wctx          = WsFederationAuthenticationDefaults.WctxKey + "=" + Uri.EscapeDataString(Options.StateDataFormat.Protect(properties)),
                };
                if (!string.IsNullOrWhiteSpace(Options.Wreply))
                {
                    wsFederationMessage.Wreply = Options.Wreply;
                }

                if (Options.Notifications != null && Options.Notifications.RedirectToIdentityProvider != null)
                {
                    RedirectToIdentityProviderNotification <WsFederationMessage> notification =
                        new RedirectToIdentityProviderNotification <WsFederationMessage> {
                        ProtocolMessage = wsFederationMessage
                    };
                    await Options.Notifications.RedirectToIdentityProvider(notification);

                    if (notification.Cancel)
                    {
                        return;
                    }
                }

                string redirect = wsFederationMessage.CreateSignInQueryString();
                if (!Uri.IsWellFormedUriString(redirect, UriKind.Absolute))
                {
                    _logger.WriteError(string.Format(CultureInfo.InvariantCulture, "The WsFederation sign-in redirect uri is not well formed: '{0}'", redirect));
                    return;
                }

                Response.Redirect(redirect);
            }

            return;
        }
コード例 #24
0
        /// <summary>
        /// Handles Challenge
        /// </summary>
        /// <returns></returns>
        protected override async Task ApplyResponseChallengeAsync()
        {
            if (Response.StatusCode != 401)
            {
                return;
            }

            AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);

            if (challenge == null)
            {
                return;
            }

            string baseUri =
                Request.Scheme +
                Uri.SchemeDelimiter +
                Request.Host +
                Request.PathBase;

            string currentUri =
                baseUri +
                Request.Path +
                Request.QueryString;

            // Save the original challenge URI so we can redirect back to it when we're done.
            AuthenticationProperties properties = challenge.Properties;

            if (string.IsNullOrEmpty(properties.RedirectUri))
            {
                properties.RedirectUri = currentUri;
            }

            SamlMessage SamlMessage = await SamlMessageFromRequest();

            {
                //IssuerAddress = _configuration.TokenEndpoint ?? string.Empty,
                //Wtrealm = Options.Wtrealm,
                //Wctx = SamlAuthenticationDefaults.WctxKey + "=" + Uri.EscapeDataString(Options.StateDataFormat.Protect(properties)),
                //Wa = SamlActions.SignIn,
            };

            //if (!string.IsNullOrWhiteSpace(Options.Wreply))
            //{
            //    SamlMessage.Wreply = Options.Wreply;
            //}

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

            if (!notification.HandledResponse)
            {
                string redirectUri = notification.ProtocolMessage.BuildRedirectUrl();
                if (!Uri.IsWellFormedUriString(redirectUri, UriKind.Absolute))
                {
                    _logger.WriteWarning("The sign-in redirect URI is malformed: " + redirectUri);
                }
                Response.Redirect(redirectUri);
            }
        }
コード例 #25
0
        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;
        }
コード例 #26
0
        protected override Task ApplyResponseChallengeAsync()
        {
            if (Response.StatusCode != 401)
            {
                return(Task.FromResult <object>(null));
            }

            AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);

            if (challenge != null)
            {
                string baseUri =
                    Request.Scheme +
                    Uri.SchemeDelimiter +
                    Request.Host +
                    Request.PathBase;

                string currentUri =
                    baseUri +
                    Request.Path +
                    Request.QueryString;

                string redirectUri =
                    baseUri +
                    Options.CallbackPath;

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

                // OAuth2 10.12 CSRF
                GenerateCorrelationId(Options.CookieManager, properties);

                var queryStrings = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
                queryStrings.Add("response_type", "code");
                queryStrings.Add("client_id", Options.ClientId);
                queryStrings.Add("redirect_uri", redirectUri);

                var acrValues = string.Join(" ", Options.AcrValues);
                if (!string.IsNullOrEmpty(acrValues))
                {
                    queryStrings.Add("acr_values", acrValues);
                }

                // space separated
                string scope = string.Join(" ", Options.Scope);
                if (string.IsNullOrEmpty(scope))
                {
                    scope = "openid email";
                }
                AddQueryString(queryStrings, properties, "scope", scope);

                AddQueryString(queryStrings, properties, "access_type", Options.AccessType);
                AddQueryString(queryStrings, properties, "approval_prompt");
                AddQueryString(queryStrings, properties, "prompt");
                AddQueryString(queryStrings, properties, "login_hint");
                AddQueryString(queryStrings, properties, "include_granted_scopes");

                string state = Options.StateDataFormat.Protect(properties);
                queryStrings.Add("state", state);

                string authorizationEndpoint = WebUtilities.AddQueryString(Options.AuthorizationEndpoint,
                                                                           queryStrings);

                var redirectContext = new NortonApplyRedirectContext(
                    Context, Options,
                    properties, authorizationEndpoint);
                Options.Provider.ApplyRedirect(redirectContext);
            }

            return(Task.FromResult <object>(null));
        }
コード例 #27
0
        /// <summary>
        ///  执行401跳转
        /// </summary>
        /// <returns></returns>
        protected override Task ApplyResponseChallengeAsync()
        {
            // return base.ApplyResponseChallengeAsync();

            if (Response.StatusCode != 401)
            {
                return(Task.FromResult <object>(null));
            }
            AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);

            if (challenge != null)
            {
                string baseUri = Request.Scheme + Uri.SchemeDelimiter + Request.Host + Request.PathBase;

                string currentUri = baseUri + Request.Path + Request.QueryString;

                string redirectUri = baseUri + Options.CallbackPath;

                AuthenticationProperties extra = challenge.Properties;

                if (string.IsNullOrEmpty(extra.RedirectUri))
                {
                    extra.RedirectUri = currentUri;
                }

                // OAuth2 10.12 CSRF
                GenerateCorrelationId(extra);
                string stateId  = GenerateStateId(extra);
                string scope    = null;
                string endPoint = null;
                scope    = Options.Scope;
                endPoint = MPAuthorizationEndpoint;
                bool hasHost = !string.IsNullOrWhiteSpace(base.Options.ApiHost);

                if (hasHost)
                {
                    string host = base.Options.ApiHost;
                    Uri    uri;

                    if (Options.ApiHost.IndexOf(":") > 0 && Uri.TryCreate(host, UriKind.RelativeOrAbsolute, out uri))
                    {
                        Uri endPointUri = new Uri(endPoint);
                        endPoint = new Uri(uri, endPointUri.PathAndQuery).ToString();
                    }
                    else
                    {
                        endPoint = new UriBuilder(endPoint)
                        {
                            Host = host
                        }.ToString();
                    }
                }
                string authorizationEndpoint = string.Format(endPoint + "?appid={0}&redirect_uri={1}&response_type=code&scope={2}&state={3}#wechat_redirect",
                                                             Uri.EscapeDataString(Options.AppId),
                                                             Uri.EscapeDataString(redirectUri),
                                                             Uri.EscapeDataString(scope),
                                                             Uri.EscapeDataString(stateId));

                Context.Response.Redirect(authorizationEndpoint);

                // var redirectContext = new WeixinApplyRedirectContext(Context, Options, extra, authorizationEndpoint);
                //Options.Provider.ApplyRedirect(redirectContext);
            }
            return(Task.FromResult <object>(null));
        }