public SnakeCaseQueryValueProvider(
     BindingSource bindingSource, 
     IReadableStringCollection values, 
     CultureInfo culture)
     : base(bindingSource, values, culture)
 {
 }
 public CookiesFeature(string key, string value)
 {
     _cookies = new ReadableStringCollection(new Dictionary<string, string[]>()
     {
         { key, new[] { value } }
     });
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="OAuthValidateClientAuthenticationContext"/> class
 /// </summary>
 /// <param name="context"></param>
 /// <param name="options"></param>
 /// <param name="parameters"></param>
 public OAuthValidateClientAuthenticationContext(
     IOwinContext context,
     OAuthAuthorizationServerOptions options,
     IReadableStringCollection parameters)
     : base(context, options, null)
 {
     Parameters = parameters;
 }
 /// <summary>
 /// Creates a provider for <see cref="IReadableStringCollection"/> wrapping an existing set of key value pairs.
 /// </summary>
 /// <param name="bindingSource">The <see cref="BindingSource"/> for the data.</param>
 /// <param name="values">The key value pairs to wrap.</param>
 /// <param name="culture">The culture to return with ValueProviderResult instances.</param>
 public ReadableStringCollectionValueProvider(
     [NotNull] BindingSource bindingSource,
     [NotNull] IReadableStringCollection values, 
     CultureInfo culture)
     : base(bindingSource)
 {
     _values = values;
     _culture = culture;
 }
        public RequestCookiesFeature(IReadableStringCollection cookies)
        {
            if (cookies == null)
            {
                throw new ArgumentNullException(nameof(cookies));
            }

            _parsedValues = cookies;
        }
        public QueryFeature(IReadableStringCollection query)
        {
            if (query == null)
            {
                throw new ArgumentNullException(nameof(query));
            }

            _parsedValues = query;
        }
        /// <summary>
        /// Creates a new instance populated with values from the form encoded body parameters.
        /// </summary>
        /// <param name="parameters">Form encoded body parameters from a request.</param>
        public TokenEndpointRequest(IReadableStringCollection parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            Func<string, string> getParameter = parameters.Get;

            Parameters = parameters;
            GrantType = getParameter(Constants.Parameters.GrantType);
            ClientId = getParameter(Constants.Parameters.ClientId);
            if (String.Equals(GrantType, Constants.GrantTypes.AuthorizationCode, StringComparison.Ordinal))
            {
                AuthorizationCodeGrant = new TokenEndpointRequestAuthorizationCode
                {
                    Code = getParameter(Constants.Parameters.Code),
                    RedirectUri = getParameter(Constants.Parameters.RedirectUri),
                };
            }
            else if (String.Equals(GrantType, Constants.GrantTypes.ClientCredentials, StringComparison.Ordinal))
            {
                ClientCredentialsGrant = new TokenEndpointRequestClientCredentials
                {
                    Scope = (getParameter(Constants.Parameters.Scope) ?? string.Empty).Split(' ')
                };
            }
            else if (String.Equals(GrantType, Constants.GrantTypes.RefreshToken, StringComparison.Ordinal))
            {
                RefreshTokenGrant = new TokenEndpointRequestRefreshToken
                {
                    RefreshToken = getParameter(Constants.Parameters.RefreshToken),
                    Scope = (getParameter(Constants.Parameters.Scope) ?? string.Empty).Split(' ')
                };
            }
            else if (String.Equals(GrantType, Constants.GrantTypes.Password, StringComparison.Ordinal))
            {
                ResourceOwnerPasswordCredentialsGrant = new TokenEndpointRequestResourceOwnerPasswordCredentials
                {
                    UserName = getParameter(Constants.Parameters.Username),
                    Password = getParameter(Constants.Parameters.Password),
                    Scope = (getParameter(Constants.Parameters.Scope) ?? string.Empty).Split(' ')
                };
            }
            else if (!String.IsNullOrEmpty(GrantType))
            {
                CustomExtensionGrant = new TokenEndpointRequestCustomExtension
                {
                    Parameters = parameters,
                };
            }
        }
        /// <summary>
        /// Creates a new instance populated with values from the form encoded body parameters.
        /// </summary>
        /// <param name="parameters">Form encoded body parameters from a request.</param>
        public TokenEndpointRequest(IReadableStringCollection parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            Parameters = parameters;
            GrantType = parameters[Constants.Parameters.GrantType];
            ClientId = parameters[Constants.Parameters.ClientId];
            if (string.Equals(GrantType, Constants.GrantTypes.AuthorizationCode, StringComparison.Ordinal))
            {
                AuthorizationCodeGrant = new TokenEndpointRequestAuthorizationCode
                {
                    Code = parameters[Constants.Parameters.Code],
                    RedirectUri = parameters[Constants.Parameters.RedirectUri],
                };
            }
            else if (string.Equals(GrantType, Constants.GrantTypes.ClientCredentials, StringComparison.Ordinal))
            {
                ClientCredentialsGrant = new TokenEndpointRequestClientCredentials
                {
                    Scope = ((string)parameters[Constants.Parameters.Scope] ?? string.Empty).Split(' ')
                };
            }
            else if (string.Equals(GrantType, Constants.GrantTypes.RefreshToken, StringComparison.Ordinal))
            {
                RefreshTokenGrant = new TokenEndpointRequestRefreshToken
                {
                    RefreshToken = parameters[Constants.Parameters.RefreshToken],
                    Scope = ((string)parameters[Constants.Parameters.Scope] ?? string.Empty).Split(' ')
                };
            }
            else if (string.Equals(GrantType, Constants.GrantTypes.Password, StringComparison.Ordinal))
            {
                ResourceOwnerPasswordCredentialsGrant = new TokenEndpointRequestResourceOwnerPasswordCredentials
                {
                    UserName = parameters[Constants.Parameters.Username],
                    Password = parameters[Constants.Parameters.Password],
                    Scope = ((string)parameters[Constants.Parameters.Scope] ?? string.Empty).Split(' ')
                };
            }
            else if (!string.IsNullOrEmpty(GrantType))
            {
                CustomExtensionGrant = new TokenEndpointRequestCustomExtension
                {
                    Parameters = parameters,
                };
            }
        }
        /// <summary>
        /// Creates a new instance populated with values from the query string parameters.
        /// </summary>
        /// <param name="parameters">Query string parameters from a request.</param>
        public AuthorizeEndpointRequest(IReadableStringCollection parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            Scope = new List<string>();

            foreach (var parameter in parameters)
            {
                AddParameter(parameter.Key, parameters.Get(parameter.Key));
            }
        }
Exemple #10
0
        private QRCodeParameters ParseQRParamsFromQueryString(IReadableStringCollection query)
        {
            QRCodeParameters param = new QRCodeParameters();

            var text = query["text"];
            param.Text = text;

            var size = query["size"];
            string format = query["format"];

            int intSize = 0;
            if (int.TryParse(size, out intSize)) param.Size = intSize;

            if (!string.IsNullOrWhiteSpace(format) && supportedImageFormats.ContainsKey(format.ToLower())) param.ImageFormat = supportedImageFormats[format];

            return param;
        }
        public static ImageDisParameters AppendParameters(this ImageDisParameters param, IReadableStringCollection query)
        {
            foreach (var q in query)
            {
                int integer;
                bool boolean;

                if (int.TryParse(q.Value.First(), out integer))
                    param.Add(q.Key, integer);
                else if (bool.TryParse(q.Value.First(), out boolean))
                    param.Add(q.Key, boolean);
                else
                    param.Add(q.Key, q.Value.First());
            }

            return param;
        }
        /// <summary>
        /// Creates a provider for <see cref="IReadableStringCollection"/> wrapping an existing set of key value pairs.
        /// </summary>
        /// <param name="bindingSource">The <see cref="BindingSource"/> for the data.</param>
        /// <param name="values">The key value pairs to wrap.</param>
        /// <param name="culture">The culture to return with ValueProviderResult instances.</param>
        public ReadableStringCollectionValueProvider(
            BindingSource bindingSource,
            IReadableStringCollection values,
            CultureInfo culture)
            : base(bindingSource)
        {
            if (bindingSource == null)
            {
                throw new ArgumentNullException(nameof(bindingSource));
            }

            if (values == null)
            {
                throw new ArgumentNullException(nameof(values));
            }

            _values = values;
            _culture = culture;
        }
        public bool Equals(IReadableStringCollection other)
        {
            if (this.Count() != other.Count())
                return false;

            foreach (var kv in this)
            {
                var values1 = GetValues(kv.Key);
                var values2 = other.GetValues(kv.Key);

                var missing1 = values1.Except(values2).Any();
                var missing2 = values2.Except(values1).Any();

                if (missing1 || missing2)
                    return false;
            }

            return true;
        }
 public OwinRequest(IReadableStringCollection query, IFormCollection body)
 {
     _query = query;
     _body = body;
 }
Exemple #15
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app, IComponentContext container)
        {
            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)),

                    OnApplyRedirect = ctx =>
                    {
                        if (!new Func <IOwinRequest, bool>(x => {
                            IReadableStringCollection query = x.Query;
                            if ((query != null) && (query["X-Requested-With"] == "XMLHttpRequest"))
                            {
                                return(true);
                            }
                            IHeaderDictionary headers = x.Headers;
                            return((headers != null) && (headers["X-Requested-With"] == "XMLHttpRequest"));
                        })(ctx.Request))
                        {
                            ctx.Response.Redirect(ctx.RedirectUri);
                        }
                    }
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            app.UseOAuthBearerTokens(
                new OAuthAuthorizationServerOptions()
            {
                TokenEndpointPath         = new PathString("/Token"),
                Provider                  = container.Resolve <IOAuthAuthorizationServerProvider>(),
                AuthorizeEndpointPath     = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                // Note: Remove the following line before you deploy to production:
                AllowInsecureHttp = true
            });



            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
        private async Task<IReadableStringCollection> GetValueCollectionAsync()
        {
            if (_values == null)
            {
                Debug.Assert(_valuesFactory != null);
                _values = await _valuesFactory();
            }

            return _values;
        }
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                IReadableStringCollection query = Request.Query;

                properties = UnpackStateParameter(query);
                if (properties == null)
                {
                    _logger.WriteWarning("Invalid return state");
                    return(null);
                }

                // Anti-CSRF
                if (!ValidateCorrelationId(properties, _logger))
                {
                    return(new AuthenticationTicket(null, properties));
                }

                string ticket = GetTicketParameter(query);
                if (String.IsNullOrEmpty(ticket))
                {
                    // No ticket
                    return(new AuthenticationTicket(null, properties));
                }

                // Now, we need to get the ticket validated

                string validateUrl = Options.CasServerUrlBase + "/serviceValidate" +
                                     "?service=" + Uri.EscapeDataString(BuildReturnTo(GetStateParameter(query))) +
                                     "&ticket=" + Uri.EscapeDataString(ticket);

                HttpResponseMessage response = await _httpClient.GetAsync(validateUrl, Request.CallCancelled);

                response.EnsureSuccessStatusCode();
                var responseBody = await response.Content.ReadAsStringAsync();

                string validatedUserName = null;

                using (TextReader stringReader = new StringReader(responseBody))
                {
                    var xmlReaderSetting = new XmlReaderSettings();
                    xmlReaderSetting.ConformanceLevel = ConformanceLevel.Auto;
                    xmlReaderSetting.IgnoreWhitespace = true;
                    using (XmlReader xmlReader = XmlReader.Create(stringReader, xmlReaderSetting))
                    {
                        if (xmlReader.ReadToFollowing("cas:user"))
                        {
                            validatedUserName = xmlReader.ReadElementString();
                        }
                    }
                }

                if (String.IsNullOrEmpty(validatedUserName))
                {
                    return(new AuthenticationTicket(null, properties));
                }

                var identity = new ClaimsIdentity(Options.AuthenticationType);
                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, validatedUserName, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));
                identity.AddClaim(new Claim(ClaimTypes.Name, validatedUserName, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));

                var context = new CasAuthenticatedContext(
                    Context,
                    identity,
                    properties);

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError("Authentication failed", ex);
                return(new AuthenticationTicket(null, properties));
            }
        }
