private OAuthResponse FetchToken(OAuthEnvironment environment, String requestPayload, TokenType tokenType) { //Get credentials CredentialUtil.Credentials credentials = GetCredentials(environment); //Initialize client RestClient client = new RestClient { BaseUrl = new Uri(environment.ApiEndpoint()) }; //Create request RestRequest request = new RestRequest(Method.POST); //Add headers request.AddHeader(Constants.HEADER_AUTHORIZATION, OAuth2Util.CreateAuthorizationHeader(credentials)); //Set request payload request.AddParameter(Constants.HEADER_CONTENT_TYPE, requestPayload, ParameterType.RequestBody); //Call the API IRestResponse response = client.Execute(request); //Parse response OAuthResponse oAuthResponse = HandleApiResponse(response, tokenType); return(oAuthResponse); }
/* * Use this operation to update the access token if it has expired */ public OAuthResponse GetAccessToken(OAuthEnvironment environment, String refreshToken, IList <String> scopes) { //Validate request ValidateEnvironmentAndScopes(environment, scopes); ValidateInput("RefreshToken", refreshToken); //Get credentials CredentialUtil.Credentials credentials = GetCredentials(environment); //Format scopes String formattedScopes = OAuth2Util.FormatScopesForRequest(scopes); // Create request payload Dictionary <String, String> payloadParams = new Dictionary <string, string> { { Constants.PAYLOAD_GRANT_TYPE, Constants.PAYLOAD_VALUE_REFRESH_TOKEN }, { Constants.PAYLOAD_REFRESH_TOKEN, refreshToken }, { Constants.PAYLOAD_SCOPE, formattedScopes } }; String requestPayload = OAuth2Util.CreateRequestPayload(payloadParams); OAuthResponse oAuthResponse = FetchToken(environment, requestPayload, TokenType.USER); return(oAuthResponse); }
/* * Loading YAML file */ public static void Load(StreamReader streamReader) { //Load the stream YamlStream yaml = new YamlStream(); yaml.Load(streamReader); // Parse the stream var rootNode = (YamlMappingNode)yaml.Documents[0].RootNode; foreach (var firstLevelNode in rootNode.Children) { OAuthEnvironment environment = OAuthEnvironment.LookupByConfigIdentifier(((YamlScalarNode)firstLevelNode.Key).Value); if (environment == null) { continue; } foreach (var node in firstLevelNode.Value.AllNodes) { if (node is YamlMappingNode) { Credentials credentials = new Credentials((YamlMappingNode)node); envCredentials[environment.ConfigIdentifier()] = credentials; } } } log.Info("Loaded configuration for eBay oAuth Token"); }
private void GetApplicationToken_Success(OAuthEnvironment environment) { OAuthResponse oAuthResponse = oAuth2Api.GetApplicationToken(environment, scopes); Assert.NotNull(oAuthResponse); PrintOAuthResponse(environment, "GetApplicationToken", oAuthResponse); }
private void GetAccessToken_EndToEnd(OAuthEnvironment environment) { //Load user credentials UserCredential userCredential = ReadUserNamePassword(environment); if ("<sandbox-username>".Equals(userCredential.UserName) || "<production-username>".Equals(userCredential.UserName) || "<sandbox-user-password>".Equals(userCredential.Pwd) || "<production-user-password>".Equals(userCredential.Pwd)) { Console.WriteLine("User name and password are not specified in test-config-sample.yaml"); return; } String authorizationUrl = oAuth2Api.GenerateUserAuthorizationUrl(environment, userScopes, null); Console.WriteLine("AuthorizationUrl => " + authorizationUrl); String authorizationCode = GetAuthorizationCode(authorizationUrl, userCredential); Console.WriteLine("AuthorizationCode => " + authorizationCode); OAuthResponse oAuthResponse = oAuth2Api.ExchangeCodeForAccessToken(environment, authorizationCode); Assert.NotNull(oAuthResponse); Assert.NotNull(oAuthResponse.RefreshToken); String refreshToken = oAuthResponse.RefreshToken.Token; Console.WriteLine("RefreshToken=> " + refreshToken); oAuthResponse = oAuth2Api.GetAccessToken(environment, refreshToken, userScopes); Assert.NotNull(oAuthResponse); Assert.NotNull(oAuthResponse.AccessToken); Console.WriteLine("AccessToken=> " + oAuthResponse.AccessToken.Token); }
/* * Use this operation to get the Authorization URL to redirect the user to. * Once the user authenticates and approves the consent, the callback need to be * captured by the redirect URL setup by the app */ public String GenerateUserAuthorizationUrl(OAuthEnvironment environment, IList <String> scopes, String state) { //Validate request ValidateEnvironmentAndScopes(environment, scopes); //Get credentials CredentialUtil.Credentials credentials = GetCredentials(environment); //Format scopes String formattedScopes = OAuth2Util.FormatScopesForRequest(scopes); //Prepare URL StringBuilder sb = new StringBuilder(); sb.Append(environment.WebEndpoint()).Append("?"); //Prepare request payload Dictionary <String, String> queryParams = new Dictionary <string, string> { { Constants.PAYLOAD_CLIENT_ID, credentials.Get(CredentialType.APP_ID) }, { Constants.PAYLOAD_RESPONSE_TYPE, Constants.PAYLOAD_VALUE_CODE }, { Constants.PAYLOAD_REDIRECT_URI, credentials.Get(CredentialType.REDIRECT_URI) }, { Constants.PAYLOAD_SCOPE, formattedScopes } }; if (state != null) { queryParams.Add(Constants.PAYLOAD_STATE, state); } sb.Append(OAuth2Util.CreateRequestPayload(queryParams)); log.Debug("Authorization url " + sb); return(sb.ToString()); }
private CredentialUtil.Credentials GetCredentials(OAuthEnvironment environment) { CredentialUtil.Credentials credentials = CredentialUtil.GetCredentials(environment); if (credentials == null) { throw new ArgumentException("Credentials have not been loaded for " + environment.ConfigIdentifier()); } return(credentials); }
public void GetAccessToken_Success() { OAuthEnvironment environment = OAuthEnvironment.PRODUCTION; String refreshToken = "v^1.1*****************I2MA=="; OAuthResponse oAuthResponse = oAuth2Api.GetAccessToken(environment, refreshToken, userScopes); Assert.NotNull(oAuthResponse); PrintOAuthResponse(environment, "GetAccessToken", oAuthResponse); }
public void ExchangeCodeForAccessToken_Success() { OAuthEnvironment environment = OAuthEnvironment.PRODUCTION; String code = "v^1.1**********************jYw"; OAuthResponse oAuthResponse = oAuth2Api.ExchangeCodeForAccessToken(environment, code); Assert.NotNull(oAuthResponse); PrintOAuthResponse(environment, "ExchangeCodeForAccessToken", oAuthResponse); }
private void PrintOAuthResponse(OAuthEnvironment environment, String methodName, OAuthResponse oAuthResponse) { Console.WriteLine("======================" + methodName + "======================"); Console.WriteLine("Environment=> " + environment.ConfigIdentifier() + ", ErroMessage=> " + oAuthResponse.ErrorMessage); if (oAuthResponse.AccessToken != null) { Console.WriteLine("AccessToken=> " + oAuthResponse.AccessToken.Token); } if (oAuthResponse.RefreshToken != null) { Console.WriteLine("RefreshToken=> " + oAuthResponse.RefreshToken.Token); } }
public void UpdateValue(OAuthEnvironment environment, OAuthResponse oAuthResponse, DateTime expiresAt) { AppTokenCacheModel appTokenCacheModel = new AppTokenCacheModel { OAuthResponse = oAuthResponse, //Setting a buffer of 5 minutes for refresh ExpiresAt = expiresAt.Subtract(new TimeSpan(0, 5, 0)) }; envAppTokenCache.Add(environment.ConfigIdentifier(), appTokenCacheModel); }
public OAuthResponse GetValue(OAuthEnvironment environment) { AppTokenCacheModel appTokenCacheModel = this.envAppTokenCache.TryGetValue(environment.ConfigIdentifier(), out AppTokenCacheModel value) ? value : null; if (appTokenCacheModel != null) { if ((appTokenCacheModel.OAuthResponse != null && appTokenCacheModel.OAuthResponse.ErrorMessage != null) || (DateTime.Now.CompareTo(appTokenCacheModel.ExpiresAt) < 0)) { return(appTokenCacheModel.OAuthResponse); } } //Since the value is expired, return null return(null); }
/* * Use this operation to update the access token if it has expired */ public OAuthResponse GetAccessToken(OAuthEnvironment environment, String refreshToken, IList <String> scopes) { //Validate request ValidateEnvironmentAndScopes(environment, scopes); ValidateInput("RefreshToken", refreshToken); //Get credentials CredentialUtil.Credentials credentials = GetCredentials(environment); //Format scopes String formattedScopes = OAuth2Util.FormatScopesForRequest(scopes); // Create request payload Dictionary <String, String> payloadParams = new Dictionary <string, string> { { Constants.PAYLOAD_GRANT_TYPE, Constants.PAYLOAD_VALUE_REFRESH_TOKEN }, { Constants.PAYLOAD_REFRESH_TOKEN, refreshToken }, { Constants.PAYLOAD_SCOPE, formattedScopes } }; String requestPayload = OAuth2Util.CreateRequestPayload(payloadParams); OAuthResponse oAuthResponse; //Check for token in cache oAuthResponse = accessTokenCache.GetValue(environment); if (oAuthResponse != null && oAuthResponse.AccessToken != null && oAuthResponse.AccessToken.Token != null) { log.Info("Returning access token from cache for " + environment.ConfigIdentifier()); return(oAuthResponse); } oAuthResponse = FetchToken(environment, requestPayload, TokenType.USER); if (oAuthResponse != null && oAuthResponse.AccessToken != null) { accessTokenCache.UpdateValue(environment, oAuthResponse, oAuthResponse.AccessToken.ExpiresOn); } return(oAuthResponse); }
/* * Use this operation to get the refresh and access tokens. */ public OAuthResponse ExchangeCodeForAccessToken(OAuthEnvironment environment, String code) { //Validate request ValidateInput("Environment", environment); ValidateInput("Code", code); //Get credentials CredentialUtil.Credentials credentials = GetCredentials(environment); // Create request payload Dictionary <String, String> payloadParams = new Dictionary <string, string> { { Constants.PAYLOAD_GRANT_TYPE, Constants.PAYLOAD_VALUE_AUTHORIZATION_CODE }, { Constants.PAYLOAD_REDIRECT_URI, credentials.Get(CredentialType.REDIRECT_URI) }, { Constants.PAYLOAD_CODE, code } }; String requestPayload = OAuth2Util.CreateRequestPayload(payloadParams); OAuthResponse oAuthResponse = FetchToken(environment, requestPayload, TokenType.USER); return(oAuthResponse); }
private UserCredential ReadUserNamePassword(OAuthEnvironment environment) { UserCredential userCredential = new UserCredential(); YamlStream yaml = new YamlStream(); StreamReader streamReader = new StreamReader("../../../test-config-sample.yaml"); yaml.Load(streamReader); var rootNode = (YamlMappingNode)yaml.Documents[0].RootNode; foreach (var firstLevelNode in rootNode.Children) { foreach (var node in firstLevelNode.Value.AllNodes) { String configEnvironment = ((YamlScalarNode)firstLevelNode.Key).Value; if ((environment.ConfigIdentifier().Equals(OAuthEnvironment.PRODUCTION.ConfigIdentifier()) && "sandbox-user".Equals(configEnvironment)) || (environment.ConfigIdentifier().Equals(OAuthEnvironment.SANDBOX.ConfigIdentifier()) && "production-user".Equals(configEnvironment))) { continue; } if (node is YamlMappingNode) { foreach (var keyValuePair in ((YamlMappingNode)node).Children) { if ("username".Equals(keyValuePair.Key.ToString())) { userCredential.UserName = keyValuePair.Value.ToString(); } else { userCredential.Pwd = keyValuePair.Value.ToString(); } } } } } return(userCredential); }
/* * Use this operation to get an OAuth access token using a client credentials grant. * The access token retrieved from this process is called an Application access token. */ public OAuthResponse GetApplicationToken(OAuthEnvironment environment, IList <String> scopes) { //Validate request ValidateEnvironmentAndScopes(environment, scopes); OAuthResponse oAuthResponse = null; //Check for token in cache if (appTokenCache != null) { oAuthResponse = appTokenCache.GetValue(environment); if (oAuthResponse != null && oAuthResponse.AccessToken != null && oAuthResponse.AccessToken.Token != null) { log.Info("Returning token from cache for " + environment.ConfigIdentifier()); return(oAuthResponse); } } //App token not in cache, fetch it and set into cache String formattedScopes = OAuth2Util.FormatScopesForRequest(scopes); //Prepare request payload Dictionary <String, String> payloadParams = new Dictionary <string, string> { { Constants.PAYLOAD_GRANT_TYPE, Constants.PAYLOAD_VALUE_CLIENT_CREDENTIALS }, { Constants.PAYLOAD_SCOPE, formattedScopes } }; String requestPayload = OAuth2Util.CreateRequestPayload(payloadParams); oAuthResponse = FetchToken(environment, requestPayload, TokenType.APPLICATION); //Update value in cache if (oAuthResponse != null && oAuthResponse.AccessToken != null) { appTokenCache.UpdateValue(environment, oAuthResponse, oAuthResponse.AccessToken.ExpiresOn); } return(oAuthResponse); }
/* * Get Credentials based on Environment */ public static Credentials GetCredentials(OAuthEnvironment environment) { return(envCredentials.TryGetValue(environment.ConfigIdentifier(), out Credentials credentials) ? credentials : null); }
private void ValidateEnvironmentAndScopes(OAuthEnvironment environment, IList <String> scopes) { ValidateInput("Environment", environment); ValidateScopes(scopes); }