コード例 #1
0
        public string ToOAuthHeader()
        {
            var authHeader = new StringBuilder();

            authHeader.Append(string.Format("{0} ", OAuthConstants.AUTHORIZATION_OAUTH));

            if (!string.IsNullOrEmpty(RequestParameters[OAuthParameter.OAUTH_REALM]))
            {
                authHeader.Append(string.Format("{0}={1},", OAuthParameter.OAUTH_REALM, OAuthParameter.UrlEncode(RequestParameters[OAuthParameter.OAUTH_REALM])));
            }

            authHeader.Append(string.Format("{0}={1},", OAuthParameter.OAUTH_CONSUMER_KEY, OAuthParameter.UrlEncode(RequestParameters[OAuthParameter.OAUTH_CONSUMER_KEY])));

            if (!string.IsNullOrEmpty(RequestParameters[OAuthParameter.OAUTH_TOKEN]))
            {
                authHeader.Append(string.Format("{0}={1},", OAuthParameter.OAUTH_TOKEN, OAuthParameter.UrlEncode(RequestParameters[OAuthParameter.OAUTH_TOKEN])));
            }

            authHeader.Append(string.Format("{0}={1},", OAuthParameter.OAUTH_SIGNATURE_METHOD, OAuthParameter.UrlEncode(RequestParameters[OAuthParameter.OAUTH_SIGNATURE_METHOD])));
            authHeader.Append(string.Format("{0}={1},", OAuthParameter.OAUTH_SIGNATURE, OAuthParameter.UrlEncode(RequestParameters[OAuthParameter.OAUTH_SIGNATURE])));
            authHeader.Append(string.Format("{0}={1},", OAuthParameter.OAUTH_TIMESTAMP, OAuthParameter.UrlEncode(RequestParameters[OAuthParameter.OAUTH_TIMESTAMP])));
            authHeader.Append(string.Format("{0}={1}", OAuthParameter.OAUTH_NONCE, OAuthParameter.UrlEncode(RequestParameters[OAuthParameter.OAUTH_NONCE])));

            if (!string.IsNullOrEmpty(RequestParameters[OAuthParameter.OAUTH_VERSION]))
            {
                authHeader.Append(string.Format(",{0}={1}", OAuthParameter.OAUTH_VERSION, OAuthParameter.UrlEncode(RequestParameters[OAuthParameter.OAUTH_VERSION])));
            }

            return(authHeader.ToString());
        }
コード例 #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TwitterOAuthRequestBuilder"/> class.
        /// Authorization request builder.
        /// </summary>
        /// <param name="requestUri">Request Uri.</param>
        /// <param name="tokens">Tokens to form request.</param>
        /// <param name="signatureManager">Signature manager to sign the OAuth request</param>
        /// <param name="method">Method to use with request.</param>
        public TwitterOAuthRequestBuilder(Uri requestUri, TwitterOAuthTokens tokens, ISignatureManager signatureManager, string method = "GET")
        {
            _signatureManager = signatureManager;
            Verb = method;

            RequestUriWithoutQuery = new Uri(requestUri.AbsoluteWithoutQuery());

            if (!string.IsNullOrEmpty(requestUri.Query))
            {
                QueryParams = requestUri.GetQueryParams()
                              .Select(p => new OAuthParameter(p.Key, Uri.UnescapeDataString(p.Value)))
                              .ToList();
            }
            else
            {
                QueryParams = new List <OAuthParameter>();
            }

            EncodedRequestUri = GetEncodedUri(requestUri, QueryParams);

            Version         = new OAuthParameter("oauth_version", "1.0");
            Nonce           = new OAuthParameter("oauth_nonce", GenerateNonce());
            Timestamp       = new OAuthParameter("oauth_timestamp", GenerateTimeStamp());
            SignatureMethod = new OAuthParameter("oauth_signature_method", "HMAC-SHA1");
            ConsumerKey     = new OAuthParameter("oauth_consumer_key", tokens.ConsumerKey);
            ConsumerSecret  = new OAuthParameter("oauth_consumer_secret", tokens.ConsumerSecret);
            Token           = new OAuthParameter("oauth_token", tokens.AccessToken);
            TokenSecret     = new OAuthParameter("oauth_token_secret", tokens.AccessTokenSecret);
        }