Exemple #18
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                string code  = null;
                string state = null;

                IReadableStringCollection query  = Request.Query;
                IList <string>            values = query.GetValues("code");
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }
                values = query.GetValues("state");
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }

                properties = Options.StateDataFormat.Unprotect(state);
                if (properties == null)
                {
                    return(null);
                }

                // OAuth2 10.12 CSRF
                if (!ValidateCorrelationId(properties, logger))
                {
                    return(new AuthenticationTicket(null, properties));
                }

                string requestPrefix = Request.Scheme + "://" + Request.Host;
                string redirectUri   = requestPrefix + Request.PathBase + Options.CallbackPath;

                // Build up the body for the token request
                var body = new List <KeyValuePair <string, string> >();
                body.Add(new KeyValuePair <string, string>("grant_type", "authorization_code"));
                body.Add(new KeyValuePair <string, string>("code", code));
                body.Add(new KeyValuePair <string, string>("redirect_uri", redirectUri));
                body.Add(new KeyValuePair <string, string>("state", state));
                body.Add(new KeyValuePair <string, string>("scope", string.Join(",", Options.Scope)));
                var request = new HttpRequestMessage(HttpMethod.Post, TokenEndpoint);
                request.Content = new FormUrlEncodedContent(body);

                // Request the token

                HttpResponseMessage tokenResponse =
                    await httpClient.PostAsync(TokenEndpoint, new FormUrlEncodedContent(body));

                tokenResponse.EnsureSuccessStatusCode();
                string text = await tokenResponse.Content.ReadAsStringAsync();

                // Deserializes the token response
                dynamic response     = JsonConvert.DeserializeObject <dynamic>(text);
                string  accessToken  = (string)response.access_token;
                string  expires      = (string)response.expires_in;
                string  refreshToken = (string)response.refresh_token;

                // Get the Reddit user
                HttpRequestMessage userRequest = new HttpRequestMessage(HttpMethod.Get, UserInfoEndpoint);
                userRequest.Headers.Add("User-Agent", "OWIN OAuth Provider");
                userRequest.Headers.Add("Authorization", "bearer " + Uri.EscapeDataString(accessToken) + "");
                HttpResponseMessage graphResponse = await httpClient.SendAsync(userRequest, Request.CallCancelled);

                graphResponse.EnsureSuccessStatusCode();
                text = await graphResponse.Content.ReadAsStringAsync();

                JObject user = JObject.Parse(text);

                var context = new RedditAuthenticatedContext(Context, user, accessToken, expires, refreshToken);
                context.Identity = new ClaimsIdentity(
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);
                if (!string.IsNullOrEmpty(context.Id))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.UserName, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.UserName))
                {
                    context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.UserName, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Link))
                {
                    context.Identity.AddClaim(new Claim("urn:reddit:url", context.Link, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.AccessToken))
                {
                    context.Identity.AddClaim(new Claim("urn:reddit:accesstoken", context.AccessToken, XmlSchemaString, Options.AuthenticationType));
                }
                context.Identity.AddClaim(new Claim("urn:reddit:overeighteen", context.OverEighteen.ToString()));
                context.Properties = properties;

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                logger.WriteError(ex.Message);
            }
            return(new AuthenticationTicket(null, properties));
        }
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                string access_token              = null;
                string useruin                   = null;
                string appKey                    = null;
                string sign                      = null;
                IReadableStringCollection query  = Request.Query;
                IList <string>            values = query.GetValues("access_token");
                if (values != null && values.Count == 1)
                {
                    access_token = values[0];
                }
                values = query.GetValues("useruin");
                if (values != null && values.Count == 1)
                {
                    useruin = values[0];
                }
                values = query.GetValues("app_oauth_id");
                if (values != null && values.Count == 1)
                {
                    appKey = values[0];
                }
                values = query.GetValues("sign");
                if (values != null && values.Count == 1)
                {
                    sign = values[0];
                }
                properties = new AuthenticationProperties()
                {
                    RedirectUri = Options.DefaultCallBack
                };
                if (appKey != Options.AppKey)
                {
                    return(null);
                }
                //todo:验证sign
                var context = new PaipaiAccountAuthenticatedContext(Context, access_token, useruin);

                context.Identity = new ClaimsIdentity(
                    new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, context.Id, ClaimValueTypes.String,
                              Options.AuthenticationType),
                    new Claim(ClaimTypes.Name, context.Name, ClaimValueTypes.String, Options.AuthenticationType),
                    new Claim("pp:UserUin", context.Id, ClaimValueTypes.String, Options.AuthenticationType),
                    new Claim("pp:AccessToken", context.AccessToken, ClaimValueTypes.String,
                              Options.AuthenticationType)
                },
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);


                await Options.Provider.Authenticated(context);

                context.Properties = properties;

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteWarning("Authentication failed", ex);
                return(new AuthenticationTicket(null, properties));
            }
        }
        //step 2.3
        //making AuthenticationTicket after client return from Vk.com
        //here we make actually autorization work
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                string code = "";

                IReadableStringCollection query  = Request.Query;
                IList <string>            values = query.GetValues("code");

                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }

                properties = Options.StateDataFormat.Unprotect(Options.StoreState);
                if (properties == null)
                {
                    return(null);
                }

                // OAuth2 10.12 CSRF
                if (!ValidateCorrelationId(properties, _logger))
                {
                    return(new AuthenticationTicket(null, properties));
                }

                string requestPrefix = Request.Scheme + Uri.SchemeDelimiter + Request.Host;
                string redirectUri   = requestPrefix + Request.PathBase + Options.CallbackPath;

                //https://oauth.vk.com/access_token?client_id=APP_ID&client_secret=APP_SECRET&code=7a6fa4dff77a228eeda56603b8f53806c883f011c40b72630bb50df056f6479e52a&redirect_uri=REDIRECT_URI
                string tokenRequest = TokenEndpoint + "?client_id=" + Uri.EscapeDataString(Options.AppId) +
                                      "&client_secret=" + Uri.EscapeDataString(Options.AppSecret) +
                                      "&code=" + Uri.EscapeDataString(code) +
                                      "&redirect_uri=" + Uri.EscapeDataString(redirectUri);

                HttpResponseMessage tokenResponse = await _httpClient.GetAsync(tokenRequest, Request.CallCancelled);

                tokenResponse.EnsureSuccessStatusCode();
                string text = await tokenResponse.Content.ReadAsStringAsync();

                //IFormCollection form = WebHelpers.ParseForm(text);
                var JsonResponse = JsonConvert.DeserializeObject <dynamic>(text);
                //JObject TokenResponse = JObject.Parse(text);

                string accessToken = JsonResponse["access_token"];
                string expires     = JsonResponse["expires_in"];
                string userid      = JsonResponse["user_id"];
                string email       = JsonResponse["email"];

                //public method which dont require token
                string userInfoLink = GraphApiEndpoint + "users.get.xml" +
                                      "?user_ids=" + Uri.EscapeDataString(userid) +
                                      "&fields=" + Uri.EscapeDataString("nickname,screen_name,photo_50");

                HttpResponseMessage graphResponse = await _httpClient.GetAsync(userInfoLink, Request.CallCancelled);

                graphResponse.EnsureSuccessStatusCode();
                text = await graphResponse.Content.ReadAsStringAsync();

                XmlDocument UserInfoResponseXml = new XmlDocument();
                UserInfoResponseXml.LoadXml(text);

                var context = new VkAuthenticatedContext(Context, UserInfoResponseXml, accessToken, expires, Options.PreferedNameClaim);
                context.Identity = new ClaimsIdentity(
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);

                if (!string.IsNullOrEmpty(context.Id))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.DefaultName))
                {
                    context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.DefaultName, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.FullName))
                {
                    context.Identity.AddClaim(new Claim("urn:vkontakte:name", context.FullName, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Link))
                {
                    context.Identity.AddClaim(new Claim("urn:vkontakte:link", context.Link, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(email))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Email, email, XmlSchemaString, Options.AuthenticationType));
                }
                context.Properties = properties;

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError(ex.Message);
            }
            return(new AuthenticationTicket(null, properties));
        }
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            _logger.WriteVerbose("AuthenticateCore");

            AuthenticationProperties properties = null;

            try
            {
                string code  = null;
                string state = null;

                IReadableStringCollection query  = Request.Query;
                IList <string>            values = query.GetValues("code");
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }
                values = query.GetValues("state");
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }

                properties = Options.StateDataFormat.Unprotect(state);
                if (properties == null)
                {
                    return(null);
                }

                // OAuth2 10.12 CSRF
                if (!ValidateCorrelationId(properties, _logger))
                {
                    return(new AuthenticationTicket(null, properties));
                }

                var tokenRequestParameters = new List <KeyValuePair <string, string> >()
                {
                    new KeyValuePair <string, string>("client_id", Options.AppId),
                    new KeyValuePair <string, string>("client_secret", Options.AppSecret),
                    new KeyValuePair <string, string>("redirect_uri", GenerateRedirectUri()),
                    new KeyValuePair <string, string>("code", code),
                    new KeyValuePair <string, string>("grant_type", "authorization_code"),
                };

                FormUrlEncodedContent requestContent = new FormUrlEncodedContent(tokenRequestParameters);

                HttpResponseMessage response = await _httpClient.PostAsync(TokenEndpoint, requestContent, Request.CallCancelled);

                response.EnsureSuccessStatusCode();
                string oauthTokenResponse = await response.Content.ReadAsStringAsync();

                var tokenDict = QueryStringToDict(oauthTokenResponse);

                string accessToken = null;
                if (tokenDict.ContainsKey("access_token"))
                {
                    accessToken = tokenDict["access_token"];
                }
                else
                {
                    _logger.WriteWarning("Access token was not found");
                    return(new AuthenticationTicket(null, properties));
                }

                string openIDUri = OpenIDEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken);
                HttpResponseMessage openIDResponse = await _httpClient.GetAsync(openIDUri, Request.CallCancelled);

                openIDResponse.EnsureSuccessStatusCode();
                string openIDString = await openIDResponse.Content.ReadAsStringAsync();

                openIDString = ExtractOpenIDCallbackBody(openIDString);
                JObject openIDInfo = JObject.Parse(openIDString);

                var clientId = openIDInfo["client_id"].Value <string>();
                var openId   = openIDInfo["openid"].Value <string>();

                string userInfoUri = UserInfoEndpoint +
                                     "?access_token=" + Uri.EscapeDataString(accessToken) +
                                     "&oauth_consumer_key=" + Uri.EscapeDataString(clientId) +
                                     "&openid=" + Uri.EscapeDataString(openId);
                HttpResponseMessage userInfoResponse = await _httpClient.GetAsync(userInfoUri, Request.CallCancelled);

                userInfoResponse.EnsureSuccessStatusCode();
                string userInfoString = await userInfoResponse.Content.ReadAsStringAsync();

                JObject userInfo = JObject.Parse(userInfoString);

                var context = new QQConnectAuthenticatedContext(Context, openId, userInfo, accessToken);
                context.Identity = new ClaimsIdentity(new[] {
                    new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString, Options.AuthenticationType),
                    new Claim(ClaimsIdentity.DefaultNameClaimType, context.Name, XmlSchemaString, Options.AuthenticationType),
                    new Claim("urn:qqconnect:id", context.Id, XmlSchemaString, Options.AuthenticationType),
                    new Claim("urn:qqconnect:name", context.Name, XmlSchemaString, Options.AuthenticationType),
                });

                await Options.Provider.Authenticated(context);

                context.Properties = properties;

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError(ex.Message);
            }

            return(new AuthenticationTicket(null, properties));
        }
Exemple #22
0
 public QueryFeature([NotNull] IReadableStringCollection query)
 {
     _query = query;
 }
 public QueryFeature([NotNull] IReadableStringCollection query)
 {
     _query = query;
 }
