/// <summary> /// Used to Check if the API key is valid or not. /// </summary> /// <param name="consumerkey"></param> /// <param name="consumersecret"></param> /// <returns></returns> public static string CMS_Auditor(String consumerkey, String consumersecret) { try { var requestEndPoint = new Uri("https://vulndb.cyberriskanalytics.com/oauth/request_token"); var authorizeEndPoint = new Uri("https://vulndb.cyberriskanalytics.com/oauth/authorize"); var accessEndPoint = new Uri("https://vulndb.cyberriskanalytics.com/oauth/access_token"); var ctx = new OAuthConsumerContext { ConsumerKey = consumerkey, ConsumerSecret = consumersecret, SignatureMethod = SignatureMethod.HmacSha1 }; var genericSession = new OAuthSession(ctx, requestEndPoint, authorizeEndPoint, accessEndPoint); var targetServiceUri = new Uri("https://vulndb.cyberriskanalytics.com/api/v1/vulnerabilities/search_query?utf8=✓&query=teamviewer"); var respText = genericSession.Request().Get().ForUri(targetServiceUri).ToString(); return respText; } catch (WebException ex) { using (var stream = ex.Response.GetResponseStream()) using (var reader = new StreamReader(stream)) { Console.WriteLine(reader.ReadToEnd()); return "Please Check your API Key and Secret"; } } }
public TradeMeToken AuthenticateWithVerifier(PreliminaryToken preliminaryToken, string oAuthVerifierOrPin) { if (string.IsNullOrEmpty(oAuthVerifierOrPin)) { throw new Exception(); } oAuthVerifierOrPin = oAuthVerifierOrPin.Trim(); var consumerContext = new OAuthConsumerContext { ConsumerKey = _appKeys.ConsumerKey, ConsumerSecret = _appKeys.ConsumerSecret, SignatureMethod = SignatureMethod.HmacSha1, UseHeaderForOAuthParameters = true }; var session = new OAuthSession( consumerContext, Profile.Current.RequestTokenUrl + "?scope=" + _appKeys.ScopeOfRequest, Profile.Current.AuthorizeUrl, Profile.Current.AccessUrl); return new TradeMeToken(session.ExchangeRequestTokenForAccessToken(preliminaryToken.Token, oAuthVerifierOrPin)); }
public void GoogleConsumer() { X509Certificate2 certificate = TestCertificates.OAuthTestCertificate(); string requestUrl = "https://www.google.com/accounts/OAuthGetRequestToken"; string userAuthorizeUrl = "https://www.google.com/accounts/accounts/OAuthAuthorizeToken"; string accessUrl = "https://www.google.com/accounts/OAuthGetAccessToken"; string callBackUrl = "http://www.mysite.com/callback"; var consumerContext = new OAuthConsumerContext { ConsumerKey = "weitu.googlepages.com", SignatureMethod = SignatureMethod.RsaSha1, Key = certificate.PrivateKey }; var session = new OAuthSession(consumerContext, requestUrl, userAuthorizeUrl, accessUrl) .WithQueryParameters(new { scope = "http://www.google.com/m8/feeds" }); // get a request token from the provider IToken requestToken = session.GetRequestToken(); // generate a user authorize url for this token (which you can use in a redirect from the current site) string authorizationLink = session.GetUserAuthorizationUrlForToken(requestToken, callBackUrl); // exchange a request token for an access token IToken accessToken = session.ExchangeRequestTokenForAccessToken(requestToken); // make a request for a protected resource string responseText = session.Request().Get().ForUrl("http://www.google.com/m8/feeds/contacts/default/base").ToString(); }
public PreliminaryToken GetOAuthVerifier(Uri callback) { var consumerContext = new OAuthConsumerContext { ConsumerKey = _appKeys.ConsumerKey, ConsumerSecret = _appKeys.ConsumerSecret, SignatureMethod = SignatureMethod.HmacSha1, UseHeaderForOAuthParameters = true }; var session = new OAuthSession( consumerContext, Profile.Current.RequestTokenUrl + "?scope=" + _appKeys.ScopeOfRequest, Profile.Current.AuthorizeUrl, Profile.Current.AccessUrl); if (callback != null) { session.CallbackUri = callback; } var requestToken = session.GetRequestToken(); return new PreliminaryToken { AuthUrl = new Uri(session.GetUserAuthorizationUrlForToken(requestToken)), Token = requestToken }; }
// helper extension method to sign each JSON request with OAuth public static void SetAccessToken(this JsonServiceClient client, IToken access_token) { // we use a request filter to add the required OAuth header client.LocalHttpWebRequestFilter += webservice_request => { OAuthConsumerContext consumer_context = new OAuthConsumerContext (); consumer_context.SignatureMethod = "HMAC-SHA1"; consumer_context.ConsumerKey = access_token.ConsumerKey; consumer_context.ConsumerSecret = "anyone"; consumer_context.UseHeaderForOAuthParameters = true; // the OAuth process creates a signature, which uses several data from // the web request like method, hostname, headers etc. OAuthContext request_context = new OAuthContext (); request_context.Headers = webservice_request.Headers; request_context.RequestMethod = webservice_request.Method; request_context.RawUri = webservice_request.RequestUri; // now create the signature for that context consumer_context.SignContextWithToken (request_context, access_token); // BUG TODO the oauth_token is not included when generating the header, // this is a bug ing DevDefined.OAuth. We add it manually as a workaround request_context.AuthorizationHeaderParameters.Add ("oauth_token", access_token.Token); string oauth_header = request_context.GenerateOAuthParametersForHeader (); webservice_request.Headers.Add ("Authorization", oauth_header); }; }
/// <summary> /// Note: Default urls are taken from the developer documentation. Override if necessary. /// </summary> /// <param name="consumerKey"></param> /// <param name="consumerSecret"></param> /// <param name="intuitQboApiUrl"></param> /// <param name="intuitOauthUrl"></param> /// <param name="intuitRequestTokenUrl"></param> /// <param name="intuitAccessTokenUrl"></param> /// <param name="intuitUserAuthorizationUrl"></param> public OauthTokenManager(string consumerKey, string consumerSecret, string intuitQboApiUrl, string intuitOauthUrl = "https://oauth.intuit.com/oauth/v1", string intuitRequestTokenUrl = "https://oauth.intuit.com/oauth/v1/get_request_token", string intuitAccessTokenUrl = "https://oauth.intuit.com/oauth/v1/get_access_token", string intuitUserAuthorizationUrl = "https://appcenter.intuit.com/Connect/Begin") { if (string.IsNullOrEmpty(consumerKey)) { throw new InvalidParameterException("Oops. ConsumerKey is required."); } if (string.IsNullOrEmpty(consumerSecret)) { throw new InvalidParameterException("Oops. ConsumerSecret is required."); } if (string.IsNullOrEmpty(intuitQboApiUrl)) { throw new InvalidParameterException("Oops. API Url is required."); } _intuitUserAuthorizationUrl = intuitUserAuthorizationUrl; OauthInfo = new QboOauthConnectionInfo { ApiUrl = intuitQboApiUrl, ConsumerKey = consumerKey, ConsumerSecret = consumerSecret }; var consumerContext = new OAuthConsumerContext { ConsumerKey = OauthInfo.ConsumerKey, ConsumerSecret = OauthInfo.ConsumerSecret, SignatureMethod = SignatureMethod.HmacSha1 }; _authSession = new OAuthSession(consumerContext, intuitRequestTokenUrl, intuitOauthUrl, intuitAccessTokenUrl); }
/// <summary> /// Creates the new OAuth session as well as getting the AccessToken for that Session. /// Here instead of getting the Access Token by exchanging RequestTokens, we are able to just pull it from storage /// </summary> /// <param name="currentBusinessAccount">The current business account.</param> /// <returns> /// Oath Session with the AccessToken held within it /// </returns> public static OAuthSession CreateOAuthSessionAndAccessToken(BusinessAccount currentBusinessAccount) { //Generates the consumer context based on the constants for our IntuitAnywhere App //In this case the Consumer is actually FoundOps var consumerContext = new OAuthConsumerContext { ConsumerKey = OauthConstants.ConsumerKey, SignatureMethod = SignatureMethod.HmacSha1, ConsumerSecret = OauthConstants.ConsumerSecret }; //Generates the OAuth session based on the constants for our IntuitAnywhere App and the ConsumerContext created above OAuthSession oSession = new OAuthSession(consumerContext, OauthConstants.IdFedOAuthBaseUrl + OauthConstants.UrlRequestToken, OauthConstants.AuthorizeUrl, OauthConstants.IdFedOAuthBaseUrl + OauthConstants.UrlAccessToken); oSession.ConsumerContext.UseHeaderForOAuthParameters = true; //Access Token is generated from storage here and saved into the OauthSession oSession.AccessToken = new TokenBase { Token = currentBusinessAccount.QuickBooksAccessToken, ConsumerKey = OauthConstants.ConsumerKey, TokenSecret = currentBusinessAccount.QuickBooksAccessTokenSecret }; return oSession; }
public IOAuthSession CreatePrivateConsumerSession() { // Load the private certificate from disk using the password used to create it var privateCertificate = string.IsNullOrEmpty(_privateKeyPassword) ? new X509Certificate2(_privateKeyFile) : new X509Certificate2(_privateKeyFile, _privateKeyPassword); // Create the consumer session var consumerContext = new OAuthConsumerContext { ConsumerKey = _privateConsumerKey, ConsumerSecret = _privateConsumerSecret, SignatureMethod = SignatureMethod.RsaSha1, UseHeaderForOAuthParameters = true, Key = privateCertificate.PrivateKey, UserAgent = _privateUserAgentString }; return new OAuthSession( consumerContext, "https://api.xero.com/oauth/RequestToken", "https://api.xero.com/oauth/Authorize", "https://api.xero.com/oauth/AccessToken"); }
/// <summary> /// Checks a single entry agasint vulnDB Search API. /// </summary> /// <param name="consumerkey"></param> /// <param name="consumersecret"></param> /// <param name="Application"></param> /// <returns></returns> public static string vulndb_appCheck(String consumerkey, String consumersecret, String Application) { try { var requestEndPoint = new Uri("https://vulndb.cyberriskanalytics.com/oauth/request_token"); var authorizeEndPoint = new Uri("https://vulndb.cyberriskanalytics.com/oauth/authorize"); var accessEndPoint = new Uri("https://vulndb.cyberriskanalytics.com/oauth/access_token"); var ctx = new OAuthConsumerContext { ConsumerKey = consumerkey, ConsumerSecret = consumersecret, SignatureMethod = SignatureMethod.HmacSha1 }; var genericSession = new OAuthSession(ctx, requestEndPoint, authorizeEndPoint, accessEndPoint); var targetServiceUri = new Uri("https://vulndb.cyberriskanalytics.com/api/v1/vulnerabilities/search_query?query=\"" + Application.ToString() +"\""); var respText = genericSession.Request().Get().ForUri(targetServiceUri).ToString(); return respText; } catch (WebException ex) { using (var stream = ex.Response.GetResponseStream()) using (var reader = new StreamReader(stream)) { Console.WriteLine(reader.ReadToEnd()); return "Nothing Found for: " + Application.ToString(); } } }
/// <summary> /// Creates a HttpRequest with oAuthSession (OAuth Token) and gets the response with invalidating user /// from QuickBooks for this app /// For Authorization: The request header must include the OAuth parameters defined by OAuth Core 1.0 Revision A. /// /// If the disconnect is successful, then the HTTP status code is 200 and /// the XML response includes the <ErrorCode> element with a 0 value. /// If an HTTP error is detected, then the HTTP status code is not 200. /// If an HTTP error is not detected but the disconnect is unsuccessful, /// then the HTTP status code is 200 and the response XML includes the <ErrorCode> element with a non-zero value. /// For example, if the OAuth access token expires or is invalid for some other reason, then the value of <ErrorCode> is 270. /// </summary> /// <param name="sender">Sender of the event.</param> /// <param name="e">Event args.</param> protected void Page_Load(object sender, EventArgs e) { OAuthConsumerContext consumerContext = new OAuthConsumerContext { ConsumerKey = ConfigurationManager.AppSettings["consumerKey"].ToString(), SignatureMethod = SignatureMethod.HmacSha1, ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"].ToString() }; OAuthSession oSession = new OAuthSession(consumerContext, Constants.OauthEndPoints.IdFedOAuthBaseUrl + Constants.OauthEndPoints.UrlRequestToken, Constants.OauthEndPoints.AuthorizeUrl, Constants.OauthEndPoints.IdFedOAuthBaseUrl + Constants.OauthEndPoints.UrlAccessToken); oSession.ConsumerContext.UseHeaderForOAuthParameters = true; if ((Session["accessToken"] + "").Length > 0) { oSession.AccessToken = new TokenBase { Token = HttpContext.Current.Session["accessToken"].ToString(), ConsumerKey = ConfigurationManager.AppSettings["consumerKey"].ToString(), TokenSecret = HttpContext.Current.Session["accessTokenSecret"].ToString() }; IConsumerRequest conReq = oSession.Request(); conReq = conReq.Get(); conReq = conReq.ForUrl(Constants.PlatformApiEndpoints.DisconnectUrl); try { conReq = conReq.SignWithToken(); } catch (Exception ex) { throw ex; } //Used just see the what header contains string header = conReq.Context.GenerateOAuthParametersForHeader(); //This method will clean up the OAuth Token txtServiceResponse = conReq.ReadBody(); //Reset All the Session Variables HttpContext.Current.Session.Remove("oauthToken"); // Add the invalid access token into session for the display of the Disconnect btn HttpContext.Current.Session["InvalidAccessToken"] = HttpContext.Current.Session["accessToken"]; // Dont remove the access token since this is required for Reconnect btn in the Blue dot menu // HttpContext.Current.Session.Remove("accessToken"); // Dont Remove flag since we need to display the blue dot menu for Reconnect btn in the Blue dot menu // HttpContext.Current.Session.Remove("Flag"); DisconnectFlg = "User is Disconnected from QuickBooks!"; //Remove the Oauth access token from the OauthAccessTokenStorage.xml OauthAccessTokenStorageHelper.RemoveInvalidOauthAccessToken(Session["FriendlyEmail"].ToString(), Page); } }
private OAuthSession GetOAuthSession(String key, String secret) { OAuthConsumerContext consumerContext = new OAuthConsumerContext(); consumerContext.ConsumerKey = key; consumerContext.ConsumerSecret = secret; consumerContext.SignatureMethod = SignatureMethod.HmacSha1; return (new OAuthSession(consumerContext, Chpp.RequestTokenURL, Chpp.AuthorizeURL, Chpp.AccessTokenURL)); }
public void GetRequestTokenForConsumerWithoutCallbackUrl() { var consumerContext = new OAuthConsumerContext {ConsumerKey = "key"}; var session = new OAuthSession(consumerContext, "http://localhost/request", "http://localhost/userauth", "http://localhost/access"); RequestDescription description = session.BuildRequestTokenContext("POST").GetRequestDescription(); Assert.True(description.Body.Contains("oauth_callback=oob")); }
/// <summary> /// Creates a HttpRequest with oAuthSession (OAuth Token) and gets the response with invalidating user /// from QuickBooks for this app /// For Authorization: The request header must include the OAuth parameters defined by OAuth Core 1.0 Revision A. /// /// If the disconnect is successful, then the HTTP status code is 200 and /// the XML response includes the <ErrorCode> element with a 0 value. /// If an HTTP error is detected, then the HTTP status code is not 200. /// If an HTTP error is not detected but the disconnect is unsuccessful, /// then the HTTP status code is 200 and the response XML includes the <ErrorCode> element with a non-zero value. /// For example, if the OAuth access token expires or is invalid for some other reason, then the value of <ErrorCode> is 270. /// </summary> // // GET: /CleanUpOnDisconnect/ public ActionResult Disconnect() { OAuthConsumerContext consumerContext = new OAuthConsumerContext { ConsumerKey = ApplicationUserAppValues.ConsumerKey, SignatureMethod = SignatureMethod.HmacSha1, ConsumerSecret = ApplicationUserAppValues.ConsumerSecret }; OAuthSession oSession = new OAuthSession(consumerContext, Constants.OauthEndPoints.IdFedOAuthBaseUrl + Constants.OauthEndPoints.UrlRequestToken, Constants.OauthEndPoints.AuthorizeUrl, Constants.OauthEndPoints.IdFedOAuthBaseUrl + Constants.OauthEndPoints.UrlAccessToken); oSession.ConsumerContext.UseHeaderForOAuthParameters = true; if ((SessionWrapper.accessToken + "").Length > 0) { oSession.AccessToken = new TokenBase { Token = SessionWrapper.accessToken, ConsumerKey = ApplicationUserAppValues.ConsumerKey, TokenSecret = SessionWrapper.accessTokenSecret }; IConsumerRequest conReq = oSession.Request(); conReq = conReq.Get(); conReq = conReq.ForUrl(Constants.IaEndPoints.DisconnectUrl); try { conReq = conReq.SignWithToken(); } catch (Exception ex) { throw ex; } //Used just see the what header contains string header = conReq.Context.GenerateOAuthParametersForHeader(); //This method will clean up the OAuth Token GlobalVariablesWrapper.TxtServiceResponse = conReq.ReadBody(); // Add the invalid access token into session for the display of the Disconnect btn SessionWrapper.InvalidAccessToken = SessionWrapper.accessToken; // Dont remove the access token since this is required for Reconnect btn in the Blue dot menu // HttpContext.Current.Session.Remove("accessToken"); // Dont Remove flag since we need to display the blue dot menu for Reconnect btn in the Blue dot menu // HttpContext.Current.Session.Remove("Flag"); GlobalVariablesWrapper.DisconnectFlg = "User is Disconnected from QuickBooks!"; } return View("Disconnect"); }
private static IOAuthSession CreateOAuthSession() { var consumerContext = new OAuthConsumerContext { ConsumerKey = ApiKey, ConsumerSecret = ApiSecret, Realm = "", SignatureMethod = "HMAC-SHA1", UseHeaderForOAuthParameters = true }; return new OAuthSession(consumerContext, RequestTokenURL, NoBrowserAuthorizationURL, AccessTokenURL); }
/// <summary> /// Creates Session /// </summary> /// <returns>Returns OAuth Session</returns> protected IOAuthSession CreateSession() { OAuthConsumerContext consumerContext = new OAuthConsumerContext { ConsumerKey = consumerKey, ConsumerSecret = consumerSecret, SignatureMethod = SignatureMethod.HmacSha1 }; return new OAuthSession(consumerContext, Constants.OauthEndPoints.IdFedOAuthBaseUrl + Constants.OauthEndPoints.UrlRequestToken, oauthLink, Constants.OauthEndPoints.IdFedOAuthBaseUrl + Constants.OauthEndPoints.UrlAccessToken); }
public void GetRequestTokenForMethodGetDoesNotPopulateBody() { var consumerContext = new OAuthConsumerContext {ConsumerKey = "key"}; var session = new OAuthSession(consumerContext, "http://localhost/request", "http://localhost/userauth", "http://localhost/access"); RequestDescription description = session.BuildRequestTokenContext("GET").GetRequestDescription(); Assert.Null(description.Body); Assert.Null(description.ContentType); Assert.Equal("GET", description.Method); }
/// <summary> /// Creates Session /// </summary> /// <returns>Returns OAuth Session</returns> private static IOAuthSession CreateSession(String oauth_callback_url, String oauthLink) { OAuthConsumerContext consumerContext = new OAuthConsumerContext { ConsumerKey = ApplicationUserAppValues.ConsumerKey, ConsumerSecret = ApplicationUserAppValues.ConsumerSecret, SignatureMethod = SignatureMethod.HmacSha1 }; return new OAuthSession(consumerContext, Constants.OauthEndPoints.IdFedOAuthBaseUrl + Constants.OauthEndPoints.UrlRequestToken, oauthLink, Constants.OauthEndPoints.IdFedOAuthBaseUrl + Constants.OauthEndPoints.UrlAccessToken); }
private void CreateSession() { X509Certificate2 certificate = TestCertificates.OAuthTestCertificate(); var consumerContext = new OAuthConsumerContext { SignatureMethod = SignatureMethod.HmacSha1, ConsumerKey = consumerKey, ConsumerSecret = consumerSecret, UseHeaderForOAuthParameters = false, }; this.context = consumerContext; this.session = new OAuthSession(this.context, requestUrl, userAuthorizeUrl, accessUrl); }
private static void Main() { string requestUrl = "https://apis.daum.net/oauth/requestToken"; string userAuthorizeUrl = "https://apis.daum.net/oauth/authorize"; string accessUrl = "https://apis.daum.net/oauth/accessToken"; string callbackUrl = "oob"; var consumerContext = new OAuthConsumerContext { //TODO:Daum OAuth소개 페이지(https://apis.daum.net/oauth/consumer/list)에서 등록된 Consumer 정보 입력 ConsumerKey = "eb3eff10-b95d-455c-8572-e7858a2b34d0", ConsumerSecret = "suz6.HUjzlaG-S9ezBzFQ11FtKhQvv8cdT-9C_hWBFthpUmMTsOuUA00", SignatureMethod = SignatureMethod.HmacSha1, }; //OAuth 준비 var session = new OAuthSession(consumerContext, requestUrl, userAuthorizeUrl, accessUrl); session.WithQueryParameters(new Dictionary<string,string>(){ { "oauth_callback", callbackUrl } }); // 1. request token 받기 DevDefined.OAuth.Framework.IToken requestToken = session.GetRequestToken(); // 인증주소 받기 string authorizationLink = session.GetUserAuthorizationUrlForToken(requestToken, callbackUrl); // 2. 사용자 인증 하기 System.Console.WriteLine("웹브라우저를 실행하여 다음 URL을 접속하세요."); System.Console.WriteLine(authorizationLink); System.Console.Write("\n\n웹브라우저에서 인증 후 반환 된 값을 입력하세요:"); string inputVerifier = System.Console.ReadLine(); // 얻어진 Verifier값을 포함시키기 session.WithQueryParameters(new Dictionary<string, string>() { { "oauth_verifier", inputVerifier } }); // 3. 인증 후 얻은 Verifier값을 이용하여 엑세스 토큰 얻기 DevDefined.OAuth.Framework.IToken accessToken = session.ExchangeRequestTokenForAccessToken(requestToken); // '게시글 쓰기(한줄메모장)' API를 호출 System.Console.WriteLine("OAuth를 통한 인증으로 '게시글 쓰기(한줄메모장)'를 호출하고 XML로 응답 받는 테스트를 합니다."); string apiUrl = "http://apis.daum.net/cafe/write_article/{cafeCode}/{boardId}.xml?"; //{cafeCode} - 카페코드 : //{boardId} apiUrl += string.Format("content={0}&", "여기는 메모를 삽입합니다."); apiUrl += string.Format("hideyn={0}&", "N"); //비밀글일때 Y string responseText = session.Request().Get().ForUrl(apiUrl).ToString(); System.Console.WriteLine(responseText); System.Console.ReadLine(); }
/// <summary> /// Creates the OAuth Session using Consumer key /// </summary> /// <returns>OAuth Session.</returns> private static IOAuthSession CreateSession() { OAuthConsumerContext consumerContext = new OAuthConsumerContext { ConsumerKey = ApplicationUserAppValues.ConsumerKey.ToString(CultureInfo.InvariantCulture), ConsumerSecret = ApplicationUserAppValues.ConsumerSecret.ToString(CultureInfo.InvariantCulture), SignatureMethod = SignatureMethod.HmacSha1 }; return new OAuthSession(consumerContext, Constants.OauthEndPoints.IdFedOAuthBaseUrl + Constants.OauthEndPoints.UrlRequestToken, Constants.OauthEndPoints.IdFedOAuthBaseUrl, Constants.OauthEndPoints.IdFedOAuthBaseUrl + Constants.OauthEndPoints.UrlAccessToken); }
IOAuthSession CreateGoogleContactsSession() { var consumerContext = new OAuthConsumerContext { ConsumerKey = "weitu.googlepages.com", SignatureMethod = SignatureMethod.RsaSha1, Key = certificate.PrivateKey }; return new OAuthSession(consumerContext, "https://www.google.com/accounts/OAuthGetRequestToken", "https://www.google.com/accounts/OAuthAuthorizeToken", "https://www.google.com/accounts/OAuthGetAccessToken ") .WithQueryParameters(new {scope = "https://www.google.com/m8/feeds"}) .RequiresCallbackConfirmation(); }
private IOAuthSession createDevDefinedOAuthSession(string consumerKey, string consumerSecret) { var oauthRequestTokenUrl = ConfigurationSettings.AppSettings["oauthBaseUrl"] + ConfigurationSettings.AppSettings["oauthRequestTokenEndpoint"]; var oauthAccessTokenUrl = ConfigurationSettings.AppSettings["oauthBaseUrl"] + ConfigurationSettings.AppSettings["oauthAccessTokenEndpoint"]; var oauthUserAuthorizeUrl = ConfigurationSettings.AppSettings["oauthUserAuthUrl"]; OAuthConsumerContext consumerContext = new OAuthConsumerContext { ConsumerKey = consumerKey, ConsumerSecret = consumerSecret, SignatureMethod = SignatureMethod.HmacSha1 }; return new OAuthSession(consumerContext, oauthRequestTokenUrl, oauthUserAuthorizeUrl, oauthAccessTokenUrl); }
private IOAuthSession createDevDefinedOAuthSession(string consumerKey, string consumerSecret) { var oauthRequestTokenUrl = Constants.OauthEndPoints.IdFedOAuthBaseUrl + Constants.OauthEndPoints.UrlRequestToken; var oauthAccessTokenUrl = Constants.OauthEndPoints.IdFedOAuthBaseUrl + Constants.OauthEndPoints.UrlAccessToken; var oauthUserAuthorizeUrl = Constants.OauthEndPoints.AuthorizeUrl; OAuthConsumerContext consumerContext = new OAuthConsumerContext { ConsumerKey = consumerKey, ConsumerSecret = consumerSecret, SignatureMethod = SignatureMethod.HmacSha1 }; return new OAuthSession(consumerContext, oauthRequestTokenUrl, oauthUserAuthorizeUrl, oauthAccessTokenUrl); }
IOAuthSession CreateConsumer(string signatureMethod) { var consumerContext = new OAuthConsumerContext { SignatureMethod = signatureMethod, ConsumerKey = "key", ConsumerSecret = "secret", Key = certificate.PrivateKey, Realm = "http://term.ie/" }; return new OAuthSession(consumerContext, "http://term.ie/oauth/example/request_token.php", "http://localhost/authorize", "http://term.ie/oauth/example/access_token.php"); }
static IOAuthSession CreateConsumer(string signatureMethod) { var consumerContext = new OAuthConsumerContext { SignatureMethod = signatureMethod, ConsumerKey = "key", ConsumerSecret = "secret", Key = TestCertificates.OAuthTestCertificate().PrivateKey }; var session = new OAuthSession(consumerContext, "http://localhost/oauth/requesttoken.rails", "http://localhost/oauth/userauhtorize.rails", "http://localhost/oauth/accesstoken.rails"); return session; }
private static void Main() { string requestUrl = "https://apis.daum.net/oauth/requestToken"; string userAuthorizeUrl = "https://apis.daum.net/oauth/authorize"; string accessUrl = "https://apis.daum.net/oauth/accessToken"; string callbackUrl = "oob"; var consumerContext = new OAuthConsumerContext { //TODO:Daum OAuth소개 페이지(https://apis.daum.net/oauth/consumer/list)에서 등록된 Consumer 정보 입력 ConsumerKey = "eb3eff10-b95d-455c-8572-e7858a2b34d0", ConsumerSecret = "suz6.HUjzlaG-S9ezBzFQ11FtKhQvv8cdT-9C_hWBFthpUmMTsOuUA00", SignatureMethod = SignatureMethod.HmacSha1, }; //OAuth 준비 var session = new OAuthSession(consumerContext, requestUrl, userAuthorizeUrl, accessUrl); session.WithQueryParameters(new Dictionary<string,string>(){ { "oauth_callback", callbackUrl } }); // 1. request token 받기 DevDefined.OAuth.Framework.IToken requestToken = session.GetRequestToken(); // 인증주소 받기 string authorizationLink = session.GetUserAuthorizationUrlForToken(requestToken, callbackUrl); // 2. 사용자 인증 하기 System.Console.WriteLine("웹브라우저를 실행하여 다음 URL을 접속하세요."); System.Console.WriteLine(authorizationLink); System.Console.Write("\n\n웹브라우저에서 인증 후 반환 된 값을 입력하세요:"); string inputVerifier = System.Console.ReadLine(); // 얻어진 Verifier값을 포함시키기 session.WithQueryParameters(new Dictionary<string, string>() { { "oauth_verifier", inputVerifier } }); session.WithQueryParameters(new Dictionary<string, string>() { { "content", System.Web.HttpUtility.HtmlEncode("~다!음@ #요$즘% ^특&수*문(자) -_\'발=+송\\| \"테<스>;트/") } }); //session.WithQueryParameters(new Dictionary<string, string>() { { "content", System.Web.HttpUtility.UrlEncode("한글") } }); // 3. 인증 후 얻은 Verifier값을 이용하여 엑세스 토큰 얻기 DevDefined.OAuth.Framework.IToken accessToken = session.ExchangeRequestTokenForAccessToken(requestToken); // '요즘 가입여부 확인하기' API를 통해 인증 확인하기 System.Console.WriteLine("OAuth를 통한 인증으로 '요즘 가입여부 확인하기'를 테스트합니다."); string responseText = session.Request().Post().ForUrl("https://apis.daum.net/cafe/write_article/JJGO/JVYh.xml?").ToString(); System.Console.WriteLine(responseText); System.Console.ReadLine(); }
public void TestSignAccessToken() { var cert = new X509Certificate2("XeroApiNet-Sample.pfx", "password"); var consumerContext = new OAuthConsumerContext { // Partner and Private apps use RSA-SHA1 signing method SignatureMethod = SignatureMethod.RsaSha1, UseHeaderForOAuthParameters = true, // Urls RequestTokenUri = null, UserAuthorizeUri = null, AccessTokenUri = XeroApiEndpoints.PublicAccessTokenUri, BaseEndpointUri = XeroApiEndpoints.PublicBaseEndpointUri, Key = cert.PrivateKey, ConsumerKey = ConsumerKey, ConsumerSecret = string.Empty, UserAgent = UserAgent, }; var oauthContext = new OAuthContext { RequestMethod = "POST", RawUri = new Uri("https://photos.example.net/access_token"), ConsumerKey = "dpf43f3p2l4k3l03", SignatureMethod = SignatureMethod.RsaSha1, Timestamp = "1191242090", Token = "hh5s93j4hdidpola", TokenSecret = "hdhd0244k9j7ao03", Nonce = "hsu94j3884jdopsl", Verifier = "hfdp7dh39dks9884", Version = "1.0" }; var signatureBase = oauthContext.GenerateSignatureBase(); consumerContext.Signer.SignContext(oauthContext, new SigningContext { Algorithm = consumerContext.Key, ConsumerSecret = null, SignatureBase = signatureBase }); Assert.That(oauthContext.Signature, Is.EqualTo("32vGleSAIeMbgW9E0pC+PUkyZ1Y05zuEd+FZwg+w4jZzj3E1zldbrGY5SnVpypZfjixWuHMtV4mwGwptwiTZRkrLBudWqJDEddvlwuIMY1j6WkQulz/IXzbGuPNgTya/KTEhQ5IExJXCKE1LZ9bNsMXBDpyi7/ayZe9ONqoVzS8=")); }
protected IOAuthSession CreateSession() { string callBackUrl = "http://localhost:" + HttpContext.Current.Request.Url.Port + "/Callback.aspx"; var consumerContext = new OAuthConsumerContext { ConsumerKey = "key", ConsumerSecret = "secret", Key = TestCertificates.OAuthTestCertificate().PrivateKey }; return new OAuthSession(consumerContext, Settings.Default.RequestTokenUrl, Settings.Default.UserAuthorizationUrl, Settings.Default.AccessTokenUrl, callBackUrl).RequiresCallbackConfirmation(); }
private static void Main() { string requestUrl = "https://apis.daum.net/oauth/requestToken"; string userAuthorizeUrl = "https://apis.daum.net/oauth/authorize"; string accessUrl = "https://apis.daum.net/oauth/accessToken"; string callBackUrl = "oob"; var consumerContext = new OAuthConsumerContext { //TODO:Daum OAuth소개 페이지(https://apis.daum.net/oauth/consumer/list)에서 등록된 Consumer 정보 입력 ConsumerKey = "{발급 받은 Key를 입력하세요.}", ConsumerSecret = "{발급 받은 Secret를 입력하세요.}", SignatureMethod = SignatureMethod.HmacSha1, }; //OAuth 준비 var session = new OAuthSession(consumerContext, requestUrl, userAuthorizeUrl, accessUrl); session.WithQueryParameters(new Dictionary<string,string>(){ { "oauth_callback", callBackUrl } }); // 1. request token 받기 DevDefined.OAuth.Framework.IToken requestToken = session.GetRequestToken(); // 인증주소 받기 string authorizationLink = session.GetUserAuthorizationUrlForToken(requestToken, callBackUrl); // 2. 사용자 인증 하기 System.Console.WriteLine("웹브라우저를 실행하여 다음 URL을 접속하세요."); System.Console.WriteLine(authorizationLink); System.Console.Write("\n\n웹브라우저에서 인증 후 반환 된 값을 입력하세요:"); string inputVerifier = System.Console.ReadLine(); // 얻어진 Verifier값을 포함시키기 session.WithQueryParameters(new Dictionary<string, string>() { { "oauth_verifier", inputVerifier } }); // 3. 인증 후 얻은 Verifier값을 이용하여 엑세스 토큰 얻기 DevDefined.OAuth.Framework.IToken accessToken = session.ExchangeRequestTokenForAccessToken(requestToken); // '요즘 가입여부 확인하기' API를 통해 인증 확인하기 System.Console.WriteLine("OAuth를 통한 인증으로 '요즘 글쓰기'를 테스트합니다."); ConsumerRequest cr = session.Request().Post().ForUrl("https://apis.daum.net/yozm/v1_0/message/add.xml"); cr = cr.WithFormParameters(new Dictionary<string, string>() { { "message", System.Web.HttpUtility.UrlEncode("%$가나다^$%^%$^RTY<><><><><") } }); string responseText = cr.ToString(); System.Console.WriteLine(responseText); System.Console.ReadLine(); }
// this performs our main OAuth authentication, performing // the request token retrieval, authorization, and exchange // for an access token public IToken GetAccessToken() { var consumerContext = new OAuthConsumerContext () { ConsumerKey = "anyone" }; var rest_client = new JsonServiceClient (BaseUri); var url = new Rainy.WebService.ApiRequest ().ToUrl("GET"); var api_ref = rest_client.Get<ApiResponse> (url); var session = new OAuthSession (consumerContext, api_ref.OAuthRequestTokenUrl, api_ref.OAuthAuthorizeUrl, api_ref.OAuthAccessTokenUrl); IToken request_token = session.GetRequestToken (); // we dont need a callback url string link = session.GetUserAuthorizationUrlForToken (request_token, "http://example.com/"); // visit the link to perform the authorization (no interaction needed) HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create (link); // disallow auto redirection, since we are interested in the location header only req.AllowAutoRedirect = false; // the oauth_verifier we need, is part of the querystring in the (redirection) // 'Location:' header string location = ((HttpWebResponse)req.GetResponse ()).Headers ["Location"]; var query = string.Join ("", location.Split ('?').Skip (1)); var oauth_data = System.Web.HttpUtility.ParseQueryString (query); IToken access_token = session.ExchangeRequestTokenForAccessToken (request_token, oauth_data ["oauth_verifier"]); return access_token; }