コード例 #3
0
        public override string BuildSignature(WebRequest webRequest, IOAuthConsumer consumer, IOAuthToken ioAuthToken)
        {
            if (consumer == null)
            {
                throw new ArgumentNullException(ERROR_CONSUMER_NULL);
            }

            if (ioAuthToken == null)
            {
                throw new ArgumentNullException(ERROR_TOKEN_NULL);
            }

            var requestUri = string.Format("{0}://{1}{2}", webRequest.RequestUri.Scheme, webRequest.RequestUri.Authority, webRequest.RequestUri.AbsolutePath);
            var request    = WebRequest.Create(requestUri);

            request.Method = webRequest.Method;

            var           key             = string.Format(FORMAT_PARAMETER, OAuthParameter.UrlEncode(consumer.ConsumerSecret), OAuthParameter.UrlEncode(ioAuthToken.TokenSecret));
            HashAlgorithm hashAlgorithm   = new HMACSHA1(Encoding.UTF8.GetBytes(key));
            var           canonicalString = this.GetCanonicalString(request, consumer, ioAuthToken);
            var           encoded         = Encoding.UTF8.GetBytes(canonicalString);
            var           result          = Convert.ToBase64String(hashAlgorithm.ComputeHash(encoded));

            return(result);
        }
コード例 #4
0
        private static string GetSortedString(NameValueCollection list)
        {
            var sb   = new StringBuilder();
            var keys = list.AllKeys;

            Array.Sort(keys);

            foreach (var key in keys)
            {
                var valuesArray = list.GetValues(key);
                if (valuesArray == null)
                {
                    continue;
                }

                Array.Sort(valuesArray);

                foreach (var myvalue in valuesArray)
                {
                    sb.Append(OAuthParameter.UrlEncode(key)).Append('=');
                    sb.Append(OAuthParameter.UrlEncode(myvalue));
                    sb.Append('&');
                }
            }

            if (sb.Length > 1)
            {
                sb.Remove(sb.Length - 1, 1);
            }

            return(sb.ToString());
        }
コード例 #5
0
        protected string GetCanonicalString(WebRequest webRequest, IOAuthConsumer consumer, IOAuthToken ioAuthToken)
        {
            if (string.IsNullOrEmpty(webRequest.Method))
            {
                throw new ArgumentNullException(ERROR_HTTP_METHOD);
            }

            var stringToSign = new StringBuilder();

            stringToSign.Append(webRequest.Method.ToUpper().Trim());
            stringToSign.Append(OAuthParameter.QUERYSTRING_SEPERATOR);
            //TODO: check if querystring should be part of it
            stringToSign.Append(OAuthParameter.UrlEncode(webRequest.RequestUri.AbsoluteUri));
            stringToSign.Append(OAuthParameter.QUERYSTRING_SEPERATOR);

            if (RequestParameters[OAuthParameter.OAUTH_REALM] != null)
            {
                RequestParameters.Remove(OAuthParameter.OAUTH_REALM);
            }

            if (RequestParameters[OAuthParameter.OAUTH_SIGNATURE] != null)
            {
                RequestParameters.Remove(OAuthParameter.OAUTH_SIGNATURE);
            }

            //TODO: input correct parameters
            if (RequestParameters[OAuthParameter.OAUTH_SIGNATURE_METHOD] == null)
            {
                RequestParameters.Add(OAuthParameter.OAUTH_SIGNATURE_METHOD, GeneralUtil.SignatureMethodTypeToString(consumer.OAuthSignatureMethod));
            }

            if (RequestParameters[OAuthParameter.OAUTH_CONSUMER_KEY] == null)
            {
                RequestParameters.Add(OAuthParameter.OAUTH_CONSUMER_KEY, consumer.ConsumerKey);
            }

            if (RequestParameters[OAuthParameter.OAUTH_VERSION] == null)
            {
                RequestParameters.Add(OAuthParameter.OAUTH_VERSION, GeneralUtil.OAuthVersionTypeToString(consumer.OAuthVersion));
            }

            if (RequestParameters[OAuthParameter.OAUTH_TIMESTAMP] == null)
            {
                RequestParameters.Add(OAuthParameter.OAUTH_TIMESTAMP, GenerateTimeStamp());
            }
            if (RequestParameters[OAuthParameter.OAUTH_NONCE] == null)
            {
                RequestParameters.Add(OAuthParameter.OAUTH_NONCE, GenerateNonce());
            }
            if (RequestParameters[OAuthParameter.OAUTH_TOKEN] == null && !string.IsNullOrEmpty(ioAuthToken.TokenKey))
            {
                RequestParameters.Add(OAuthParameter.OAUTH_TOKEN, ioAuthToken.TokenKey);
            }

            stringToSign.Append(OAuthParameter.UrlEncode(GetNormalizedParameterString(RequestParameters).Trim()));

            return(stringToSign.ToString());
        }