Exemple #24
0
        protected override async Task<AuthenticationTicket> AuthenticateCoreAsync()
        {
            var properties = new AuthenticationProperties();

            try
            {
                string code = null;
                string state = null;

                IReadableStringCollection query = Request.Query;
                IList<string> values = query.GetValues("code");
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }
                values = query.GetValues("state");
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }

                properties = Options.StateDataFormat.Unprotect(state);
                if (properties == null)
                {
                    return null;
                }

                // OAuth2 10.12 CSRF
                if (!ValidateCorrelationId(properties, _logger))
                {
                    return new AuthenticationTicket(null, properties);
                }

                string requestPrefix = Request.Scheme + "://" + Request.Host;
                string redirectUri = requestPrefix + Request.PathBase + Options.CallbackPath;

                // Build up the body for the token request
                var body = new List<KeyValuePair<string, string>>();
                body.Add(new KeyValuePair<string, string>("code", code));
                body.Add(new KeyValuePair<string, string>("redirect_uri", redirectUri));
                body.Add(new KeyValuePair<string, string>("client_id", Options.ClientId));
                body.Add(new KeyValuePair<string, string>("client_secret", Options.ClientSecret));
                body.Add(new KeyValuePair<string, string>("grant_type", "authorization_code"));

                // Request the token
                var requestMessage = new HttpRequestMessage(HttpMethod.Post, Options.Endpoints.TokenEndpoint);
                requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                requestMessage.Content = new FormUrlEncodedContent(body);
                HttpResponseMessage tokenResponse = await _httpClient.SendAsync(requestMessage);
                tokenResponse.EnsureSuccessStatusCode();
                string text = await tokenResponse.Content.ReadAsStringAsync();

                // Deserializes the token response
                dynamic response = JsonConvert.DeserializeObject<dynamic>(text);
                string accessToken = (string)response.access_token;
                string refreshToken = (string)response.refresh_token;

                // Get the Sidekick user using the user info endpoint, which is part of the token - response.id
                HttpRequestMessage userRequest = new HttpRequestMessage(HttpMethod.Get, Constants.UserProfileEndpoint);
                userRequest.Headers.Add("Authorization", "Bearer " + Uri.EscapeDataString(accessToken));
                userRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage userResponse = await _httpClient.SendAsync(userRequest, Request.CallCancelled);
                userResponse.EnsureSuccessStatusCode();
                text = await userResponse.Content.ReadAsStringAsync();
                JObject user = JObject.Parse(text);

                var context = new SidekickAuthenticatedContext(Context, user, accessToken, refreshToken);
                context.Identity = new ClaimsIdentity(
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);

                if (!string.IsNullOrEmpty(context.Id))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.UserName))
                {
                    context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.UserName, XmlSchemaString, Options.AuthenticationType));
                }

                if (!string.IsNullOrEmpty(context.Email))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, XmlSchemaString, Options.AuthenticationType));
                }

                if (!string.IsNullOrEmpty(context.FirstName))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.GivenName, context.FirstName, XmlSchemaString, Options.AuthenticationType));
                }

                if (!string.IsNullOrEmpty(context.LastName))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Surname, context.LastName, XmlSchemaString, Options.AuthenticationType));
       
                }

                if (!string.IsNullOrEmpty(context.MobileNumber))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.MobilePhone, context.MobileNumber, XmlSchemaString, Options.AuthenticationType));
                }



                context.Identity.AddClaim(new Claim("urn:Sidekick:isactive", context.Active.ToString(), XmlSchemaString,
                    Options.AuthenticationType));

                
                if (!string.IsNullOrEmpty(context.AccessToken))
                {
                    context.Identity.AddClaim(new Claim("urn:Sidekick:accesstoken", context.AccessToken, XmlSchemaString, Options.AuthenticationType));
                }
           
                
                context.Properties = properties;

                await Options.Provider.Authenticated(context);

                return new AuthenticationTicket(context.Identity, context.Properties);
            }
            catch (Exception ex)
            {
                _logger.WriteError(ex.Message);
            }
            return new AuthenticationTicket(null, properties);
        }
Exemple #25
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                string token = null;

                IReadableStringCollection query  = Request.Query;
                IList <string>            values = query.GetValues("token");
                if (values != null && values.Count == 1)
                {
                    token = values[0];
                }

                string stateCookieKey = Constants.StatePrefix + Options.AuthenticationType;
                string stateCookie    = Request.Cookies[stateCookieKey];
                if (string.IsNullOrWhiteSpace(stateCookie))
                {
                    _logger.WriteWarning("{0} cookie not found.", stateCookie);
                    return(null);
                }

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

                Response.Cookies.Delete(stateCookieKey, cookieOptions);

                properties = Options.StateDataFormat.Unprotect(stateCookie);
                if (properties == null)
                {
                    return(null);
                }

                // Request the token
                ActivityDetails activityDetails = await _yotiClient.GetActivityDetailsAsync(token);

                if (activityDetails.Outcome != ActivityOutcome.Success)
                {
                    // TODO: Check how this is handled
                    throw new HttpRequestException();
                }

                var context = new YotiAuthenticatedContext(Context, activityDetails.UserProfile)
                {
                    Identity = new ClaimsIdentity(
                        Options.AuthenticationType,
                        ClaimsIdentity.DefaultNameClaimType,
                        ClaimsIdentity.DefaultRoleClaimType)
                };

                if (!string.IsNullOrEmpty(context.User.Id))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.User.Id, ClaimValueTypes.String, Options.AuthenticationType));
                }

                if (context.User.Selfie != null)
                {
                    context.Identity.AddClaim(new Claim("selfie", Convert.ToBase64String(context.User.Selfie.Data), context.User.Selfie.Type.ToString(), Options.AuthenticationType));
                }

                if (!string.IsNullOrEmpty(context.User.GivenNames))
                {
                    context.Identity.AddClaim(new Claim("given_names", context.User.GivenNames, ClaimValueTypes.String, Options.AuthenticationType));
                }

                if (!string.IsNullOrEmpty(context.User.FamilyName))
                {
                    context.Identity.AddClaim(new Claim("family_name", context.User.FamilyName, ClaimValueTypes.String, Options.AuthenticationType));
                }

                if (!string.IsNullOrEmpty(context.User.FullName))
                {
                    context.Identity.AddClaim(new Claim("full_name", context.User.FullName, ClaimValueTypes.String, Options.AuthenticationType));
                }

                if (!string.IsNullOrEmpty(context.User.MobileNumber))
                {
                    context.Identity.AddClaim(new Claim("phone_number", context.User.MobileNumber, ClaimValueTypes.String, Options.AuthenticationType));
                }

                if (!string.IsNullOrEmpty(context.User.EmailAddress))
                {
                    context.Identity.AddClaim(new Claim("email_address", context.User.EmailAddress, ClaimValueTypes.String, Options.AuthenticationType));
                }

                if (context.User.DateOfBirth != null)
                {
                    context.Identity.AddClaim(new Claim("date_of_birth", context.User.DateOfBirth.Value.ToString("yyyy-MM-dd"), ClaimValueTypes.String, Options.AuthenticationType));
                }

                if (context.User.IsAgeVerified != null)
                {
                    context.Identity.AddClaim(new Claim("is_age_verified", context.User.IsAgeVerified.ToString(), ClaimValueTypes.String, Options.AuthenticationType));
                }

                if (!string.IsNullOrEmpty(context.User.Address))
                {
                    context.Identity.AddClaim(new Claim("postal_address", context.User.Address, ClaimValueTypes.String, Options.AuthenticationType));
                }

                if (!string.IsNullOrEmpty(context.User.Gender))
                {
                    context.Identity.AddClaim(new Claim("gender", context.User.Gender, ClaimValueTypes.String, Options.AuthenticationType));
                }

                if (!string.IsNullOrEmpty(context.User.Nationality))
                {
                    context.Identity.AddClaim(new Claim("nationality", context.User.Nationality, ClaimValueTypes.String, Options.AuthenticationType));
                }

                foreach (var attributeName in context.User.OtherAttributes.Keys)
                {
                    var attributeValue = context.User.OtherAttributes[attributeName];
                    context.Identity.AddClaim(new Claim(attributeName, attributeValue.ToString(), attributeValue.Type.ToString(), Options.AuthenticationType));
                }

                context.Properties = properties;

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError("Authentication failed", ex);
                return(new AuthenticationTicket(null, properties));
            }
        }
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                string code  = null;
                string state = null;

                IReadableStringCollection query  = Request.Query;
                IList <string>            values = query.GetValues("code");
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }
                values = query.GetValues("state");
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }

                properties = Options.StateDataFormat.Unprotect(state);
                if (properties == null)
                {
                    return(null);
                }

                // OAuth2 10.12 CSRF
                if (!ValidateCorrelationId(properties, logger))
                {
                    return(new AuthenticationTicket(null, properties));
                }

                string requestPrefix = Request.Scheme + "://" + Request.Host;
                string redirectUri   = requestPrefix + Request.PathBase + Options.CallbackPath;

                // Build up the body for the token request
                var body = new List <KeyValuePair <string, string> >();
                body.Add(new KeyValuePair <string, string>("grant_type", "authorization_code"));
                body.Add(new KeyValuePair <string, string>("code", code));
                body.Add(new KeyValuePair <string, string>("redirect_uri", redirectUri));
                body.Add(new KeyValuePair <string, string>("client_id", Options.ClientId));
                body.Add(new KeyValuePair <string, string>("client_secret", Options.ClientSecret));

                // Request the token
                HttpResponseMessage tokenResponse =
                    await httpClient.PostAsync(TokenEndpoint, new FormUrlEncodedContent(body));

                tokenResponse.EnsureSuccessStatusCode();
                string text = await tokenResponse.Content.ReadAsStringAsync();

                // Deserializes the token response
                dynamic response    = JsonConvert.DeserializeObject <dynamic>(text);
                string  accessToken = (string)response.access_token;
                string  blogId      = (string)response.blog_id;
                string  blogUrl     = (string)response.blog_url;

                // Get the Wordpress user
                HttpRequestMessage userRequest = new HttpRequestMessage(HttpMethod.Get, UserInfoEndpoint);
                userRequest.Headers.Add("User-Agent", "OWIN OAuth Provider");
                userRequest.Headers.Add("Authorization", "BEARER " + accessToken);
                HttpResponseMessage graphResponse = await httpClient.SendAsync(userRequest, Request.CallCancelled);

                graphResponse.EnsureSuccessStatusCode();
                text = await graphResponse.Content.ReadAsStringAsync();

                JObject user = JObject.Parse(text);

                // Get the site details
                HttpRequestMessage siteRequest = new HttpRequestMessage(HttpMethod.Get, SiteInfoEndpoint + blogId);
                siteRequest.Headers.Add("User-Agent", "OWIN OAuth Provider");
                siteRequest.Headers.Add("Authorization", "BEARER " + accessToken);
                HttpResponseMessage siteResponse = await httpClient.SendAsync(siteRequest, Request.CallCancelled);

                siteResponse.EnsureSuccessStatusCode();
                text = await siteResponse.Content.ReadAsStringAsync();

                JObject site = JObject.Parse(text);

                var context = new WordPressAuthenticatedContext(Context, user, site, accessToken, blogId, blogUrl);
                context.Identity = new ClaimsIdentity(
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);
                if (!string.IsNullOrEmpty(context.Id))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Name))
                {
                    context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.Name, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Email))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, XmlSchemaString, Options.AuthenticationType));
                }
                context.Properties = properties;

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                logger.WriteError(ex.Message);
            }
            return(new AuthenticationTicket(null, properties));
        }
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                IReadableStringCollection query = Request.Query;
                string protectedRequestToken    = Request.Cookies[StateCookie];

                RequestToken requestToken = Options.StateDataFormat.Unprotect(protectedRequestToken);

                if (requestToken == null)
                {
                    _logger.WriteWarning("Invalid state");
                    return(null);
                }

                properties = requestToken.Properties;

                string returnedToken = query.Get("oauth_token");
                if (string.IsNullOrWhiteSpace(returnedToken))
                {
                    _logger.WriteWarning("Missing oauth_token");
                    return(new AuthenticationTicket(null, properties));
                }

                if (returnedToken != requestToken.Token)
                {
                    _logger.WriteWarning("Unmatched token");
                    return(new AuthenticationTicket(null, properties));
                }

                string oauthVerifier = query.Get("oauth_verifier");
                if (string.IsNullOrWhiteSpace(oauthVerifier))
                {
                    _logger.WriteWarning("Missing or blank oauth_verifier");
                    return(new AuthenticationTicket(null, properties));
                }

                AccessToken accessToken = await ObtainAccessTokenAsync(Options.ConsumerKey, Options.ConsumerSecret, requestToken, oauthVerifier);

                var context = new TwitterAuthenticatedContext(Context, accessToken.UserId, accessToken.ScreenName, accessToken.Token, accessToken.TokenSecret);

                context.Identity = new ClaimsIdentity(
                    new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, accessToken.UserId, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType),
                    new Claim(ClaimTypes.Name, accessToken.ScreenName, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType),
                    new Claim("urn:twitter:userid", accessToken.UserId, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType),
                    new Claim("urn:twitter:screenname", accessToken.ScreenName, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType)
                },
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);
                context.Properties = requestToken.Properties;

                Response.Cookies.Delete(StateCookie);

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError("Authentication failed", ex);
                return(new AuthenticationTicket(null, properties));
            }
        }
        private static string SerializeQuery(IReadableStringCollection query)
        {
            var dictionary = query.ToDictionary(item => item.Key, item => item.Value.Count > 1 ? (object)item.Value : item.Value[0]);

            var settings = new JsonSerializerSettings
            {
                StringEscapeHandling = StringEscapeHandling.EscapeHtml
            };

            return JsonConvert.SerializeObject(dictionary, settings).Replace("\"", "'");
        }
