public static async Task <IApiSession> GetOAuth2Session() { var session = new OAuth2Session(HostUrl, ClientCredentials, UserCredentials); await session.GetAccessToken(); return(session); }
/// <summary> /// Instantiates a new AuthRepository /// </summary> /// <param name="canvasConfig">The Canvas app configuration that should be used</param> /// <param name="requestService">The service that will be used to make the requests</param> /// <param name="converter">How requests/responses will be serialized/deserialized respectively</param> /// <param name="session">The current authenticated session</param> public AuthRepository(ICanvasConfig canvasConfig, IRequestService requestService, IJsonConverter converter, OAuth2Session session) { _config = canvasConfig; _service = requestService; _converter = converter; Session = session; }
public bool InitializeOauth() { var tokens = System.IO.File.ReadAllLines(@Server.MapPath("~/state.txt")); var refresh_token = ""; var token_type = ""; var access_token = ""; if (tokens != null && tokens.Count() == 3) { string domain = ConfigurationManager.AppSettings["Domain"]; string oauth_path = ConfigurationManager.AppSettings["OauthPath"]; string client_id = ConfigurationManager.AppSettings["ClientID"]; var client_secret = ConfigurationManager.AppSettings["ClientSecret"]; var redirect_uri_str = ConfigurationManager.AppSettings["RedirectUri"]; var redirect_uri = (Uri)null; if (string.IsNullOrEmpty(redirect_uri_str) == false) { redirect_uri = new Uri(redirect_uri_str); } access_token = tokens[0]; refresh_token = tokens[1]; token_type = tokens[2]; _Config = new CanvasConfig(domain, client_id, client_secret, redirect_uri); _Session = new OAuth2Session(access_token, refresh_token, 1, token_type); _AuthRepository = new AuthRepository(_Config, new RequestService(new HttpRequestHandler()), new JsonConverter(), _Session); _Client = new Client(_Config, _AuthRepository); return(true); } return(false); }
public async static Task DoStuff(string[] tokens, string domain, string client_id) { var access_token = tokens[0]; var refresh_token = tokens[1]; var token_type = tokens[2]; var client_secret = ConfigurationManager.AppSettings["ClientSecret"]; var redirect_uri_str = ConfigurationManager.AppSettings["RedirectUri"]; var redirect_uri = (Uri)null; if (string.IsNullOrEmpty(redirect_uri_str) == false) { redirect_uri = new Uri(redirect_uri_str); } var canvas_config = new CanvasConfig(domain, client_id, client_secret, redirect_uri); var oauth2session = new OAuth2Session("", refresh_token, 0, token_type); var client = new Client(canvas_config, new AuthRepository(canvas_config, new RequestService(new HttpRequestHandler()), new JsonConverter(), oauth2session)); var self_account = await client.AccountsManager.GetSelf().ConfigureAwait(false); var courses = await client.CoursesManager.GetAll().ConfigureAwait(false); return; }
/// <summary> /// Refreshes the session by exchanging the access token for a new Access/Refresh token pair. In general, /// this method should not need to be called explicitly, as an automatic refresh is invoked when the SDK /// detects that the tokens have expired. /// </summary> /// <param name="accessToken"></param> /// <returns></returns> public virtual async Task <OAuth2Session> RefreshAccessTokenAsync(string accessToken) { OAuth2Session session; using (await _mutex.LockAsync().ConfigureAwait(false)) { if (_expiredTokens.Contains(accessToken)) { session = Session; } else { // Add the expired token to the list so subsequent calls will get new acces token. Add // token to the list before making the network call. This way, if refresh fails, subsequent calls // with the same refresh token will not attempt te call. _expiredTokens.Add(accessToken); session = await ExchangeRefreshToken(Session.RefreshToken).ConfigureAwait(false); Session = session; OnSessionAuthenticated(session); } } return(session); }
public async Task QueueTask_MultipleThreads_OrderedResponse() { /*** Arrange ***/ int numTasks = 1000; int count = 0; // Increments the access token each time a call is made to the API _handler.Setup(h => h.ExecuteAsync <OAuth2Session>(It.IsAny <IApiRequest>())) .Returns(() => Task.FromResult <IApiResponse <OAuth2Session> >(new ApiResponse <OAuth2Session>() { Status = ResponseStatus.Success, ContentString = "{\"access_token\": \"" + count + "\",\"expires_in\": 3600,\"token_type\": \"bearer\",\"refresh_token\": \"J7rxTiWOHMoSC1isKZKBZWizoRXjkQzig5C6jFgCVJ9bUnsUfGMinKBDLZWP9BgR\"}" })).Callback(() => System.Threading.Interlocked.Increment(ref count)); /*** Act ***/ IApiRequest request = new ApiRequest(new Uri("http://example.com"), "folders"); List <Task <IApiResponse <OAuth2Session> > > tasks = new List <Task <IApiResponse <OAuth2Session> > >(); for (int i = 0; i < numTasks; i++) { tasks.Add(_service.EnqueueAsync <OAuth2Session>(request)); } await Task.WhenAll(tasks); /*** Assert ***/ for (int i = 0; i < numTasks; i++) { OAuth2Session session = _converter.Parse <OAuth2Session>(tasks[i].Result.ContentString); Assert.AreEqual(session.AccessToken, i.ToString()); } }
/// <summary> /// Retry the request once if the first try was due to an expired token /// </summary> /// <typeparam name="T"></typeparam> /// <param name="request"></param> /// <returns></returns> protected async Task <IApiResponse <T> > RetryExpiredTokenRequest <T>(IApiRequest request) where T : class { OAuth2Session newSession = await _auth.RefreshAccessTokenAsync(request.Authorization).ConfigureAwait(false); AddDefaultHeaders(request); AddAuthorization(request, newSession.AccessToken); return(await _service.ToResponseAsync <T>(request).ConfigureAwait(false)); }
public ResourceManagerTestIntegration() { _auth = new OAuth2Session("YOUR_ACCESS_TOKEN", "YOUR_REFRESH_TOKEN", 3600, "bearer"); _handler = new HttpRequestHandler(); _parser = new JsonConverter(); _config = new CanvasConfig(CanvasDomain, ClientId, ClientSecret, RedirectUri); _client = new Client(_config, _auth); }
/// <summary> /// Allows sub classes to invoke the SessionAuthenticated event /// </summary> /// <param name="e"></param> protected void OnSessionAuthenticated(OAuth2Session session) { var handler = SessionAuthenticated; if (handler != null) { handler(this, new SessionAuthenticatedEventArgs(session)); } }
/// <summary> /// Instantiates a Client with the provided config object and auth session /// </summary> /// <param name="config">The config object to be used</param> /// <param name="authSession">A fully authenticated auth session</param> public Client(ICanvasConfig config, OAuth2Session authSession = null) : this(config, new AuthRepository(config, new RequestService(new HttpRequestHandler()), new JsonConverter(), authSession)) { _config = config; _converter = new JsonConverter(); _service = new RequestService(new HttpRequestHandler()); Auth = new AuthRepository(config, new RequestService(new HttpRequestHandler()), new JsonConverter(), authSession); InitManagers(); }
public RequestServiceTest() { // Initial Setup _converter = new JsonConverter(); _handler = new Mock<IRequestHandler>(); _service = new RequestService(_handler.Object); _boxConfig = new Mock<ICanvasConfig>(); OAuth2Session session = new OAuth2Session("fakeAccessToken", "fakeRefreshToken", 3600, "bearer"); _authRepository = new AuthRepository(_boxConfig.Object, _service, _converter, session); }
public RequestServiceTest() { // Initial Setup _converter = new JsonConverter(); _handler = new Mock <IRequestHandler>(); _service = new RequestService(_handler.Object); _boxConfig = new Mock <ICanvasConfig>(); OAuth2Session session = new OAuth2Session("fakeAccessToken", "fakeRefreshToken", 3600, "bearer"); _authRepository = new AuthRepository(_boxConfig.Object, _service, _converter, session); }
public async Task AuthenticateLive_InvalidAuthCode_Exception() { // Arrange IRequestHandler handler = new HttpRequestHandler(); IRequestService service = new RequestService(handler); ICanvasConfig config = new CanvasConfig("domain", null, null, null); IAuthRepository authRepository = new AuthRepository(config, service, _converter); // Act OAuth2Session response = await authRepository.AuthenticateAsync("fakeAuthorizationCode"); }
/// <summary> /// Authenticates the session by exchanging the provided auth code for a Access/Refresh token pair /// </summary> /// <param name="authCode"></param> /// <returns></returns> public virtual async Task <OAuth2Session> AuthenticateAsync(string authCode) { OAuth2Session session = await ExchangeAuthCode(authCode).ConfigureAwait(false); using (await _mutex.LockAsync().ConfigureAwait(false)) { Session = session; OnSessionAuthenticated(session); } return(session); }
/// <summary> /// Authenticates the session by exchanging the provided auth code for a Access/Refresh token pair /// </summary> /// <param name="authCode"></param> /// <returns></returns> public virtual async Task<OAuth2Session> AuthenticateAsync(string authCode) { OAuth2Session session = await ExchangeAuthCode(authCode).ConfigureAwait(false); using (await _mutex.LockAsync().ConfigureAwait(false)) { Session = session; OnSessionAuthenticated(session); } return session; }
public async Task Authenticate_ErrorResponse_Exception() { // Arrange _handler.Setup(h => h.ExecuteAsync <OAuth2Session>(It.IsAny <IApiRequest>())) .Returns(Task <IApiResponse <OAuth2Session> > .Factory.StartNew(() => new ApiResponse <OAuth2Session>() { Status = ResponseStatus.Error, ContentString = "{\"error\": \"invalid_grant\",\"error_description\": \"Invalid user credentials\"}" })); // Act OAuth2Session session = await _authRepository.AuthenticateAsync("fakeauthorizationcode"); }
public async Task RefreshSession_ValidResponse_ValidSession() { // Arrange _handler.Setup(h => h.ExecuteAsync <OAuth2Session>(It.IsAny <IApiRequest>())) .Returns(Task <IApiResponse <OAuth2Session> > .Factory.StartNew(() => new ApiResponse <OAuth2Session>() { Status = ResponseStatus.Success, ContentString = "{\"access_token\": \"T9cE5asGnuyYCCqIZFoWjFHvNbvVqHjl\",\"expires_in\": 3600,\"token_type\": \"bearer\",\"refresh_token\": \"J7rxTiWOHMoSC1isKZKBZWizoRXjkQzig5C6jFgCVJ9bUnsUfGMinKBDLZWP9BgR\"}" })); // Act OAuth2Session session = await _authRepository.RefreshAccessTokenAsync("fakeaccesstoken"); // Assert Assert.AreEqual(session.AccessToken, "T9cE5asGnuyYCCqIZFoWjFHvNbvVqHjl"); Assert.AreEqual(session.ExpiresIn, 3600); Assert.AreEqual(session.RefreshToken, "J7rxTiWOHMoSC1isKZKBZWizoRXjkQzig5C6jFgCVJ9bUnsUfGMinKBDLZWP9BgR"); Assert.AreEqual(session.TokenType, "bearer"); }
public SessionAuthenticatedEventArgs(OAuth2Session session) { Session = session; }
/// <summary> /// Refreshes the session by exchanging the access token for a new Access/Refresh token pair. In general, /// this method should not need to be called explicitly, as an automatic refresh is invoked when the SDK /// detects that the tokens have expired. /// </summary> /// <param name="accessToken"></param> /// <returns></returns> public virtual async Task<OAuth2Session> RefreshAccessTokenAsync(string accessToken) { OAuth2Session session; using (await _mutex.LockAsync().ConfigureAwait(false)) { if (_expiredTokens.Contains(accessToken)) { session = Session; } else { // Add the expired token to the list so subsequent calls will get new acces token. Add // token to the list before making the network call. This way, if refresh fails, subsequent calls // with the same refresh token will not attempt te call. _expiredTokens.Add(accessToken); session = await ExchangeRefreshToken(Session.RefreshToken).ConfigureAwait(false); Session = session; OnSessionAuthenticated(session); } } return session; }