コード例 #6
0
        public SSOIdentity OAuth(OAuthParameter param)
        {
            var id = mgr.OAuth(param);

            if (id.IsAuthenticated)
            {
                this.SetSignIn(id);
            }
            return(id);
        }
コード例 #7
0
 public static string ToStringValue(this OAuthParameter value)
 {
     if (Enum.IsDefined(typeof(OAuthParameter), value))
     {
         return(OAuthParametersNames[value]);
     }
     else
     {
         throw new NotImplementedException();
     }
 }
コード例 #8
0
        /// <summary>
        /// This method is meant for servers to validate incoming OAuth requests from MySpace typically made through an OpenSocial makeRequest call, or an iFrame src attribute. If the return value is true, it means that the signature contained in the request matches the actual request that was signed with the correct consumer secret for that consumer key.
        /// </summary>
        /// <param name="apiServerUri">Your server which is being requested by MySpace(e.g. http://localhost:9090/ or http://myserver.com/).</param>
        /// <param name="resourcePath">The relative path of the resource being requested.</param>
        /// <param name="httpRequest">The request</param>
        /// <param name="accessTokenSecret">The access token of the particular request. This will be empty for onsite apps and iFrame src attributes.</param>
        /// <returns>True if the signature in the request matches correctly.</returns>
        public bool ValidateSignature(string apiServerUri, string resourcePath, HttpRequest httpRequest, string accessTokenSecret)
        {
            OAuthParameter oAuthParameter = null;

            try
            {
                oAuthParameter = OAuthParameter.FromHttpContext(httpRequest.Headers, httpRequest.QueryString);
            }
            catch (ArgumentNullException)
            {
                var x = 1;
            }
            catch
            {
                var y = 2;
            }

            if (oAuthParameter == null)
            {
                //TODO: change to problem reporting
                throw new ArgumentException("no oauth parameters found");
            }

            if (oAuthParameter.HasError)
            {
                return(false);
            }

            var oAuthSigner         = new OAuthSigner();
            var signatureMethodType = GeneralUtil.StringToSignatureMethodType(oAuthParameter.SignatureMethod);
            var signatureMethod     = oAuthSigner.GetSignatureMethod(signatureMethodType);

            signatureMethod.RequestParameters.Add(oAuthParameter.ToCollection());
            signatureMethod.RequestParameters.Add(oAuthParameter.UnknownParameterCollection);

            //if (string.IsNullOrEmpty(oAuthParameter.Token))
            //{
            //    signatureMethod.RequestParameters.Add(OAuthParameter.OAUTH_TOKEN, string.Empty);
            //}

            var request = WebRequest.Create(apiServerUri + resourcePath);

            request.Method = httpRequest.HttpMethod;

            var consumer  = new OAuthConsumer(apiServerUri, oAuthParameter.ConsumerKey, consumerSecret);
            var token     = new ConsumerToken(consumer, oAuthParameter.Token, accessTokenSecret);
            var signature = signatureMethod.BuildSignature(request, consumer, token);

            return(oAuthParameter.Signature == signature);
        }
コード例 #9
0
        public override string BuildSignature(WebRequest webRequest, IOAuthConsumer consumer, IOAuthToken ioAuthToken)
        {
            if (consumer == null)
            {
                throw new ArgumentNullException(ERROR_CONSUMER_NULL);
            }

            if (ioAuthToken == null)
            {
                throw new ArgumentNullException(ERROR_TOKEN_NULL);
            }

            var result = string.Format(FORMAT_PARAMETER, OAuthParameter.UrlEncode(consumer.ConsumerSecret), OAuthParameter.UrlEncode(ioAuthToken.TokenSecret));

            return(result);
        }