Exemple #29
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                string code  = null;
                string state = null;

                IReadableStringCollection query  = Request.Query;
                IList <string>            values = query.GetValues("code");
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }
                values = query.GetValues("state");
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }

                properties = Options.StateDataFormat.Unprotect(state);
                if (properties == null)
                {
                    return(null);
                }

                // OAuth2 10.12 CSRF
                if (!ValidateCorrelationId(properties, logger))
                {
                    return(new AuthenticationTicket(null, properties));
                }

                string requestPrefix = "https://" + Request.Host; // Schema must be HTTPS
                string redirectUri   = requestPrefix + Request.PathBase + Options.CallbackPath;

                var param = new List <KeyValuePair <string, string> >();
                param.Add(new KeyValuePair <string, string>("client_id", Options.AppId));
                param.Add(new KeyValuePair <string, string>("client_secret", Options.AppSecret));
                param.Add(new KeyValuePair <string, string>("grant_type", "authorization_code"));
                param.Add(new KeyValuePair <string, string>("code", code));
                param.Add(new KeyValuePair <string, string>("redirect_uri", redirectUri));
                FormUrlEncodedContent content = new FormUrlEncodedContent(param);

                // Request the token
                HttpResponseMessage tokenResponse = await httpClient.PostAsync(Options.Endpoints.TokenEndPoint, content);

                tokenResponse.EnsureSuccessStatusCode();
                string text = await tokenResponse.Content.ReadAsStringAsync();

                JObject token = JObject.Parse(text);

                string accessToken = NRIIAuthenticatedContext.TryGetValue(token, "access_token");
                int    expiresIn   = Convert.ToInt32(NRIIAuthenticatedContext.TryGetValue(token, "expires_in"));

                // Get the NRII user
                string              requestInfoQueryString = "?access_token=" + accessToken;
                HttpRequestMessage  userRequest            = new HttpRequestMessage(HttpMethod.Get, Options.Endpoints.UserInfoEndPoint + requestInfoQueryString);
                HttpResponseMessage userResponse           = await httpClient.SendAsync(userRequest, Request.CallCancelled);

                userResponse.EnsureSuccessStatusCode();
                text = await userResponse.Content.ReadAsStringAsync();

                text = text.Substring(text.IndexOf('{'), text.LastIndexOf('}') - text.IndexOf('{') + 1);
                JObject user = JObject.Parse(text);

                var context = new NRIIAuthenticatedContext(Context, user, accessToken, expiresIn);
                context.Identity = new ClaimsIdentity(
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);
                if (!string.IsNullOrEmpty(context.Id))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Name))
                {
                    context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.Name, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Email))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, XmlSchemaString, Options.AuthenticationType));
                }
                context.Properties = properties;

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                logger.WriteError(ex.ToString());
            }
            return(new AuthenticationTicket(null, properties));
        }
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                string code  = null;
                string state = null;

                IReadableStringCollection query  = Request.Query;
                IList <string>            values = query.GetValues("code");

                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }
                values = query.GetValues("state");

                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }

                if (!ValidateStateId(state, out properties))
                {
                    return(null);
                }

                // OAuth2 10.12 CSRF
                if (!ValidateCorrelationId(properties, _logger))
                {
                    return(new AuthenticationTicket(null, properties));
                }

                var tokenRequestParameters = new List <KeyValuePair <string, string> >()
                {
                    new KeyValuePair <string, string>("appid", Options.AppId),
                    new KeyValuePair <string, string>("secret", Options.AppSecret),
                    new KeyValuePair <string, string>("code", code),
                    new KeyValuePair <string, string>("grant_type", "authorization_code"),
                };
                var requestContent = new FormUrlEncodedContent(tokenRequestParameters);

                // 通过code获取access_token
                HttpResponseMessage response = await _httpClient.PostAsync(TokenEndpoint, requestContent, Request.CallCancelled);

                response.EnsureSuccessStatusCode();
                string oauthTokenResponse = await response.Content.ReadAsStringAsync();

                JObject oauth2Token = JObject.Parse(oauthTokenResponse);
                var     accessToken = oauth2Token["access_token"].Value <string>();

                // Refresh token is only available when wl.offline_access is request.
                // Otherwise, it is null.
                var refreshToken = oauth2Token.Value <string>("refresh_token");
                var expire       = oauth2Token.Value <string>("expires_in");

                if (string.IsNullOrWhiteSpace(accessToken))
                {
                    _logger.WriteWarning("Access token was not found");
                    return(new AuthenticationTicket(null, properties));
                }

                var openId  = oauth2Token.Value <string>("openid");
                var scope   = oauth2Token.Value <string>("scope");
                var unionId = oauth2Token.Value <string>("unionid");

                // 获取用户信息
                var userInfoResponse = await _httpClient.GetAsync(string.Format(UserInfoEndpoint + "?access_token={0}&openid={1}", Uri.EscapeDataString(accessToken), Uri.EscapeDataString(openId)), Request.CallCancelled);

                userInfoResponse.EnsureSuccessStatusCode();
                string userInfoResponseString = await userInfoResponse.Content.ReadAsStringAsync();

                JObject userInformation = JObject.Parse(userInfoResponseString);
                _logger.WriteInformation(userInfoResponseString);
                var context = new WeixinAuthenticatedContext(Context, userInformation, accessToken, refreshToken, expire);

                context.Identity = new ClaimsIdentity(new[] {
                    new Claim(ClaimTypes.Name, WeixinSecurityConstants.DefaultAuthenticationType, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType),
                    new Claim(ClaimTypes.Surname, context.OpenId, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType),
                    new Claim(ClaimTypes.NameIdentifier, context.OpenId, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType),
                    new Claim(CommonClaimType.NickName, context.Nickame, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType),
                    new Claim(CommonClaimType.Avatar, context.HeadimgUrl, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType),
                    new Claim(WeixinSecurityConstants.WeixinClaimType, userInformation.ToString(), "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType),
                },
                                                      Options.AuthenticationType,
                                                      ClaimsIdentity.DefaultNameClaimType,
                                                      ClaimsIdentity.DefaultRoleClaimType);

                await Options.Provider.Authenticated(context);

                context.Properties = properties;
                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError("Authentication failed", ex);
                return(new AuthenticationTicket(null, properties));
            }
        }
Exemple #31
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                string code  = null;
                string state = null;

                IReadableStringCollection query  = Request.Query;
                IList <string>            values = query.GetValues("code");
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }
                values = query.GetValues("state");
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }

                properties = Options.StateDataFormat.Unprotect(state);
                if (properties == null)
                {
                    return(null);
                }

                // OAuth2 10.12 CSRF
                if (!ValidateCorrelationId(properties, _logger))
                {
                    return(new AuthenticationTicket(null, properties));
                }

                string requestPrefix = Request.Scheme + "://" + Request.Host;
                string redirectUri   = requestPrefix + Request.PathBase + Options.CallbackPath;

                var postContent = "?grant_type=authorization_code" +
                                  "&code=" + Uri.EscapeDataString(code) +
                                  "&redirect_uri=" + Uri.EscapeDataString(redirectUri) +
                                  "&client_id=" + Uri.EscapeDataString(Options.ClientId) +
                                  "&client_secret=" + Uri.EscapeDataString(Options.ClientSecret);

                var tokenResponse = await _httpClient.PostAsync(TokenEndpoint + postContent, null, Request.CallCancelled);

                tokenResponse.EnsureSuccessStatusCode();
                var text = await tokenResponse.Content.ReadAsStringAsync();

                dynamic form = JObject.Parse(text);

                string accessToken = form.access_token;

                var selfRespone =
                    await _httpClient.GetAsync(string.Format(SelfEndpointTemplate, Uri.EscapeDataString(accessToken)));

                selfRespone.EnsureSuccessStatusCode();
                text = await selfRespone.Content.ReadAsStringAsync();

                dynamic self = JObject.Parse(text);
                JObject user = self.response["user"];

                var context = new FoursquareAuthenticatedContext(Context, user, accessToken)
                {
                    Identity = new ClaimsIdentity(
                        Options.AuthenticationType,
                        ClaimsIdentity.DefaultNameClaimType,
                        ClaimsIdentity.DefaultRoleClaimType)
                };

                if (!string.IsNullOrEmpty(context.Id))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.FullName))
                {
                    context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.FullName, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.FullName))
                {
                    context.Identity.AddClaim(new Claim("urn:Foursquare:fullName", context.FullName, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Email))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, XmlSchemaString, Options.AuthenticationType));
                }
                context.Properties = properties;

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError(ex.Message);
            }
            return(new AuthenticationTicket(null, properties));
        }
Exemple #32
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                string code  = null;
                string state = null;

                IReadableStringCollection query  = Request.Query;
                IList <string>            values = query.GetValues("code");
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }

                values = query.GetValues("state");
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }

                properties = Options.StateDataFormat.Unprotect(state);
                if (properties == null)
                {
                    return(null);
                }

                // OAuth2 10.12 CSRF
                if (!ValidateCorrelationId(properties, logger))
                {
                    return(new AuthenticationTicket(null, properties));
                }

                // Check for error
                //if (Request.Query.Get("error") != null)
                //    return new AuthenticationTicket(null, properties);

                string requestPrefix = Request.Scheme + "://" + Request.Host;
                string redirectUri   = requestPrefix + Request.PathBase + Options.CallbackPath;

                // Build up the body for the token request
                var body = new List <KeyValuePair <string, string> >();
                body.Add(new KeyValuePair <string, string>("grant_type", "authorization_code"));
                body.Add(new KeyValuePair <string, string>("code", code));
                body.Add(new KeyValuePair <string, string>("client_id", Options.AppKey));
                body.Add(new KeyValuePair <string, string>("client_secret", Options.AppSecret));
                body.Add(new KeyValuePair <string, string>("redirect_uri", redirectUri));

                // Get token
                var tokenRequest = new HttpRequestMessage(HttpMethod.Post, "https://" + Options.Hostname + TokenEndpoint);
                tokenRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                tokenRequest.Content = new FormUrlEncodedContent(body);

                HttpResponseMessage tokenResponse = await httpClient.SendAsync(tokenRequest, Request.CallCancelled);

                tokenResponse.EnsureSuccessStatusCode();
                string text = await tokenResponse.Content.ReadAsStringAsync();

                // Deserializes the token response
                dynamic response    = JsonConvert.DeserializeObject <dynamic>(text);
                string  accessToken = (string)response.access_token;

                string tokenType = (string)response.token_type;

                var userRequest = new HttpRequestMessage(HttpMethod.Get, "https://" + Options.Hostname + UserInfoEndpoint);
                userRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                userRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                //userRequest.Headers.Authorization = new AuthenticationHeaderValue(tokenType, accessToken);
                HttpResponseMessage graphResponse = await httpClient.SendAsync(userRequest, Request.CallCancelled);

                graphResponse.EnsureSuccessStatusCode();
                text = await graphResponse.Content.ReadAsStringAsync();

                JObject user = JObject.Parse(text);

                var context = new JawboneAuthenticatedContext(Context, user, accessToken);
                context.Identity = new ClaimsIdentity(
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);
                if (!string.IsNullOrEmpty(context.Id))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Name))
                {
                    context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.Name, XmlSchemaString, Options.AuthenticationType));
                }
                context.Properties = properties;

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                logger.WriteError(ex.Message);
            }
            return(new AuthenticationTicket(null, properties));
        }
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                string code  = null;
                string state = null;

                IReadableStringCollection query  = Request.Query;
                IList <string>            values = query.GetValues("code");
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }
                values = query.GetValues("state");
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }

                properties = Options.StateDataFormat.Unprotect(state);
                if (properties == null)
                {
                    return(null);
                }

                // OAuth2 10.12 CSRF
                if (!ValidateCorrelationId(properties, logger))
                {
                    return(new AuthenticationTicket(null, properties));
                }

                string requestPrefix = Request.Scheme + "://" + Request.Host;
                string redirectUri   = requestPrefix + Request.PathBase + Options.CallbackPath;

                // Build up the body for the token request
                var body = new List <KeyValuePair <string, string> >();
                body.Add(new KeyValuePair <string, string>("grant_type", "authorization_code"));
                body.Add(new KeyValuePair <string, string>("client_id", Options.ClientId));
                body.Add(new KeyValuePair <string, string>("client_secret", Options.ClientSecret));
                body.Add(new KeyValuePair <string, string>("redirect_uri", redirectUri));
                body.Add(new KeyValuePair <string, string>("code", code));

                /*Your app makes a POST request to https://app.asana.com/-/oauth_token, passing the parameters as part of a standard form-encoded post body.
                 *      grant_type - required Must be authorization_code
                 *      client_id - required The Client ID uniquely identifies the application making the request.
                 *      client_secret - required The Client Secret belonging to the app, found in the details pane of the developer view
                 *      redirect_uri - required Must match the redirect_uri specified in the original request
                 *      code - required The code you are exchanging for an auth token
                 */

                // Request the token
                var requestMessage = new HttpRequestMessage(HttpMethod.Post, Options.Endpoints.TokenEndpoint);
                requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                requestMessage.Content = new FormUrlEncodedContent(body);
                HttpResponseMessage tokenResponse = await httpClient.SendAsync(requestMessage);

                tokenResponse.EnsureSuccessStatusCode();
                string text = await tokenResponse.Content.ReadAsStringAsync();

                // Deserializes the token response
                dynamic response    = JsonConvert.DeserializeObject <dynamic>(text);
                string  accessToken = (string)response.access_token;

                /*
                 * In the response, you will receive a JSON payload with the following parameters:
                 *  access_token - The token to use in future requests against the API
                 *  expires_in - The number of seconds the token is valid, typically 3600 (one hour)
                 *  token_type - The type of token, in our case, bearer
                 *  refresh_token - If exchanging a code, a long-lived token that can be used to get new access tokens when old ones expire.
                 *  data - A JSON object encoding a few key fields about the logged-in user, currently id, name, and email.
                 */

                // Get the Asana user

                var context = new AsanaAuthenticatedContext(Context, response.data, accessToken);
                context.Identity = new ClaimsIdentity(
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);
                if (!string.IsNullOrEmpty(context.Id))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Email))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Name))
                {
                    context.Identity.AddClaim(new Claim("urn:asana:name", context.Name, XmlSchemaString, Options.AuthenticationType));
                }
                context.Properties = properties;

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                logger.WriteError(ex.Message);
            }
            return(new AuthenticationTicket(null, properties));
        }
