protected override OAuthParameters OAuthParametersFactory() { OAuthParameters oap = base.OAuthParametersFactory(); oap.put(RequestTokenService.REALM, "eWallet"); return(oap); }
public string CreateSignature(IToken token, Uri uri, string verb, string verifier = null, string callback = null) { var oAuthParameters = new OAuthParameters( new ConsumerKey(token.ConsumerKey), new TokenKey(token.TokenKey), "HMAC-SHA1", new DefaultTimestampSequence(), new DefaultNonceSequence(), string.Empty, "1.0", verifier, token.Session, false, callback); var signatureBaseString = new SignatureBaseString( new Request { Url = uri, Verb = verb }, oAuthParameters); var signature = new HmacSha1().Sign(signatureBaseString, token.ConsumerSecret, token.TokenSecret); oAuthParameters.SetSignature(signature); return(new AuthorizationHeader(oAuthParameters, string.Empty).Value); }
public void TestAEqualsB() { OAuthParameters parameters = new OAuthParameters(); parameters.AdditionalParameters.Add("a", "b"); Assert.That(parameters.ToNormalizedString(), Is.EqualTo("a=b")); }
public void TestNameParamNoValue() { OAuthParameters parameters = new OAuthParameters(); // NB: HttpRequest parses "name=" as { "name", string.Empty } parameters.AdditionalParameters.Add("name", string.Empty); Assert.That(parameters.ToNormalizedString(), Is.EqualTo("name=")); }
public void TestAEqualsXBangYAndAEqualsXSpaceY() { OAuthParameters parameters = new OAuthParameters(); parameters.AdditionalParameters.Add("a", "x!y"); parameters.AdditionalParameters.Add("a", "x y"); Assert.That(parameters.ToNormalizedString(), Is.EqualTo("a=x%20y&a=x%21y")); }
public void TestXBangYEqualsAAndXEqualsA() { OAuthParameters parameters = new OAuthParameters(); parameters.AdditionalParameters.Add("x!y", "a"); parameters.AdditionalParameters.Add("x", "a"); Assert.That(parameters.ToNormalizedString(), Is.EqualTo("x=a&x%21y=a")); }
public void TestGetHttpExampleDotComWithSlashWithNEqualsV() { OAuthParameters parameters = new OAuthParameters(); parameters.AdditionalParameters.Add("n", "v"); Assert.That( SignatureBase.Create("GET", new Uri("http://example.com/"), parameters), Is.EqualTo("GET&http%3A%2F%2Fexample.com%2F&n%3Dv")); }
/// <summary> /// Create a new request token /// </summary> /// <param name="consumer">The consumer for whom the token is to be created</param> /// <param name="parameters">The parameters that were sent in the request that /// created this token (both OAuth and additional parameters).</param> /// <returns>A request token</returns> public virtual IRequestToken CreateRequestToken(IConsumer consumer, OAuthParameters parameters) { return(new OAuthRequestToken( GuidHelper.CreateGuid().ToString("D"), GuidHelper.CreateGuid().ToString("D"), consumer, TokenStatus.Unauthorized, parameters, null, new string[] { })); }
public AuthorizeCheckoutResponse GetAuthorizeCheckoutResponse(AuthorizeCheckoutRequest request) { string response = ""; OAuthParameters param = OAuthParametersFactory(); param.addParameter(Connector.OAUTH_SIGNATURE, request.OAuthToken); Dictionary <string, string> responseMap = doRequest(getURL(), "POST", param, Serializer <AuthorizeCheckoutRequest> .Serialize(request).InnerXml); responseMap.TryGetValue(MESSAGE, out response); return(Serializer <AuthorizeCheckoutResponse> .Deserialize(response)); }
/// <summary> /// 6.2.1. Consumer Directs the User to the Service Provider /// </summary> /// <param name="parameters"></param> /// <returns></returns> public override string GetAuthorizationUrl(OAuthParameters parameters) { if (parameters.Binding == OAuthParametersBinding.QueryString) { string baseUrl = base.GetAuthorizationUrl(parameters); // return(baseUrl.Replace("oauth_consumer_key", "key").Replace("oauth_token", "token")); } return(parameters.Url); }
public ActionResult Authorize() { OAuthParameters parameters = BuildParameters(); // build the token for unauthorized requests and generate the url GetUnauthorizedRequestToken(parameters); string authorizationUrl = OAuthUtil.CreateUserAuthorizationUrl(parameters); // store the parameters temporarily and redirect to google for authorization SaveParametersTokens(parameters); Response.Redirect(authorizationUrl); return(View()); }
public ActionResult Oauth() { // retrieve and update the tokens for temporary authentication OAuthParameters parameters = BuildParameters(); OAuthUtil.UpdateOAuthParametersFromCallback(Request.Url.Query, parameters); // finally, get the token we need b@#$!!! OAuthUtil.GetAccessToken(parameters); // save those tokens into the database SaveParametersTokens(parameters); // all the success in the world, return back return(RedirectToAction("Index", "Admin")); }
/***************************************************/ /**** Public Methods ****/ /***************************************************/ public static bool AddOAuthSignature(this OAuthParameters oAuthParameters, string basestring) { //Build the signing key string signingKey = EncodeCharacters(Uri.EscapeDataString(oAuthParameters.OAuthConsumerSecret)) + "&" + EncodeCharacters(Uri.EscapeDataString(oAuthParameters.OAuthTokenSecret)); //Sign the request HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey)); oAuthParameters.OAuthSignature = System.Convert.ToBase64String( hasher.ComputeHash(new System.Text.ASCIIEncoding().GetBytes(basestring))); return(true); }
public void TestPostHttpsPhotosDotExampleDotNetSlashRequestUnderscoreTokenWithOAuthParameters() { OAuthParameters parameters = new OAuthParameters() { Version = Constants.Version1_0, ConsumerKey = "dpf43f3p2l4k3l03", Timestamp = "1191242090", Nonce = "hsu94j3884jdopsl", SignatureMethod = "PLAINTEXT", Signature = "ignored" }; Assert.That( SignatureBase.Create("POST", new Uri("https://photos.example.net/request_token"), parameters), Is.EqualTo("POST&https%3A%2F%2Fphotos.example.net%2Frequest_token&oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dhsu94j3884jdopsl%26oauth_signature_method%3DPLAINTEXT%26oauth_timestamp%3D1191242090%26oauth_version%3D1.0")); }
/// <summary> /// Echoes the query string parameters out to the screen (except /// for OAuth parameters) /// </summary> /// <param name="context">HTTP context</param> public void ProcessRequest(HttpContext context) { string separator = string.Empty; NameValueCollection parameters = OAuthParameters.GetNonOAuthParameters( context.Request.QueryString); foreach (string key in parameters.AllKeys) { foreach (string value in parameters.GetValues(key)) { context.Response.Write(separator + key + "=" + value); separator = "&"; } } }
private static string authorizationHeaderParams(OAuthParameters OAuthParameters) { StringBuilder authorizationHeaderParams = new StringBuilder(); authorizationHeaderParams.Append("OAuth "); authorizationHeaderParams.Append("oauth_nonce=" + "\"" + Uri.EscapeDataString(OAuthParameters.OAuthNonce) + "\","); authorizationHeaderParams.Append("oauth_signature_method=" + "\"" + Uri.EscapeDataString(OAuthParameters.OAuthSignatureMethod) + "\","); authorizationHeaderParams.Append("oauth_timestamp=" + "\"" + Uri.EscapeDataString(OAuthParameters.OAuthTimestamp) + "\","); authorizationHeaderParams.Append("oauth_consumer_key=" + "\"" + Uri.EscapeDataString(OAuthParameters.OAuthConsumerKey) + "\","); if (!string.IsNullOrEmpty(OAuthParameters.OAuthToken)) { authorizationHeaderParams.Append("oauth_token=" + "\"" + Uri.EscapeDataString(OAuthParameters.OAuthToken) + "\","); } authorizationHeaderParams.Append("oauth_signature=" + "\"" + Uri.EscapeDataString(OAuthParameters.OAuthSignature) + "\","); authorizationHeaderParams.Append("oauth_version=" + "\"" + Uri.EscapeDataString(OAuthParameters.OAuthVersion) + "\""); return(authorizationHeaderParams.ToString()); }
protected virtual void ParseParameters(HttpContext httpContext, OAuthRequestContext requestContext) { // Try to parse the parameters OAuthParameters parameters = OAuthParameters.Parse(httpContext.Request, ServiceProviderContext.Settings.ParameterSources); /* * Check for missing required parameters: * * The consumer key, signature method, signature, timestamp and nonce parameters * are all required */ parameters.RequireAllOf( Constants.ConsumerKeyParameter, Constants.TokenParameter, Constants.SignatureMethodParameter, Constants.SignatureParameter, Constants.TimestampParameter, Constants.NonceParameter, Constants.VerifierParameter); /* * The version parameter is optional, but it if is present its value must be 1.0 */ if (parameters.Version != null) { parameters.RequireVersion(Constants.Version1_0); } /* * Check that there are no other parameters except for realm, version and * the required parameters */ parameters.AllowOnly( Constants.ConsumerKeyParameter, Constants.TokenParameter, Constants.SignatureMethodParameter, Constants.SignatureParameter, Constants.TimestampParameter, Constants.NonceParameter, Constants.VerifierParameter, Constants.VersionParameter, // (optional) Constants.RealmParameter); // (optional) requestContext.Parameters = parameters; }
/// <summary> /// OAuth - 6.2.2. Service Provider Authenticates the User and Obtains Consent | /// ETrade - https://apisb.etrade.com/docs/api/authorization/authorize.html /// </summary> /// <param name="requestTokenInfo"></param> /// <returns></returns> protected async Task <AuthorizeResponse> AuthorizeApplicationAsync() { return(await Task.Run(() => { var parameters = new OAuthParameters() { HttpMethod = HttpMethod.Get, Url = GetServer(EServer.Authorize), Binding = OAuthParametersBinding.QueryString, Values = new Dictionary <string, string>() { { "oauth_token", Credentials.RequestToken.oauth_token } } }; using (WebDriver) { try { // login to account WebDriver.Navigate().GoToUrl(OAuthSvc.GetAuthorizationUrl(parameters)); FindDriverElement("input", name: "USER").SendKeys(Credentials.userName); FindDriverElement("input", name: "PASSWORD").SendKeys(Credentials.password); var whiteListCookie = new Cookie(Credentials.consumerCookie.Key, Credentials.consumerCookie.Value); WebDriver.Manage().Cookies.AddCookie(whiteListCookie); FindDriverElement("button", id: "logon_button").Submit(); // agree to terms FindDriverElement("input", name: "submit", value: "Accept").Submit(); // get & return the authorization code string authorizationCode = FindDriverElement("input").GetAttribute("value"); return new AuthorizeResponse() { oauth_verifier = authorizationCode }; } catch (Exception ex) { throw new Exception("AuthorizeApplicationAsync failed: ", ex); } } })); }
private OAuthResponse GetResource(NameValueCollection parameters, string contentType, System.IO.Stream bodyStream) { OAuthResponse response; HttpWebRequest request = this.PrepareProtectedResourceRequest(parameters, contentType, bodyStream); // A null value for the HttpWebRequest is returned when a ResponseToken is returned // and no one has returned in the AuthorizationHandler continue with getting an AccessToken // or an RequestToken exists but the AccessToken request was refused. if (request == null) { response = new OAuthResponse(this.RequestToken); } else { OAuthResource resource; OAuthParameters responseParameters; try { resource = new OAuthResource((HttpWebResponse)request.GetResponse()); // Parse the parameters and re-throw any OAuthRequestException from the service provider responseParameters = OAuthParameters.Parse(resource); OAuthRequestException.TryRethrow(responseParameters); // If nothing is thrown then we should have a valid resource. response = new OAuthResponse(this.AccessToken ?? this.RequestToken, resource); } catch (WebException e) { // Parse the parameters and re-throw any OAuthRequestException from the service provider responseParameters = OAuthParameters.Parse(e.Response as HttpWebResponse); OAuthRequestException.TryRethrow(responseParameters); // If no OAuthRequestException, rethrow the WebException #warning TODO: We have consumer the WebException's body so rethrowing it is pretty pointless; wrap the WebException in an OAuthProtocolException and store the body (create an OAuthResource before parsing parameters) throw; } } return(response); }
public void Test_FunnyCharacters() { OAuthParameters parameters = new OAuthParameters() { ConsumerKey = "weitu.googlepages.com", Nonce = "face868c-04a9-4e75-9534-0b58616c351c", SignatureMethod = "RSA-SHA1", Timestamp = "1213351382", Token = "1/rTf4q3P05rP2xv2xP1ls8mATiaQZnWPB51nTvo8n9Sw", Version = "1.0" }; string basesig = SignatureBase.Create( "GET", new Uri("http://www.google.com/m8/feeds/contacts/default/base"), parameters); Assert.That(basesig, Is.EqualTo("GET&http%3A%2F%2Fwww.google.com%2Fm8%2Ffeeds%2Fcontacts%2Fdefault%2Fbase&oauth_consumer_key%3Dweitu.googlepages.com%26oauth_nonce%3Dface868c-04a9-4e75-9534-0b58616c351c%26oauth_signature_method%3DRSA-SHA1%26oauth_timestamp%3D1213351382%26oauth_token%3D1%252FrTf4q3P05rP2xv2xP1ls8mATiaQZnWPB51nTvo8n9Sw%26oauth_version%3D1.0")); }
protected virtual void ParseParameters(HttpApplication application, OAuthRequestContext context) { // Try to parse the parameters OAuthParameters parameters = OAuthParameters.Parse(application.Request); /* * Check for missing required parameters: * * The consumer key, token, signature method, signature, timestamp and nonce parameters * are all required */ if (ServiceProviderContext.Settings.AllowConsumerRequests) { parameters.RequireAllOf( Constants.ConsumerKeyParameter, Constants.SignatureMethodParameter, Constants.SignatureParameter, Constants.TimestampParameter, Constants.NonceParameter); } else { // For 3 legged TokenParameter is required parameters.RequireAllOf( Constants.ConsumerKeyParameter, Constants.TokenParameter, Constants.SignatureMethodParameter, Constants.SignatureParameter, Constants.TimestampParameter, Constants.NonceParameter); } /* * The version parameter is optional, but it if is present its value must be 1.0 */ if (parameters.Version != null) { parameters.RequireVersion(Constants.Version1_0); } context.Parameters = parameters; }
public void TestGetHttpPhotosDotExampleDotNetSlashPhotosWithOAuthParametersAndFileEqualsVacationDotJpgAndSizeEqualsOriginal() { OAuthParameters parameters = new OAuthParameters() { Version = Constants.Version1_0, ConsumerKey = "dpf43f3p2l4k3l03", Token = "nnch734d00sl2jdk", Timestamp = "1191242096", Nonce = "kllo9940pd9333jh", SignatureMethod = "HMAC-SHA1", Signature = "ignored" }; parameters.AdditionalParameters.Add("file", "vacation.jpg"); parameters.AdditionalParameters.Add("size", "original"); Assert.That( SignatureBase.Create("GET", new Uri("http://photos.example.net/photos"), parameters), Is.EqualTo("GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dkllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1191242096%26oauth_token%3Dnnch734d00sl2jdk%26oauth_version%3D1.0%26size%3Doriginal")); }
protected virtual void SignParameters(Uri requestUri, string httpMethod, OAuthParameters authParameters, IToken token) { // Check there is a signing provider for the signature method ISigningProvider signingProvider = this.Service.ComponentLocator.GetInstance <ISigningProvider>(Constants.SigningProviderIdPrefix + this.Service.SignatureMethod); if (signingProvider == null) { // There is no signing provider for this signature method OAuthRequestException.ThrowSignatureMethodRejected(null); } // Double check the signing provider declares that it can handle the signature method if (!signingProvider.SignatureMethod.Equals(this.Service.SignatureMethod)) { OAuthRequestException.ThrowSignatureMethodRejected(null); } // Compute the signature authParameters.Sign(requestUri, httpMethod, this.Service.Consumer, token, signingProvider); }
private bool SaveParametersTokens(OAuthParameters parameters) { try { // first delete any old ones var oldTokens = (from t in context.GO_GoogleAuthorizeTokens select t); context.GO_GoogleAuthorizeTokens.DeleteAllOnSubmit(oldTokens); context.SubmitChanges(); // now create a new one GO_GoogleAuthorizeToken newToken = new GO_GoogleAuthorizeToken { Token = parameters.Token, TokenSecret = parameters.TokenSecret }; context.GO_GoogleAuthorizeTokens.InsertOnSubmit(newToken); context.SubmitChanges(); } catch { return(false); } return(true); }
private OAuthParameters CreateOAuthParameters(NameValueCollection additionalParameters) { int timestamp = UnixTime.ToUnixTime(DateTime.Now); OAuthParameters authParameters = new OAuthParameters() { ConsumerKey = this.Service.Consumer.Key, Realm = this.Service.Realm, SignatureMethod = this.Service.SignatureMethod, Timestamp = timestamp.ToString(CultureInfo.InvariantCulture), Nonce = this.Service.ComponentLocator.GetInstance <INonceProvider>().GenerateNonce(timestamp), Version = this.Service.OAuthVersion }; if (additionalParameters != null && additionalParameters.Count > 0) { authParameters.AdditionalParameters.Add(additionalParameters); } return(authParameters); }
protected virtual HttpWebRequest DoPrepareProtectedResourceRequest(NameValueCollection parameters, string contentType, System.IO.Stream bodyStream) { // Fire the OnBeforeGetProtectedResource event PreProtectedResourceRequestEventArgs preArgs = new PreProtectedResourceRequestEventArgs( this.ResourceUri, this.ResourceEndPoint.HttpMethod, parameters ?? new NameValueCollection(), this.RequestToken, this.AccessToken); if (this.OnBeforeGetProtectedResource != null) { this.OnBeforeGetProtectedResource(this, preArgs); } OAuthParameters authParams = this.CreateOAuthParameters(preArgs.AdditionalParameters); this.SignParameters(preArgs.RequestUri, preArgs.HttpMethod, authParams, this.AccessToken); return(this.CreateRequest(preArgs.RequestUri, authParams, preArgs.HttpMethod, contentType, bodyStream)); }
public Fixture Then_we_can_connect() { var oAuthParameters = new OAuthParameters( _consumer.ConsumerKey, new TokenKey(_consumer.ConsumerKey.Value), "RSA-SHA1", new DefaultTimestampSequence(), new DefaultNonceSequence(), string.Empty, "1.0" ); var earl = new Uri("https://api.xero.com/api.xro/2.0/Organisation"); var signatureBaseString = new SignatureBaseString( new Request { Url = earl, Verb = "GET" }, oAuthParameters ); var signature = new RsaSha1(_cert).Sign(signatureBaseString); oAuthParameters.SetSignature(signature); var header = new AuthorizationHeader(oAuthParameters, string.Empty); var req = (HttpWebRequest)WebRequest.Create(earl); req.Headers.Add("Authorization", header.Value); var response = TInternet.Get(req); const HttpStatusCode expected = HttpStatusCode.OK; var actual = response.StatusCode; return(new YesNoFixture(actual == expected, "Expected [" + expected + "]. Got [" + actual + "]. And here is the body: " + response.Body, 2)); }
public void TestConsumerRequestSignature() { OAuthService service = OAuthService.Create( new EndPoint("http://example.com/request_token"), new Uri("http://example.com/authorize"), new EndPoint("http://example.com/access_token"), new MockConsumer() { Key = "dpf43f3p2l4k3l03", Secret = "kd94hf93k423kf44", Status = ConsumerStatus.Valid }); OAuthRequest consumerRequest = OAuthConsumerRequest.Create( new EndPoint("http://provider.example.net/profile", "GET"), service); OAuthParameters authParameters = new OAuthParameters() { ConsumerKey = service.Consumer.Key, Realm = service.Realm, SignatureMethod = service.SignatureMethod, Timestamp = "1191242096", Nonce = "kllo9940pd9333jh", Version = service.OAuthVersion }; Assert.AreEqual( SignatureBase.Create(consumerRequest.ResourceEndPoint.HttpMethod, consumerRequest.ResourceEndPoint.Uri, authParameters), "GET&http%3A%2F%2Fprovider.example.net%2Fprofile&oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dkllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1191242096%26oauth_version%3D1.0"); authParameters.Sign(consumerRequest.ResourceEndPoint.Uri, consumerRequest.ResourceEndPoint.HttpMethod, service.Consumer, consumerRequest.RequestToken, new OAuth.Net.Components.HmacSha1SigningProvider()); Assert.AreEqual(authParameters.Signature, "SGtGiOrgTGF5Dd4RUMguopweOSU="); }
public OAuthRequestToken( string token, string secret, IConsumer consumer, TokenStatus status, OAuthParameters associatedParameters, IIdentity authenticatedUser, string[] roles) : this() { if (string.IsNullOrEmpty(token)) { throw new ArgumentException("token must not be null or empty", "token"); } if (secret == null) { throw new ArgumentNullException("secret", "secret must not be null"); } if (consumer == null) { throw new ArgumentNullException("consumer", "consumer must not be null"); } if (roles == null) { throw new ArgumentNullException("roles", "roles must not be null"); } this.Token = token; this.Secret = secret; this.Status = status; this.ConsumerKey = consumer.Key; this.AssociatedParameters = associatedParameters; this.AuthenticatedUser = authenticatedUser; this.Roles = roles; }
//TODO: No anda todavia!! private HttpWebResponse GetContacts() { yahooAccessToken = (string[])HttpContext.Current.Session["Yahoo_AccessToken"]; Uri RequestContactBaseUri = new Uri("http://social.yahooapis.com/v1/user/" + YGuid + "/contacts"); int timestamp = Common.GetTimestamp(); OAuthParameters parameters = new OAuthParameters(); parameters.ConsumerKey = apiKey; parameters.Nonce = new GuidNonceProvider().GenerateNonce(timestamp); parameters.SignatureMethod = "HMAC-SHA1"; parameters.Timestamp = timestamp.ToString(CultureInfo.InvariantCulture); parameters.Token = Rfc3986.Decode(AccessToken); parameters.Version = "1.0"; parameters.AdditionalParameters.Add("format", "xml"); string sigBase = SignatureBase.Create("GET", RequestContactBaseUri, parameters); HmacSha1SigningProvider singProvier = new HmacSha1SigningProvider(); parameters.Signature = singProvier.ComputeSignature( sigBase, (secret), Rfc3986.Encode(AccessTokenSecret)); HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://social.yahooapis.com/v1/user/" + YGuid + "/contacts?view=tinyusercard"); request.CookieContainer = new CookieContainer(); request.Headers["WWW-Authenticate"] = " OAuth realm='yahooapis.com',"; request.Headers["WWW-Authenticate"] += " oauth_consumer_key='" + parameters.ConsumerKey + "',"; request.Headers["WWW-Authenticate"] += " oauth_nonce='" + parameters.Nonce + "',"; request.Headers["WWW-Authenticate"] += " oauth_signature_method='" + parameters.SignatureMethod + "',"; request.Headers["WWW-Authenticate"] += " oauth_timestamp='" + parameters.Timestamp + "',"; request.Headers["WWW-Authenticate"] += " oauth_token='" + token + "',"; request.Headers["WWW-Authenticate"] += " oauth_version='" + parameters.Version + "',"; request.Headers["WWW-Authenticate"] += " oauth_signature='" + parameters.Signature + "'"; request.Method = "GET"; request.ContentType = "application/xml; charset=utf-8"; return((HttpWebResponse)request.GetResponse()); }