コード例 #10
0
        public override string BuildSignature(WebRequest webRequest, IOAuthConsumer consumer, IOAuthToken ioAuthToken)
        {
            if (consumer == null)
            {
                throw new ArgumentNullException(ERROR_CONSUMER_NULL);
            }

            if (ioAuthToken == null)
            {
                throw new ArgumentNullException(ERROR_TOKEN_NULL);
            }

            var           key           = string.Format(FORMAT_PARAMETER, OAuthParameter.UrlEncode(consumer.ConsumerSecret), OAuthParameter.UrlEncode(ioAuthToken.TokenSecret));
            HashAlgorithm hashAlgorithm = new HMACSHA1(Encoding.UTF8.GetBytes(key));
            var           encoded       = Encoding.UTF8.GetBytes(this.GetCanonicalString(webRequest, consumer, ioAuthToken));
            var           result        = Convert.ToBase64String(hashAlgorithm.ComputeHash(encoded));

            return(result);
        }
コード例 #11
0
 public string ToQueryString()
 {
     return(string.Format(QUERYSTRING_FORMAT, OAUTH_TOKEN, OAuthParameter.UrlEncode(this.TokenKey), OAUTH_TOKEN_SECRET, OAuthParameter.UrlEncode(this.TokenSecret)));
 }
コード例 #12
0
        public SSOIdentity OAuth(OAuthParameter param)
        {
            int kind = EnumToValue(param.OAuthKind);

            using (var context = base.CreateUserContext())
            {
                var q = from t in context.OpenOAuths
                        where t.OpenID == param.OpenID &&
                        t.OAuthKind == kind
                        select t;
                var  entity = q.SingleOrDefault();
                Guid userID = Guid.Empty;
                // 验证OAuth返回
                if (string.IsNullOrEmpty(param.UserName))
                {
                    if (entity == null)
                    {
                        return(null);
                    }

                    var q2 = from t in context.Accounts
                             join t2 in context.OpenOAuths on t.RowID equals t2.UserID
                             where t2.OpenID == param.OpenID && t2.OAuthKind == kind
                             select new string[] { t.UserName, t.Password };
                    var args = q2.SingleOrDefault();
                    if (args == null)
                    {
                        throw new InvalidInvokeException("用户不存在");
                    }
                    param.UserName = args[0];
                    param.Password = args[1];
                }
                else
                {
                    // 没有帐号,绑定新帐号
                    if (param.UserName == param.OpenID)
                    {
                        param.UserName = CreateNewUserName(param.OpenID, param.OAuthKind);
                        if (!context.Accounts.Any(t => t.AppID == param.AppID && t.UserName == param.UserName))
                        {
                            this.SignUp(new SignUpParameter()
                            {
                                AppID    = param.AppID,
                                UserName = param.UserName,
                                Password = param.Password
                            });
                            Thread.Sleep(200);
                        }
                        goto signIn;
                    }

                    param.Password = CryptoManaged.MD5Hex(param.Password);
                    var q2 = from t in context.Accounts
                             where t.AppID == param.AppID &&
                             t.UserName == param.UserName && t.Password == param.Password
                             select t.RowID;
                    userID = q2.SingleOrDefault();
                    if (userID == Guid.Empty)
                    {
                        throw new InvalidInvokeException("帐号或密码错误");
                    }

                    var q3 = from t in context.OpenOAuths
                             where t.UserID == userID && t.OAuthKind == kind
                             select t;
                    if (q3.Any())
                    {
                        throw new InvalidInvokeException("已经绑定过其它账户");
                    }
                }
signIn:
                var id = this.SignIn(param);
                if (entity == null)
                {
                    if (id.IsAuthenticated)
                    {
                        userID = id.UserID;
                    }
                    if (userID == Guid.Empty)
                    {
                        throw new InvalidInvokeException("UserID's null");
                    }
                    entity = new OpenOAuth();
                    EntityMapper.Map <OAuthParameter, OpenOAuth>(param, entity);
                    entity.UserID     = userID;
                    entity.CreateDate = DateTime.Now;
                    context.OpenOAuths.Add(entity);
                    context.SaveChanges();
                }
                return(id);
            }
        }
コード例 #13
0
 public QueryParameter(OAuthParameter name, string value)
     : this(name.ToStringValue(), value)
 {
 }