Exemple #34
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                string code  = null;
                string state = null;

                IReadableStringCollection query  = Request.Query;
                IList <string>            values = query.GetValues("code");
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }
                values = query.GetValues("state");
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }

                properties = Options.StateDataFormat.Unprotect(state);
                if (properties == null)
                {
                    return(null);
                }

                // OAuth2 10.12 CSRF
                if (!ValidateCorrelationId(properties, logger))
                {
                    return(new AuthenticationTicket(null, properties));
                }

                string requestPrefix = Request.Scheme + "://" + Request.Host;
                string redirectUri   = requestPrefix + Request.PathBase + Options.CallbackPath;

                // Build up the body for the token request
                var body = new List <KeyValuePair <string, string> >();
                body.Add(new KeyValuePair <string, string>("code", code));
                body.Add(new KeyValuePair <string, string>("redirect_uri", redirectUri));
                body.Add(new KeyValuePair <string, string>("client_id", Options.ClientId));
                body.Add(new KeyValuePair <string, string>("client_secret", Options.ClientSecret));

                // Request the token
                HttpResponseMessage tokenResponse =
                    await httpClient.PostAsync(TokenEndpoint, new FormUrlEncodedContent(body));

                tokenResponse.EnsureSuccessStatusCode();
                string text = await tokenResponse.Content.ReadAsStringAsync();

                // Deserializes the token response
                //dynamic response = JsonConvert.DeserializeObject<dynamic>(text);
                var    responseTokens = HttpUtility.ParseQueryString(text);
                string accessToken    = responseTokens["access_token"];
                string expires        = responseTokens["expires"];

                // Get the StackExchange user
                HttpRequestMessage  userRequest   = new HttpRequestMessage(HttpMethod.Get, UserInfoEndpoint + "&access_token=" + Uri.EscapeDataString(accessToken) + "&key=" + Uri.EscapeDataString(Options.Key));
                HttpResponseMessage graphResponse = await httpClient.SendAsync(userRequest, Request.CallCancelled);

                graphResponse.EnsureSuccessStatusCode();

                //According to http://api.stackexchange.com/docs/compression -
                //Responses would always be compressed
                //If Accept-Encoding request header is not set, compression would be GZIP
                //If Content-Encoding is not specified in response header, assume GZIP
                using (var stream = new GZipStream(await graphResponse.Content.ReadAsStreamAsync(), CompressionMode.Decompress))
                {
                    var sr = new StreamReader(stream);
                    text = sr.ReadToEnd();
                }

                JObject userResponse = JObject.Parse(text);
                JToken  userAccounts;
                JObject user = userResponse.TryGetValue("items", out userAccounts)
                    ? userAccounts.First as JObject
                    : null;

                var context = new StackExchangeAuthenticatedContext(Context, user, accessToken, expires)
                {
                    Identity = new ClaimsIdentity(
                        Options.AuthenticationType,
                        ClaimsIdentity.DefaultNameClaimType,
                        ClaimsIdentity.DefaultRoleClaimType)
                };

                if (!string.IsNullOrEmpty(context.Id))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.UserName))
                {
                    context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.UserName, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Name))
                {
                    context.Identity.AddClaim(new Claim("urn:stackexchange:name", context.Name, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Link))
                {
                    context.Identity.AddClaim(new Claim("urn:stackexchange:url", context.Link, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.AccessToken))
                {
                    context.Identity.AddClaim(new Claim("urn:stackexchange:accesstoken", context.AccessToken, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.ProfileImage))
                {
                    context.Identity.AddClaim(new Claim("urn:stackexchange:profileimage", context.ProfileImage, XmlSchemaString, Options.AuthenticationType));
                }
                context.Properties = properties;

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                logger.WriteError(ex.Message);
            }
            return(new AuthenticationTicket(null, properties));
        }
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                string code  = null;
                string state = null;

                IReadableStringCollection query = Request.Query;

                IList <string> values = query.GetValues("error");
                if (values != null && values.Count >= 1)
                {
                    _logger.WriteVerbose("Remote server returned an error: " + Request.QueryString);
                }

                values = query.GetValues("code");
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }
                values = query.GetValues("state");
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }

                properties = Options.StateDataFormat.Unprotect(state);
                if (properties == null)
                {
                    return(null);
                }

                // OAuth2 10.12 CSRF
                if (!ValidateCorrelationId(properties, _logger))
                {
                    return(new AuthenticationTicket(null, properties));
                }

                if (code == null)
                {
                    // Null if the remote server returns an error.
                    return(new AuthenticationTicket(null, properties));
                }

                string requestPrefix = Request.Scheme + "://" + Request.Host;
                string redirectUri   = requestPrefix + Request.PathBase + Options.CallbackPath;

                string tokenRequest = "grant_type=authorization_code" +
                                      "&code=" + Uri.EscapeDataString(code) +
                                      "&redirect_uri=" + Uri.EscapeDataString(redirectUri) +
                                      "&client_id=" + Uri.EscapeDataString(Options.AppId) +
                                      "&client_secret=" + Uri.EscapeDataString(Options.AppSecret);

                HttpResponseMessage tokenResponse =
                    await _httpClient.GetAsync(TokenEndpoint + "?" + tokenRequest, Request.CallCancelled);

                tokenResponse.EnsureSuccessStatusCode();
                string content = await tokenResponse.Content.ReadAsStringAsync();

                JObject token = JObject.Parse(content);

                string accessToken = token["access_token"].Value <string>();
                string expires     = token["expires_in"].Value <string>();

                // get user info
                string graphAddress = UserInfoEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken);
                if (Options.SendAppSecretProof)
                {
                    graphAddress += "&appsecret_proof=" + GenerateAppSecretProof(accessToken);
                }

                HttpResponseMessage graphResponse = await _httpClient.GetAsync(graphAddress, Request.CallCancelled);

                graphResponse.EnsureSuccessStatusCode();
                content = await graphResponse.Content.ReadAsStringAsync();

                JObject user = JObject.Parse(content);

                // get permissions
                string permissionsAddress = PermissionsEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken);
                if (Options.SendAppSecretProof)
                {
                    permissionsAddress += "&appsecret_proof=" + GenerateAppSecretProof(accessToken);
                }

                HttpResponseMessage permissionsResponse = await _httpClient.GetAsync(permissionsAddress, Request.CallCancelled);

                permissionsResponse.EnsureSuccessStatusCode();
                content = await permissionsResponse.Content.ReadAsStringAsync();

                JObject permissions = JObject.Parse(content);

                // parse reponses
                var context = new FacebookAuthenticatedContext(Context, user, permissions, accessToken, expires);
                context.Identity = new ClaimsIdentity(
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);
                if (!string.IsNullOrEmpty(context.Id))
                {
                    context.Identity.AddClaim(
                        new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.UserName))
                {
                    context.Identity.AddClaim(
                        new Claim(ClaimsIdentity.DefaultNameClaimType, context.UserName, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Email))
                {
                    context.Identity.AddClaim(
                        new Claim(ClaimTypes.Email, context.Email, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Name))
                {
                    context.Identity.AddClaim(
                        new Claim("urn:facebook:name", context.Name, XmlSchemaString, Options.AuthenticationType));

                    // Many Facebook accounts do not set the UserName field.  Fall back to the Name field instead.
                    if (string.IsNullOrEmpty(context.UserName))
                    {
                        context.Identity.AddClaim(
                            new Claim(ClaimsIdentity.DefaultNameClaimType, context.Name, XmlSchemaString, Options.AuthenticationType));
                    }
                }
                if (!string.IsNullOrEmpty(context.Link))
                {
                    context.Identity.AddClaim(
                        new Claim("urn:facebook:link", context.Link, XmlSchemaString, Options.AuthenticationType));
                }
                context.Properties = properties;

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError("Authentication failed", ex);
                return(new AuthenticationTicket(null, properties));
            }
        }
Exemple #36
0
 /// <summary>
 /// Initializes a new instance of the <see cref="OAuthValidateClientAuthenticationContext"/> class
 /// </summary>
 /// <param name="context"></param>
 /// <param name="options"></param>
 /// <param name="parameters"></param>
 public OAuthValidateClientAuthenticationContext(HttpContext context, OAuthAuthorizationServerOptions options, IReadableStringCollection parameters) : base(context, options, null)
 {
     Parameters = parameters;
 }
        /// <summary>
        /// Adds the openid parameters from querystring or form body into Namespaces and Properties collections.
        /// This normalizes the parameter name, by replacing the variable namespace alias with the 
        /// actual namespace in the collection's key, and will optionally skip any parameters that are
        /// not signed if the strict argument is true.
        /// </summary>
        /// <param name="parameters">The keys and values of the incoming querystring or form body</param>
        /// <param name="strict">True if keys that are not signed should be ignored</param>
        private void Add(IReadableStringCollection parameters, bool strict)
        {
            IEnumerable<KeyValuePair<string, string[]>> addingParameters;

            // strict is true if keys that are not signed should be strict
            if (strict)
            {
                var signed = parameters.GetValues("openid.signed");
                if (signed == null ||
                    signed.Count != 1)
                {
                    // nothing is added if the signed parameter is not present
                    return;
                }

                // determine the set of keys that are signed, or which may be used without
                // signing. ns, mode, signed, and sig each may be used without signing.
                var strictKeys = new HashSet<string>(signed[0]
                    .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(value => "openid." + value)
                    .Concat(new[] { "openid.ns", "openid.mode", "openid.signed", "openid.sig" }));

                // the parameters to add are only the parameters what are in this set
                addingParameters = parameters.Where(kv => strictKeys.Contains(kv.Key));
            }
            else
            {
                // when strict is false all of the incoming parameters are to be added 
                addingParameters = parameters;
            }

            // convert the incoming parameter strings into Property objects. the
            // Key is the raw key name. The Name starts of being equal to Key with a 
            // trailing dot appended. The Value is the query or form value, with a comma delimiter
            // inserted between multiply occuring values.
            var addingProperties = addingParameters.Select(kv => new Property
            {
                Key = kv.Key,
                Name = kv.Key + ".",
                Value = string.Join(",", kv.Value)
            }).ToArray();

            // first, recognize which parameters are namespace declarations 

            var namespacePrefixes = new Dictionary<string, Property>(StringComparer.Ordinal);
            foreach (var item in addingProperties.Where(item => item.Name.StartsWith("openid.ns.", StringComparison.Ordinal)))
            {
                // the value of the parameter is the uri of the namespace
                item.Namespace = item.Value;
                item.Name = "openid." + item.Name.Substring("openid.ns.".Length);

                // the namespaces collection is keyed by the ns uri
                Namespaces.Add(item.Namespace, item);

                // and the prefixes collection is keyed by "openid.alias." 
                namespacePrefixes.Add(item.Name, item);
            }

            // second, recognize which parameters are property values 

            foreach (var item in addingProperties)
            {
                // anything with a namespace was already added to Namespaces
                if (item.Namespace != null) continue;
                // look for the namespace match for this property. 
                Property match = null;

                // try finding where openid.alias.arg2 matches openid.ns.alies namespace
                if (item.Name.StartsWith("openid.", StringComparison.Ordinal))
                {
                    var dotIndex = item.Name.IndexOf('.', "openid.".Length);
                    if (dotIndex != -1)
                    {
                        var namespacePrefix = item.Name.Substring(0, dotIndex + 1);
                        namespacePrefixes.TryGetValue(namespacePrefix, out match);
                    }
                }

                // then try finding where openid.arg1 should match openid.ns namespace
                if (match == null)
                {
                    namespacePrefixes.TryGetValue("openid.", out match);
                }

                // when a namespace is found
                if (match != null)
                {
                    // the property's namespace is defined, and the namespace's prefix is removed
                    item.Namespace = match.Namespace;
                    item.Name = item.Name.Substring(match.Name.Length);
                }

                // the resulting property key is keyed by the local name and namespace
                // so "openid.arg1" becomes "arg1.namespace-uri-of-openid"
                // and "openid.alias.arg2" becomes "arg2.namespace-uri-of-alias"
                Properties.Add(item.Name + item.Namespace, item);
            }
        }
 public HttpRequestParams(IReadableStringCollection urlData, IFormCollection formData)
 {
     UrlData = urlData;
     FormData = formData;
 }
 public RequestCookiesFeature([NotNull] IReadableStringCollection cookies)
 {
     _cookies = cookies;
 }
 /// <summary>
 /// Creates a provider for <see cref="IReadableStringCollection"/> wrapping an existing set of key value pairs.
 /// </summary>
 /// <param name="values">The key value pairs to wrap.</param>
 /// <param name="culture">The culture to return with ValueProviderResult instances.</param>
 public ReadableStringCollectionValueProvider([NotNull] IReadableStringCollection values, CultureInfo culture)
 {
     _values  = values;
     _culture = culture;
 }
 /// <summary>
 /// Creates a NameValuePairsProvider wrapping an existing set of key value pairs.
 /// </summary>
 /// <param name="values">The key value pairs to wrap.</param>
 /// <param name="culture">The culture to return with ValueProviderResult instances.</param>
 public ReadableStringCollectionValueProvider([NotNull] IReadableStringCollection values, CultureInfo culture)
 {
     _values = values;
     _culture = culture;
 }
Exemple #42
0
        public static ImageDisParameters AppendParameters(this ImageDisParameters param, IReadableStringCollection query)
        {
            foreach (var q in query)
            {
                int  integer;
                bool boolean;

                if (int.TryParse(q.Value.First(), out integer))
                {
                    param.Add(q.Key, integer);
                }
                else if (bool.TryParse(q.Value.First(), out boolean))
                {
                    param.Add(q.Key, boolean);
                }
                else
                {
                    param.Add(q.Key, q.Value.First());
                }
            }

            return(param);
        }
 private Query DeserializeFromQueryString(string name, IReadableStringCollection query)
 {
   return CqrsApplication.GetService<IDeserializer>().CreateQuery(name, query.Select(kv => new KeyValuePair<string, IEnumerable<string>>(kv.Key, kv.Value)));
 }
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                string code  = null;
                string state = null;

                IReadableStringCollection query  = Request.Query;
                IList <string>            values = query.GetValues("code");
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }
                values = query.GetValues("state");
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }

                properties = Options.StateDataFormat.Unprotect(state);
                if (properties == null)
                {
                    return(null);
                }

                // OAuth2 10.12 CSRF
                if (!ValidateCorrelationId(properties, _logger))
                {
                    return(new AuthenticationTicket(null, properties));
                }

                string requestPrefix = Request.Scheme + "://" + Request.Host;
                string redirectUri   = requestPrefix + Request.PathBase + Options.CallbackPath;

                string tokenRequest = "client_id=" + Uri.EscapeDataString(Options.ClientId) +
                                      "&client_secret=" + Uri.EscapeDataString(Options.ClientSecret) +
                                      "&code=" + Uri.EscapeDataString(code) +
                                      "&redirect_uri=" + Uri.EscapeDataString(redirectUri);

                HttpRequestMessage  _httpRequest  = new HttpRequestMessage();
                HttpResponseMessage tokenResponse = await _httpClient.PostAsync(TokenEndpoint + "?" + tokenRequest, _httpRequest.Content, Request.CallCancelled);

                tokenResponse.EnsureSuccessStatusCode();
                string text = await tokenResponse.Content.ReadAsStringAsync();

                IFormCollection form = WebHelpers.ParseForm(text);

                string accessToken = form["access_token"];
                string expires     = form["expires"];

                HttpResponseMessage graphResponse = await _httpClient.GetAsync(
                    ApiEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken) +
                    "&site=" + Uri.EscapeDataString(Options.Site) +
                    "&key=" + Uri.EscapeDataString(Options.Key), Request.CallCancelled);

                graphResponse.EnsureSuccessStatusCode();


                Stream rawStream = await graphResponse.Content.ReadAsStreamAsync();

                using (GZipStream gzipStream = new GZipStream(rawStream, CompressionMode.Decompress))
                    using (StreamReader streamReader = new StreamReader(gzipStream))
                    {
                        text = await streamReader.ReadToEndAsync();
                    }

                JObject info      = JObject.Parse(text);
                JToken  items     = info["items"];
                JToken  userToken = items.First;
                JObject user      = userToken as JObject;

                var context = new StackExchangeAuthenticatedContext(Context, user, accessToken, expires);
                context.Identity = new ClaimsIdentity(
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);
                if (!string.IsNullOrEmpty(context.UserId))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.UserId, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.DisplayName))
                {
                    context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.DisplayName, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Email))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.AccountId))
                {
                    context.Identity.AddClaim(new Claim("urn:stackexchange:accountId", context.AccountId, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Link))
                {
                    context.Identity.AddClaim(new Claim("urn:stackexchange:link", context.Link, XmlSchemaString, Options.AuthenticationType));
                }
                context.Properties = properties;

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError(ex.Message);
            }
            return(new AuthenticationTicket(null, properties));
        }
        private static void AddStringCollectionKey(StringBuilder builder,
                                                     string keyName,
                                                     string value,
                                                     IReadableStringCollection sourceCollection)
        {
            if (!string.IsNullOrEmpty(value))
            {
                // keyName(param1=value1|param2=value2)
                builder.Append(CacheKeyTokenSeparator)
                       .Append(keyName)
                       .Append("(");

                var tokenFound = false;
                foreach (var item in Tokenize(value))
                {
                    tokenFound = true;

                    builder.Append(item)
                           .Append(CacheKeyTokenSeparator)
                           .Append(sourceCollection[item])
                           .Append(CacheKeyTokenSeparator);
                }

                if (tokenFound)
                {
                    // Remove the trailing separator
                    builder.Length -= CacheKeyTokenSeparator.Length;
                }

                builder.Append(")");
            }
        }
Exemple #46
0
        protected override async Task ApplyResponseGrantAsync()
        {
            AuthenticationResponseGrant signin = Helper.LookupSignIn(Options.AuthenticationType);
            bool shouldSignin = signin != null;
            AuthenticationResponseRevoke signout = Helper.LookupSignOut(Options.AuthenticationType, Options.AuthenticationMode);
            bool shouldSignout = signout != null;

            if (!(shouldSignin || shouldSignout || _shouldRenew))
            {
                return;
            }

            AuthenticationTicket model = await AuthenticateAsync();

            try
            {
                var cookieOptions = new CookieOptions
                {
                    Domain   = Options.CookieDomain,
                    HttpOnly = Options.CookieHttpOnly,
                    Path     = Options.CookiePath ?? "/",
                };
                if (Options.CookieSecure == CookieSecureOption.SameAsRequest)
                {
                    cookieOptions.Secure = Request.IsSecure;
                }
                else
                {
                    cookieOptions.Secure = Options.CookieSecure == CookieSecureOption.Always;
                }

                #region == 登陆,登出,刷新 ==

                // 登陆
                if (shouldSignin)
                {
                    var signInContext = new CookieResponseSignInContext(
                        Context,
                        Options,
                        Options.AuthenticationType,
                        signin.Identity,
                        signin.Properties,
                        cookieOptions);

                    DateTimeOffset issuedUtc;
                    if (signInContext.Properties.IssuedUtc.HasValue)
                    {
                        issuedUtc = signInContext.Properties.IssuedUtc.Value;
                    }
                    else
                    {
                        issuedUtc = Options.SystemClock.UtcNow;
                        signInContext.Properties.IssuedUtc = issuedUtc;
                    }

                    if (!signInContext.Properties.ExpiresUtc.HasValue)
                    {
                        signInContext.Properties.ExpiresUtc = issuedUtc.Add(Options.ExpireTimeSpan);
                    }

                    Options.Provider.ResponseSignIn(signInContext);

                    if (signInContext.Properties.IsPersistent)
                    {
                        DateTimeOffset expiresUtc = signInContext.Properties.ExpiresUtc ?? issuedUtc.Add(Options.ExpireTimeSpan);
                        signInContext.CookieOptions.Expires = expiresUtc.ToUniversalTime().DateTime;
                    }

                    model = new AuthenticationTicket(signInContext.Identity, signInContext.Properties);
                    if (Options.SessionStore != null)
                    {
                        if (_sessionKey != null)
                        {
                            await Options.SessionStore.RemoveAsync(_sessionKey);
                        }
                        _sessionKey = await Options.SessionStore.StoreAsync(model);

                        ClaimsIdentity identity = new ClaimsIdentity(
                            new[] { new Claim(SessionIdClaim, _sessionKey) },
                            Options.AuthenticationType);
                        model = new AuthenticationTicket(identity, null);
                    }

                    string cookieValue = Options.TicketDataFormat.Protect(model);

                    Options.CookieManager.AppendResponseCookie(
                        Context,
                        Options.CookieName,
                        cookieValue,
                        signInContext.CookieOptions);

                    var signedInContext = new CookieResponseSignedInContext(
                        Context,
                        Options,
                        Options.AuthenticationType,
                        signInContext.Identity,
                        signInContext.Properties);

                    Options.Provider.ResponseSignedIn(signedInContext);
                }
                // 登出
                else if (shouldSignout)
                {
                    if (Options.SessionStore != null && _sessionKey != null)
                    {
                        await Options.SessionStore.RemoveAsync(_sessionKey);
                    }

                    var context = new CookieResponseSignOutContext(
                        Context,
                        Options,
                        cookieOptions);

                    Options.Provider.ResponseSignOut(context);

                    Options.CookieManager.DeleteCookie(
                        Context,
                        Options.CookieName,
                        context.CookieOptions);
                }
                // 刷新
                else if (_shouldRenew)
                {
                    model.Properties.IssuedUtc  = _renewIssuedUtc;
                    model.Properties.ExpiresUtc = _renewExpiresUtc;

                    if (Options.SessionStore != null && _sessionKey != null)
                    {
                        await Options.SessionStore.RenewAsync(_sessionKey, model);

                        ClaimsIdentity identity = new ClaimsIdentity(
                            new[] { new Claim(SessionIdClaim, _sessionKey) },
                            Options.AuthenticationType);
                        model = new AuthenticationTicket(identity, null);
                    }

                    string cookieValue = Options.TicketDataFormat.Protect(model);

                    if (model.Properties.IsPersistent)
                    {
                        cookieOptions.Expires = _renewExpiresUtc.ToUniversalTime().DateTime;
                    }

                    Options.CookieManager.AppendResponseCookie(
                        Context,
                        Options.CookieName,
                        cookieValue,
                        cookieOptions);
                }

                #endregion

                Response.Headers.Set(
                    HeaderNameCacheControl,
                    HeaderValueNoCache);

                Response.Headers.Set(
                    HeaderNamePragma,
                    HeaderValueNoCache);

                Response.Headers.Set(
                    HeaderNameExpires,
                    HeaderValueMinusOne);

                // 跳转
                bool shouldLoginRedirect  = shouldSignin && Options.LoginPath.HasValue && Request.Path == Options.LoginPath;
                bool shouldLogoutRedirect = shouldSignout && Options.LogoutPath.HasValue && Request.Path == Options.LogoutPath;

                if ((shouldLoginRedirect || shouldLogoutRedirect) && Response.StatusCode == 200)
                {
                    IReadableStringCollection query = Request.Query;
                    string redirectUri = query.Get(Options.ReturnUrlParameter); // 根据url参数读取 跳转url
                    if (!string.IsNullOrWhiteSpace(redirectUri) &&
                        IsHostRelative(redirectUri))
                    {
                        var redirectContext = new CookieApplyRedirectContext(Context, Options, redirectUri);
                        Options.Provider.ApplyRedirect(redirectContext);
                    }
                }
            }
            catch (Exception exception)
            {
                CookieExceptionContext exceptionContext = new CookieExceptionContext(Context, Options,
                                                                                     CookieExceptionContext.ExceptionLocation.ApplyResponseGrant, exception, model);
                Options.Provider.Exception(exceptionContext);
                if (exceptionContext.Rethrow)
                {
                    throw;
                }
            }
        }
Exemple #47
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                string code  = null;
                string state = null;

                IReadableStringCollection query = Request.Query;

                IList <string> values = query.GetValues("error");
                if (values != null && values.Count >= 1)
                {
                    _logger.WriteVerbose("Remote server returned an error: " + Request.QueryString);
                }

                values = query.GetValues("code");
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }
                values = query.GetValues("state");
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }

                properties = Options.StateDataFormat.Unprotect(state);
                if (properties == null)
                {
                    return(null);
                }

                if (code == null)
                {
                    // Null if the remote server returns an error.
                    return(new AuthenticationTicket(null, properties));
                }

                string requestPrefix = Request.Scheme + "://" + Request.Host;
                string redirectUri   = requestPrefix + Request.PathBase + Options.CallbackPath;

                var formContent = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair <string, string>("code", Uri.EscapeDataString(code))
                });

                HttpResponseMessage tokenResponse = await _httpClient.PostAsync(Options.UserInformationEndpoint, formContent, Request.CallCancelled);

                tokenResponse.EnsureSuccessStatusCode();
                string user = await tokenResponse.Content.ReadAsStringAsync();

                JObject response = JObject.Parse(user);

                string accessToken = response.Value <string>("access_token");

                if (string.IsNullOrWhiteSpace(accessToken))
                {
                    _logger.WriteWarning("Access token was not found");
                    return(new AuthenticationTicket(null, properties));
                }

                var email           = response.Value <string>("Email");
                var defaultUserName = response.Value <string>("DefaultUserName");

                var context = new VanLangAuthenticatedContext(Context);
                context.Identity = new ClaimsIdentity(
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);
                context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, accessToken, XmlSchemaString, Options.AuthenticationType));
                if (!string.IsNullOrEmpty(defaultUserName))
                {
                    context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, defaultUserName, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(email))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Email, email, XmlSchemaString, Options.AuthenticationType));
                }
                context.Properties = properties;

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError("Authentication failed", ex);
                return(new AuthenticationTicket(null, properties));
            }
        }
Exemple #48
0
        private static NameValueCollection BuildParams(IFormCollection form, IReadableStringCollection query)
        {
            var nvc = new NameValueCollection();
            if (form != null)
                foreach (var item in form)
                    nvc[item.Key] = item.Value[0];
            foreach (var item in query)
                nvc[item.Key] = item.Value[0];
            return nvc;

        }
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;
            string code  = null;
            string state = null;

            try
            {
                IReadableStringCollection query  = Request.Query;
                IList <string>            values = query.GetValues("code");
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }
                values = query.GetValues("state");
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }

                properties = Options.StateDataFormat.Unprotect(state);

                if (code == null)
                {
                    // Null if the remote server returns an error.
                    return(new AuthenticationTicket(null, properties));
                }

                var tokenRequestParameters = string.Format(
                    CultureInfo.InvariantCulture,
                    "client_id={0}&redirect_uri={1}&client_secret={2}&code={3}&grant_type=authorization_code",
                    Uri.EscapeDataString(Options.ClientId),
                    Uri.EscapeDataString(GenerateRedirectUri(properties)),
                    Uri.EscapeDataString(Options.ClientSecret),
                    code);

                var body = new Dictionary <string, string> {
                    { "client_id", Options.ClientId },
                    { "redirect_uri", GenerateRedirectUri(properties) },
                    { "client_secret", Options.ClientSecret },
                    { "code", Uri.EscapeDataString(code) },
                    { "grant_type", "authorization_code" }
                };

                HttpResponseMessage tokenResponse = await _httpClient.PostAsync(string.Format(TokenEndpoint, Options.Domain), new FormUrlEncodedContent(body), Request.CallCancelled);
                await EnsureTokenExchangeSuccessful(tokenResponse);

                string text = await tokenResponse.Content.ReadAsStringAsync();

                JObject tokens = JObject.Parse(text);

                string accessToken  = tokens["access_token"].Value <string>();
                string idToken      = tokens["id_token"] != null ? tokens["id_token"].Value <string>() : null;
                string refreshToken = tokens["refresh_token"] != null ? tokens["refresh_token"].Value <string>() : null;

                HttpResponseMessage graphResponse = await _httpClient.GetAsync(
                    string.Format(UserInfoEndpoint, Options.Domain) + "?access_token=" + Uri.EscapeDataString(accessToken), Request.CallCancelled);

                graphResponse.EnsureSuccessStatusCode();
                text = await graphResponse.Content.ReadAsStringAsync();

                JObject user = JObject.Parse(text);

                var context = new Auth0AuthenticatedContext(Context, user, accessToken, idToken, refreshToken);
                context.Identity = new ClaimsIdentity(
                    new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, context.Id, "http://www.w3.org/2001/XMLSchema#string", context.Connection),
                    new Claim(ClaimTypes.Name, context.Name, "http://www.w3.org/2001/XMLSchema#string", context.Connection),
                    new Claim("user_id", context.Id, "http://www.w3.org/2001/XMLSchema#string", Constants.Auth0Issuer),
                },
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);

                if (!string.IsNullOrWhiteSpace(context.Email))
                {
                    context.Identity.AddClaim(new Claim("email", context.Email, "http://www.w3.org/2001/XMLSchema#string", context.Connection));
                    context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, "http://www.w3.org/2001/XMLSchema#string", context.Connection));
                }

                if (!string.IsNullOrWhiteSpace(context.FirstName))
                {
                    context.Identity.AddClaim(new Claim("given_name", context.FirstName, "http://www.w3.org/2001/XMLSchema#string", context.Connection));
                }
                if (!string.IsNullOrWhiteSpace(context.LastName))
                {
                    context.Identity.AddClaim(new Claim("family_name", context.LastName, "http://www.w3.org/2001/XMLSchema#string", context.Connection));
                }
                if (!string.IsNullOrWhiteSpace(context.Connection))
                {
                    context.Identity.AddClaim(new Claim("connection", context.Connection, "http://www.w3.org/2001/XMLSchema#string", context.Connection));
                }
                if (!string.IsNullOrWhiteSpace(context.Picture))
                {
                    context.Identity.AddClaim(new Claim("picture", context.Picture, "http://www.w3.org/2001/XMLSchema#string", context.Connection));
                }
                if (!string.IsNullOrWhiteSpace(context.Provider))
                {
                    context.Identity.AddClaim(new Claim("provider", context.Provider, "http://www.w3.org/2001/XMLSchema#string", context.Connection));
                }
                if (!string.IsNullOrWhiteSpace(context.ProviderAccessToken))
                {
                    context.Identity.AddClaim(new Claim("provider_access_token", context.ProviderAccessToken, "http://www.w3.org/2001/XMLSchema#string", context.Connection));
                }

                if (Options.SaveIdToken && !string.IsNullOrWhiteSpace(context.IdToken))
                {
                    context.Identity.AddClaim(new Claim("id_token", context.IdToken, "http://www.w3.org/2001/XMLSchema#string", Constants.Auth0Issuer));
                }
                if (Options.SaveRefreshToken && !string.IsNullOrWhiteSpace(context.RefreshToken))
                {
                    context.Identity.AddClaim(new Claim("refresh_token", context.RefreshToken, "http://www.w3.org/2001/XMLSchema#string", Constants.Auth0Issuer));
                }
                context.Identity.AddClaim(new Claim("access_token", context.AccessToken, "http://www.w3.org/2001/XMLSchema#string", Constants.Auth0Issuer));

                context.Properties = properties ?? new AuthenticationProperties();

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                var tokenExchangeFailedContext = new Auth0TokenExchangeFailedContext(
                    Context, Options,
                    ex, code, state);
                Options.Provider.TokenExchangeFailed(tokenExchangeFailedContext);

                _logger.WriteError(ex.Message);
            }
            return(new AuthenticationTicket(null, properties));
        }
        private Dictionary<string, string> ToDictionary(IReadableStringCollection nameValueCollection)
        {
            var result = new Dictionary<string, string>();

            foreach (var kvp in nameValueCollection)
            {
                result[kvp.Key] = nameValueCollection.Get(kvp.Key);
            }

            return result;
        }
Exemple #51
0
 public RequestCookiesFeature([NotNull] IReadableStringCollection cookies)
 {
     _cookies = cookies;
 }
Exemple #52
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                string code  = null;
                string state = null;

                IReadableStringCollection query  = Request.Query;
                IList <string>            values = query.GetValues("code");
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }
                values = query.GetValues("state");
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }

                properties = Options.StateDataFormat.Unprotect(state);
                if (properties == null)
                {
                    return(null);
                }

                // OAuth2 10.12 CSRF
                if (!ValidateCorrelationId(properties, _logger))
                {
                    return(new AuthenticationTicket(null, properties));
                }

                var tokenRequestParameters = new List <KeyValuePair <string, string> >()
                {
                    new KeyValuePair <string, string>("client_id", Options.ClientId),
                    new KeyValuePair <string, string>("redirect_uri", GenerateRedirectUri()),
                    new KeyValuePair <string, string>("client_secret", Options.ClientSecret),
                    new KeyValuePair <string, string>("code", code),
                    new KeyValuePair <string, string>("grant_type", "authorization_code"),
                };

                var requestContent = new FormUrlEncodedContent(tokenRequestParameters);

                HttpResponseMessage response = await _httpClient.PostAsync(TokenEndpoint, requestContent, Request.CallCancelled);

                response.EnsureSuccessStatusCode();
                string oauthTokenResponse = await response.Content.ReadAsStringAsync();

                JObject oauth2Token = JObject.Parse(oauthTokenResponse);
                var     accessToken = oauth2Token["access_token"].Value <string>();

                // Refresh token is only available when wl.offline_access is request.
                // Otherwise, it is null.
                var refreshToken = oauth2Token.Value <string>("refresh_token");
                var expire       = oauth2Token.Value <string>("expires_in");

                if (string.IsNullOrWhiteSpace(accessToken))
                {
                    _logger.WriteWarning("Access token was not found");
                    return(new AuthenticationTicket(null, properties));
                }

                HttpResponseMessage graphResponse = await _httpClient.GetAsync(
                    GraphApiEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken), Request.CallCancelled);

                graphResponse.EnsureSuccessStatusCode();
                string accountString = await graphResponse.Content.ReadAsStringAsync();

                JObject accountInformation = JObject.Parse(accountString);

                var context = new MicrosoftAccountAuthenticatedContext(Context, accountInformation, accessToken,
                                                                       refreshToken, expire);
                context.Identity = new ClaimsIdentity(
                    new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, context.Id, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType),
                    new Claim(ClaimTypes.Name, context.Name, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType),
                    new Claim("urn:microsoftaccount:id", context.Id, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType),
                    new Claim("urn:microsoftaccount:name", context.Name, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType)
                },
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);
                if (!string.IsNullOrWhiteSpace(context.Email))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));
                }

                await Options.Provider.Authenticated(context);

                context.Properties = properties;

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError("Authentication failed", ex);
                return(new AuthenticationTicket(null, properties));
            }
        }
        protected async override Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;
            AuthenticationTicket     authenticationTicket;

            IReadableStringCollection query = this.Request.Query;

            properties = this.UnpackStateParameter(query);
            string         code   = string.Empty;
            IList <string> values = query.GetValues("code");

            if (values != null && values.Count == 1)
            {
                code = values[0];
            }
            if (string.IsNullOrEmpty(code))
            {
                authenticationTicket = new AuthenticationTicket(null, properties);
                return(authenticationTicket);
            }

            if (properties == null)
            {
                authenticationTicket = null;
            }
            else if (!this.ValidateCorrelationId(properties, this._logger))
            {
                authenticationTicket = new AuthenticationTicket(null, properties);
            }
            else
            {
                string tokenEndpoint = "https://api.weibo.com/oauth2/access_token?client_id={0}&client_secret={1}&grant_type=authorization_code&redirect_uri={3}&code={2}";
                var    url           = string.Format(
                    tokenEndpoint,
                    Uri.EscapeDataString(this.Options.AppID),
                    Uri.EscapeDataString(this.Options.AppKey),
                    Uri.EscapeDataString(code), Uri.EscapeDataString("http://" + this.Request.Host));
                HttpResponseMessage tokenResponse = await this._httpClient.PostAsync(url, new StringContent(""), this.Request.CallCancelled);

                tokenResponse.EnsureSuccessStatusCode();
                string access_tokenReturnValue = await tokenResponse.Content.ReadAsStringAsync();

                var accesstokenpa = "\"access_token\":\"(.+?)\"";
                var accesstoken   = Regex.Match(access_tokenReturnValue, accesstokenpa).Groups[1].Value;
                var uidpa         = "\"uid\":\"(.+?)\"";
                var openid        = Regex.Match(access_tokenReturnValue, uidpa).Groups[1].Value;

                var nameurlFormate = "https://api.weibo.com/2/users/show.json?access_token={0}&uid={1}";
                var nameurl        = string.Format(
                    nameurlFormate,
                    Uri.EscapeDataString(accesstoken),
                    Uri.EscapeDataString(openid));
                var nameResponse = await this._httpClient.GetAsync(nameurl, this.Request.CallCancelled);

                nameResponse.EnsureSuccessStatusCode();
                string nametxt = await nameResponse.Content.ReadAsStringAsync();

                var namepa = "\"name\":\"(.+?)\"";
                var name   = Regex.Match(nametxt, namepa).Groups[1].Value;
                //todo

                var context = new SinaAuthenticatedContext(this.Context, accesstoken, openid, name);

                var identity = new ClaimsIdentity(this.Options.AuthenticationType);

                if (!string.IsNullOrEmpty(context.OpenId))
                {
                    identity.AddClaim(
                        new Claim(
                            "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier",
                            context.OpenId,
                            "http://www.w3.org/2001/XMLSchema#string",
                            this.Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Name))
                {
                    identity.AddClaim(
                        new Claim(
                            "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",
                            context.Name,
                            "http://www.w3.org/2001/XMLSchema#string",
                            this.Options.AuthenticationType));
                }
                await this.Options.Provider.Authenticated(context);

                authenticationTicket = new AuthenticationTicket(identity, properties);
            }
            return(authenticationTicket);
        }
 public Message(IReadableStringCollection parameters, bool strict)
 {
     Namespaces = new Dictionary<string, Property>(StringComparer.Ordinal);
     Properties = new Dictionary<string, Property>(parameters.Count(), StringComparer.Ordinal);
     Add(parameters, strict);
 }
        public static ScimQueryOptions GetScimQueryOptions(this IReadableStringCollection collection, ScimServerConfiguration configuration)
        {
            var queryOptions = new ScimQueryOptions();

            queryOptions.Attributes = collection.GetValues("attributes")
                                      .ToMaybe()
                                      .Bind(attributes => new HashSet <string>(attributes.Distinct(StringComparer.OrdinalIgnoreCase), StringComparer.OrdinalIgnoreCase).ToMaybe())
                                      .FromMaybe(new HashSet <string>());

            queryOptions.ExcludedAttributes = collection.GetValues("excludedAttributes")
                                              .ToMaybe()
                                              .Bind(attributes => new HashSet <string>(attributes.Distinct(StringComparer.OrdinalIgnoreCase), StringComparer.OrdinalIgnoreCase).ToMaybe())
                                              .FromMaybe(new HashSet <string>());

            queryOptions.Filter = collection.Get("filter")
                                  .ToMaybe()
                                  .Bind(filter => new ScimFilter(configuration.ResourceExtensionSchemas.Keys, filter).Paths.MaybeSingle())
                                  .FromMaybe(null);

            queryOptions.SortBy = collection.Get("sortBy");

            queryOptions.SortOrder = collection.Get("sortOrder")
                                     .ToMaybe()
                                     .Bind(
                sortOrder =>
                (sortOrder.Equals("descending", StringComparison.OrdinalIgnoreCase)
                            ? SortOrder.Descending
                            : SortOrder.Ascending).ToMaybe())
                                     .FromMaybe(SortOrder.Ascending); // default

            queryOptions.StartIndex = collection.Get("startIndex")
                                      .ToMaybe()
                                      .Bind(index =>
            {
                // The 1-based index of the first query result. A value less than 1 SHALL be interpreted as 1.

                int indexInt = 1;
                try { indexInt = Convert.ToInt32(index); } catch {}

                return((indexInt < 1 ? 1 : indexInt).ToMaybe());
            })
                                      .FromMaybe(1); // default

            queryOptions.Count = collection.Get("count")
                                 .ToMaybe()
                                 .Bind(count =>
            {
                // Non-negative integer. Specifies the desired maximum number of query
                // results per page, e.g., 10. A negative value SHALL be interpreted as
                // "0". A value of "0" indicates that no resource indicates that no resource
                // except for "totalResults".

                int countInt = 0;
                try { countInt = Convert.ToInt32(count); } catch { }

                return((countInt < 0 ? 0 : countInt).ToMaybe());
            })
                                 .FromMaybe(configuration.GetFeature <ScimFeatureFilter>(ScimFeatureType.Filter).MaxResults); // default

            return(queryOptions);
        }
 public ReadableStringCollectionWrapper(IReadableStringCollection readableStringCollection)
 {
     _readableStringCollection = readableStringCollection;
 }
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                IReadableStringCollection query = Request.Query;

                properties = UnpackStateParameter(query);
                if (properties == null)
                {
                    _logger.WriteWarning("Invalid return state");
                    return(null);
                }

                // Anti-CSRF
                if (!ValidateCorrelationId(properties, _logger))
                {
                    return(new AuthenticationTicket(null, properties));
                }

                Message message = await ParseRequestMessageAsync(query);

                bool messageValidated = false;

                Property mode;
                if (!message.Properties.TryGetValue("mode.http://specs.openid.net/auth/2.0", out mode))
                {
                    _logger.WriteWarning("Missing mode parameter");
                    return(new AuthenticationTicket(null, properties));
                }

                if (string.Equals("cancel", mode.Value, StringComparison.Ordinal))
                {
                    _logger.WriteWarning("User cancelled signin request");
                    return(new AuthenticationTicket(null, properties));
                }

                if (string.Equals("id_res", mode.Value, StringComparison.Ordinal))
                {
                    mode.Value = "check_authentication";

                    var requestBody = new FormUrlEncodedContent(message.ToFormValues());
                    HttpResponseMessage response = await _httpClient.PostAsync("https://www.google.com/accounts/o8/ud", requestBody, Request.CallCancelled);

                    response.EnsureSuccessStatusCode();
                    string responseBody = await response.Content.ReadAsStringAsync();

                    var verifyBody = new Dictionary <string, string[]>();
                    foreach (var line in responseBody.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        int delimiter = line.IndexOf(':');
                        if (delimiter != -1)
                        {
                            verifyBody.Add("openid." + line.Substring(0, delimiter), new[] { line.Substring(delimiter + 1) });
                        }
                    }
                    var      verifyMessage = new Message(new ReadableStringCollection(verifyBody), strict: false);
                    Property isValid;
                    if (verifyMessage.Properties.TryGetValue("is_valid.http://specs.openid.net/auth/2.0", out isValid))
                    {
                        if (string.Equals("true", isValid.Value, StringComparison.Ordinal))
                        {
                            messageValidated = true;
                        }
                        else
                        {
                            messageValidated = false;
                        }
                    }
                }

                // http://openid.net/specs/openid-authentication-2_0.html#verify_return_to
                // To verify that the "openid.return_to" URL matches the URL that is processing this assertion:
                // * The URL scheme, authority, and path MUST be the same between the two URLs.
                // * Any query parameters that are present in the "openid.return_to" URL MUST also
                //   be present with the same values in the URL of the HTTP request the RP received.
                if (messageValidated)
                {
                    // locate the required return_to parameter
                    string actualReturnTo;
                    if (!message.TryGetValue("return_to.http://specs.openid.net/auth/2.0", out actualReturnTo))
                    {
                        _logger.WriteWarning("openid.return_to parameter missing at return address");
                        messageValidated = false;
                    }
                    else
                    {
                        // create the expected return_to parameter based on the URL that is processing
                        // the assertion, plus exactly and only the the query string parameter (state)
                        // that this RP must have received
                        string expectedReturnTo = BuildReturnTo(GetStateParameter(query));

                        if (!string.Equals(actualReturnTo, expectedReturnTo, StringComparison.Ordinal))
                        {
                            _logger.WriteWarning("openid.return_to parameter not equal to expected value based on return address");
                            messageValidated = false;
                        }
                    }
                }

                if (messageValidated)
                {
                    IDictionary <string, string> attributeExchangeProperties = new Dictionary <string, string>();
                    foreach (var typeProperty in message.Properties.Values)
                    {
                        if (typeProperty.Namespace == "http://openid.net/srv/ax/1.0" &&
                            typeProperty.Name.StartsWith("type."))
                        {
                            string   qname = "value." + typeProperty.Name.Substring("type.".Length) + "http://openid.net/srv/ax/1.0";
                            Property valueProperty;
                            if (message.Properties.TryGetValue(qname, out valueProperty))
                            {
                                attributeExchangeProperties.Add(typeProperty.Value, valueProperty.Value);
                            }
                        }
                    }

                    var responseNamespaces = new object[]
                    {
                        new XAttribute(XNamespace.Xmlns + "openid", "http://specs.openid.net/auth/2.0"),
                        new XAttribute(XNamespace.Xmlns + "openid.ax", "http://openid.net/srv/ax/1.0")
                    };

                    IEnumerable <object> responseProperties = message.Properties
                                                              .Where(p => p.Value.Namespace != null)
                                                              .Select(p => (object)new XElement(XName.Get(p.Value.Name.Substring(0, p.Value.Name.Length - 1), p.Value.Namespace), p.Value.Value));

                    var responseMessage = new XElement("response", responseNamespaces.Concat(responseProperties).ToArray());

                    var      identity  = new ClaimsIdentity(Options.AuthenticationType);
                    XElement claimedId = responseMessage.Element(XName.Get("claimed_id", "http://specs.openid.net/auth/2.0"));
                    if (claimedId != null)
                    {
                        identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, claimedId.Value, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));
                    }

                    string firstValue;
                    if (attributeExchangeProperties.TryGetValue("http://axschema.org/namePerson/first", out firstValue))
                    {
                        identity.AddClaim(new Claim(ClaimTypes.GivenName, firstValue, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));
                    }
                    string lastValue;
                    if (attributeExchangeProperties.TryGetValue("http://axschema.org/namePerson/last", out lastValue))
                    {
                        identity.AddClaim(new Claim(ClaimTypes.Surname, lastValue, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));
                    }
                    string nameValue;
                    if (attributeExchangeProperties.TryGetValue("http://axschema.org/namePerson", out nameValue))
                    {
                        identity.AddClaim(new Claim(ClaimTypes.Name, nameValue, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));
                    }
                    else if (!string.IsNullOrEmpty(firstValue) && !string.IsNullOrEmpty(lastValue))
                    {
                        identity.AddClaim(new Claim(ClaimTypes.Name, firstValue + " " + lastValue, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));
                    }
                    else if (!string.IsNullOrEmpty(firstValue))
                    {
                        identity.AddClaim(new Claim(ClaimTypes.Name, firstValue, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));
                    }
                    else if (!string.IsNullOrEmpty(lastValue))
                    {
                        identity.AddClaim(new Claim(ClaimTypes.Name, lastValue, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));
                    }
                    string emailValue;
                    if (attributeExchangeProperties.TryGetValue("http://axschema.org/contact/email", out emailValue))
                    {
                        identity.AddClaim(new Claim(ClaimTypes.Email, emailValue, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));
                    }

                    var context = new GoogleAuthenticatedContext(
                        Context,
                        identity,
                        properties,
                        responseMessage,
                        attributeExchangeProperties);

                    await Options.Provider.Authenticated(context);

                    return(new AuthenticationTicket(context.Identity, context.Properties));
                }

                return(new AuthenticationTicket(null, properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError("Authentication failed", ex);
                return(new AuthenticationTicket(null, properties));
            }
        }