public async Task Correctly_Detects_Stale_Token_Refreshes_And_Retries_Original_Request() { var originalToken = new OAuth2AccessToken() { Token = "eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0MzAzNDM3MzUsInNjb3BlcyI6Indwcm8gd2xvYyB3bnV0IHdzbGUgd3NldCB3aHIgd3dlaSB3YWN0IHdzb2MiLCJzdWIiOiJBQkNERUYiLCJhdWQiOiJJSktMTU4iLCJpc3MiOiJGaXRiaXQiLCJ0eXAiOiJhY2Nlc3NfdG9rZW4iLCJpYXQiOjE0MzAzNDAxMzV9.z0VHrIEzjsBnjiNMBey6wtu26yHTnSWz_qlqoEpUlpc" }; var refreshedToken = new OAuth2AccessToken() { Token = "Refreshed" }; //mocking our implementation of token manager. This test is concerned with ensuring the wiring is done correctly. Not the actual refresh process. var fakeManager = new Mock <ITokenManager>(); fakeManager.Setup(m => m.RefreshTokenAsync(It.IsAny <FitbitClient>())).Returns(() => Task.Run(() => refreshedToken)); //we shortcircuit the request to fake an expired token on the first request, and assuming the token is different the second time we let the request through var fakeServer = new StaleTokenFaker(); var sut = new FitbitClient(dummyCredentials, originalToken, fakeServer, /*Explicity activate autorefresh, default is true*/ true, fakeManager.Object); //Act var actualResponse = await sut.HttpClient.GetAsync("https://dev.fitbit.com/"); //Assert Assert.AreEqual(refreshedToken, sut.AccessToken); fakeManager.Verify(m => m.RefreshTokenAsync(It.IsAny <FitbitClient>()), Times.Once); //Expecte two interceptions. First when we get the 401 refresh, and second when we retry after refreshing the stale token Assert.AreEqual(2, fakeServer.requestCount, "It looks like either the client did not retry after the token was refreshed, or the stale token was not detected"); }
//Refresh AccessToken when expired. public static async Task <OAuth2AccessToken> RefreshTokenAsync(string expiredToken) { HttpClient httpClient = new HttpClient(); string postUrl = OAuth2Helper.FitbitOauthPostUrl; var content = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("grant_type", "refresh_token"), new KeyValuePair <string, string>("refresh_token", expiredToken), }); string clientIdConcatSecret = OAuth2Helper.Base64Encode(ClientId + ":" + ClientSecret); httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", clientIdConcatSecret); HttpResponseMessage response = await httpClient.PostAsync(postUrl, content); string responseString = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseString); OAuth2AccessToken accessToken = OAuth2Helper.ParseAccessTokenResponse(responseString); return(accessToken); }
public OAuth2AccessToken resolve(String tokenString) { OAuth2AccessTokenEnvelope envelope = JasonUtils.UnmarshalAccessTokenEnvelope(tokenString); if (envelope == null) { throw new System.ApplicationException("Cannot create OAuth2 Envelope from token"); } String accessToken = envelope.Token; if (!tokenSigner.IsValid(accessToken, envelope.SignatureValue)) { // Invalid signature, throw exception. throw new System.ApplicationException("Invalid OAuth2 Token signature"); } accessToken = tokenEncrypter.Decrypt(accessToken); if (envelope.Deflated) { accessToken = JasonUtils.inflate(accessToken, true); } OAuth2AccessToken at = JasonUtils.UnmarshalAccessToken(accessToken); // Check token expiration return(at); }
public void Can_Handle_Failed_Refresh_Operation() { const int EXPECT_TWO_COUNT_STALE_AND_RETRY = 2; var originalToken = new OAuth2AccessToken() { Token = "eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0MzAzNDM3MzUsInNjb3BlcyI6Indwcm8gd2xvYyB3bnV0IHdzbGUgd3NldCB3aHIgd3dlaSB3YWN0IHdzb2MiLCJzdWIiOiJBQkNERUYiLCJhdWQiOiJJSktMTU4iLCJpc3MiOiJGaXRiaXQiLCJ0eXAiOiJhY2Nlc3NfdG9rZW4iLCJpYXQiOjE0MzAzNDAxMzV9.z0VHrIEzjsBnjiNMBey6wtu26yHTnSWz_qlqoEpUlpc" }; var refreshedToken = new OAuth2AccessToken() { Token = "Refreshed" }; //mocking our implementation of token manager. This test is concerned with ensuring the wiring is done correctly. Not the actual refresh process. var fakeManager = new Mock <ITokenManager>(); fakeManager.Setup(m => m.RefreshTokenAsync(It.IsAny <FitbitClient>())).Returns(() => Task.Run(() => refreshedToken)); //simulate failed refresh token. var fakeServer = new StaleTokenFaker(10); var sut = new FitbitClient(dummyCredentials, originalToken, fakeServer, fakeManager.Object); //Act var r = sut.HttpClient.GetAsync("https://dev.fitbit.com/"); Assert.Throws <System.AggregateException>(() => r.Wait()); }
public void Common() { AccessToken token = AccessToken.Empty; Assert.True(token.IsEmpty); var token2 = new OAuthAccessToken(new RequestResult("text/html; charset=utf-8", "oauth_token=123456789&oauth_token_secret=abcdef&user_id=111&screen_name=test")); Assert.Equal <string>("123456789", token2.Value); Assert.Equal <string>("abcdef", token2.TokenSecret); var token3 = new OAuth2AccessToken(new RequestResult("text/plain; charset=UTF-8", "access_token=123abc&expires=5180667")); Assert.Equal <string>("123abc", token3.Value); token = "123"; Assert.Equal <string>("123", token.Value); token2 = "123"; Assert.Equal <string>("123", token2.Value); token3 = "123"; Assert.Equal <string>("123", token3.Value); var token4 = AccessToken.Parse("oauth_token=123456789&oauth_token_secret=abcdef&user_id=111&screen_name=test"); Assert.Equal(typeof(OAuthAccessToken), token4.GetType()); var token5 = AccessToken.Parse("access_token=123abc&expires=5180667"); Assert.Equal(typeof(OAuth2AccessToken), token5.GetType()); var token6 = AccessToken.Parse <OAuthAccessToken>("oauth_token=123456789&oauth_token_secret=abcdef&user_id=111&screen_name=test"); Assert.Equal <string>("123456789", token6.Value); Assert.Equal <string>("abcdef", token6.TokenSecret); var token7 = AccessToken.Parse <OAuth2AccessToken>("access_token=123abc&expires=5180667"); Assert.Equal <string>("123abc", token7.Value); Assert.Throws <InvalidCastException>(() => AccessToken.Parse <OAuth2AccessToken>("oauth_token=123456789&oauth_token_secret=abcdef&user_id=111&screen_name=test")); Assert.Throws <InvalidCastException>(() => AccessToken.Parse <OAuthAccessToken>("access_token=123abc&expires=5180667")); AccessToken token10 = null; Assert.Null(token10); AccessToken token11 = ""; Assert.NotNull(token11); var token13 = new OAuth2AccessToken("123", "4567"); Assert.Equal <string>("123", token13.Value); Assert.Equal <string>("4567", token13.RefreshToken); }
public async Task Disable_Automatic_Token_Refresh() { var originalToken = new OAuth2AccessToken() { Token = "eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0MzAzNDM3MzUsInNjb3BlcyI6Indwcm8gd2xvYyB3bnV0IHdzbGUgd3NldCB3aHIgd3dlaSB3YWN0IHdzb2MiLCJzdWIiOiJBQkNERUYiLCJhdWQiOiJJSktMTU4iLCJpc3MiOiJGaXRiaXQiLCJ0eXAiOiJhY2Nlc3NfdG9rZW4iLCJpYXQiOjE0MzAzNDAxMzV9.z0VHrIEzjsBnjiNMBey6wtu26yHTnSWz_qlqoEpUlpc" }; var refreshedToken = new OAuth2AccessToken() { Token = "Refreshed" }; //mocking our implementation of token manager. This test is concerned with ensuring the wiring is done correctly. Not the actual refresh process. var fakeManager = new Mock <ITokenManager>(); fakeManager.Setup(m => m.RefreshTokenAsync(It.IsAny <FitbitClient>())).Returns(() => Task.Run(() => refreshedToken)); //we shortcircuit the request to return a stale token and ensure that the client lets the stale token response through var fakeServer = new StaleTokenFaker(); var sut = new FitbitClient(dummyCredentials, originalToken, fakeServer, false, fakeManager.Object); //Act var actualResponse = await sut.HttpClient.GetAsync("https://dev.fitbit.com/"); //Assert Assert.AreEqual(fakeServer.staleTokenresponse, actualResponse); }
public void UpdateAndSave(OAuth2AccessToken oAuth2AccessToken) { AccessToken = oAuth2AccessToken.AccessToken; RefreshToken = oAuth2AccessToken.RefreshToken; ExpirationDateTime = DateTime.Now.AddSeconds(oAuth2AccessToken.ExpiresIn); Save(); }
protected void SignIn_Click(object sender, EventArgs e) { // Create new OAuth2 client instance OAuth2Client client = new OAuth2Client(); client.init(); // Create a new OAuth2 secure access token resolver SecureAccessTokenResolver tr = new SecureAccessTokenResolver(); tr.init(); // Recover previously stored relay state String relayState = (String)HttpContext.Current.Session["relay_state"]; // Request an access token String accessToken = client.requestToken(UserName.Text, UserPass.Text); // Resolve the token to get user information OAuth2AccessToken at = tr.resolve(accessToken); String userId = at.UserId; String email = at.getAttribute("email"); // Perform pre-authentication, the created URL will have the proper authz token as request parameter String idpUrl = client.buildIdPPreAuthnResponseUrl(relayState, UserName.Text, UserPass.Text); Response.Redirect(idpUrl); }
public static async Task <OAuth2AccessToken> ExchangeAuthCodeForAccessTokenAsync(string code) { HttpClient httpClient = new HttpClient(); string postUrl = OAuth2Helper.FitbitOauthPostUrl; var content = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("grant_type", "authorization_code"), new KeyValuePair <string, string>("client_id", ClientId), //new KeyValuePair<string, string>("client_secret", AppSecret), new KeyValuePair <string, string>("code", code), new KeyValuePair <string, string>("redirect_uri", RedirectUri) }); string clientIdConcatSecret = OAuth2Helper.Base64Encode(ClientId + ":" + ClientSecret); httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", clientIdConcatSecret); HttpResponseMessage response = await httpClient.PostAsync(postUrl, content); string responseString = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseString); OAuth2AccessToken accessToken = OAuth2Helper.ParseAccessTokenResponse(responseString); return(accessToken); }
//Final step. Take this authorization information and use it in the app public async Task <ActionResult> Callback() { //make sure you've set these up in Web.Config under <appSettings>: string ConsumerKey = ConfigurationManager.AppSettings["FitbitConsumerKey"]; string ConsumerSecret = ConfigurationManager.AppSettings["FitbitConsumerSecret"]; string ClientId = ConfigurationManager.AppSettings["FitbitClientId"]; Fitbit.Api.Portable.Authenticator2 authenticator = new Fitbit.Api.Portable.Authenticator2(ClientId, ConsumerSecret, Request.Url.GetLeftPart(UriPartial.Authority) + "/Fitbit/Callback" ); string code = Request.Params["code"]; OAuth2AccessToken accessToken = await authenticator.ExchangeAuthCodeForAccessTokenAsync(code); // For demo, put this in the session managed by ASP.NET Session["AccessToken"] = accessToken; /* * * Session["FitbitAuthToken"] = credential.AuthToken; * Session["FitbitAuthTokenSecret"] = credential.AuthTokenSecret; * Session["FitbitUserId"] = credential.UserId; * */ return(RedirectToAction("Index", "Home")); }
public void OAuth2Helper_Can_Deserialize_AccessToken() { string content = SampleDataHelper.GetContent("AccessToken.json"); OAuth2AccessToken result = OAuth2Helper.ParseAccessTokenResponse(content); Validate(result); }
static TokenResult OAuth2AccessTokenToTokenResult(OAuth2AccessToken oauth2) { TokenResult token = new TokenResult(); token.AccessToken = oauth2.Value; token.Uid = oauth2.CollectionItems["uid"].ToString(); token.TokenType = oauth2.TokenType; return(token); }
public void Can_Deserialize_AccessToken() { string content = SampleDataHelper.GetContent("AccessToken.json"); JsonDotNetSerializer deserializer = new JsonDotNetSerializer(); OAuth2AccessToken result = deserializer.Deserialize <OAuth2AccessToken>(content); Validate(result); }
public void AccessToken_With_No_Expiration_Time_Throws_On_IsFresh() { //arrenge var fixture = new Fixture(); //Create a token with no Expiration time var sut = new OAuth2AccessToken(); Assert.Throws <InvalidOperationException>(() => sut.IsFresh()); }
/* * public string TestTimeSeries() * { * FitbitClient client = GetFitbitClient(); * * var results = client.GetTimeSeries(TimeSeriesResourceType.DistanceTracker, DateTime.UtcNow.AddDays(-7), DateTime.UtcNow); * * string sOutput = ""; * foreach (var result in results.DataList) * { * sOutput += result.DateTime.ToString() + " - " + result.Value.ToString(); * } * * return sOutput; * * } * * public ActionResult LastWeekDistance() * { * FitbitClient client = GetFitbitClient(); * * TimeSeriesDataList results = client.GetTimeSeries(TimeSeriesResourceType.Distance, DateTime.UtcNow.AddDays(-7), DateTime.UtcNow); * * return View(results); * } */ public async Task <ActionResult> LastWeekSteps() { OAuth2AccessToken accessToken = (OAuth2AccessToken)Session["AccessToken"]; FitbitClient client = GetFitbitClient(accessToken.Token, accessToken.RefreshToken); FitbitResponse <TimeSeriesDataListInt> response = await client.GetTimeSeriesIntAsync(TimeSeriesResourceType.Steps, DateTime.UtcNow.AddDays(-7), DateTime.UtcNow); return(View(response.Data)); }
/// <summary> /// Store Fitbit token details against user /// </summary> /// <param name="accessToken"></param> private void StoreFitbitToken(OAuth2AccessToken accessToken) { FitbitUser fitbitUser = _unitOfWork.Metrics.GetFitbitUser(_userId); fitbitUser.FitbitUserId = accessToken.UserId; fitbitUser.RefreshToken = accessToken.RefreshToken; fitbitUser.Token = accessToken.Token; fitbitUser.TokenType = accessToken.TokenType; _unitOfWork.Complete(); }
public void Validate(OAuth2AccessToken token) { token.Should().NotBeNull(); token.Token.Should().Be("eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0MzAzNDM3MzUsInNjb3BlcyI6Indwcm8gd2xvYyB3bnV0IHdzbGUgd3NldCB3aHIgd3dlaSB3YWN0IHdzb2MiLCJzdWIiOiJBQkNERUYiLCJhdWQiOiJJSktMTU4iLCJpc3MiOiJGaXRiaXQiLCJ0eXAiOiJhY2Nlc3NfdG9rZW4iLCJpYXQiOjE0MzAzNDAxMzV9.z0VHrIEzjsBnjiNMBey6wtu26yHTnSWz_qlqoEpUlpc"); token.TokenType.Should().Be("Bearer"); token.ExpiresIn.Should().Be(3600); token.RefreshToken.Should().Be("c643a63c072f0f05478e9d18b991db80ef6061e4f8e6c822d83fed53e5fafdd7"); token.UserId.Should().Be("26FWFL"); token.Scope.Should().Be("heartrate weight nutrition settings activity sleep"); }
public void AccessToken_Knows_Token_Is_Stale() { //arrenge Fixture fixture = new Fixture(); //Create a token whose expiration date is in the future OAuth2AccessToken tokenWithFutureExpirationDate = fixture.Build <OAuth2AccessToken>() .With(t => t.UtcExpirationDate, DateTime.UtcNow.AddHours(-1.0)) .Create(); Assert.IsFalse(tokenWithFutureExpirationDate.IsFresh()); }
public async Task <string> GetAccessToken() { if (_oAuth2AccessToken != null && !_oAuth2AccessToken.IsExpired) { return(_oAuth2AccessToken.AccessToken); } _oAuth2AccessToken = await GetNewAccessTokenAsync().ConfigureAwait(false); return(_oAuth2AccessToken.AccessToken); }
internal static FitbitUser Create(string userId, OAuth2AccessToken accessToken) { FitbitUser u = new FitbitUser(); u.UserId = userId; u.FitbitUserId = accessToken.UserId; u.RefreshToken = accessToken.RefreshToken; u.Token = accessToken.Token; u.TokenType = accessToken.TokenType; return(u); }
public async Task <ActionResult> Callback(string code) { var authenticator = new OAuth2Helper(_appCredentials, ConfigurationManager.AppSettings["BaseUrl"] + "/band/callback"); OAuth2AccessToken accessToken = await authenticator.ExchangeAuthCodeForAccessTokenAsync(code); if (!string.IsNullOrEmpty(accessToken.Token)) { _bandClient = GetBandClient(accessToken); } return(RedirectToAction("Profile")); }
//Final step. Take this authorization information and use it in the app /// <summary> /// Part 2 of authorisation. User has (hopefully) accepted request and fitbit passed authorisation code. /// </summary> /// <returns></returns> public async Task <ActionResult> Callback() { FitbitAppCredentials appCredentials = FitbitHelper.GetFitbitAppCredentials(); var authenticator = new OAuth2Helper(appCredentials, Request.Url.GetLeftPart(UriPartial.Authority) + "/Fitbit/Callback"); string code = Request.Params["code"]; // ask for access token. OAuth2AccessToken accessToken = await authenticator.ExchangeAuthCodeForAccessTokenAsync(code); // save token (user may have previously authorised in which case update) FitbitHelper.AddOrUpdateUser(_unitOfWork, User.Identity.GetUserId(), accessToken); return(View("Home", PopulateModel())); }
public ActionResult Refresh(string clientName, string accessToken, string refreshToken) { AccessToken token = accessToken; if (!String.IsNullOrEmpty(refreshToken)) { token = new OAuth2AccessToken(accessToken, refreshToken); } var result = OAuthManager.RegisteredClients[clientName].RefreshToken(token); return(new ContentResult { Content = result.ToString(), ContentType = "text/plain" }); }
/// <summary> /// HttpClient and hence FitbitClient are designed to be long-lived for the duration of the session. This method ensures only one client is created for the duration of the session. /// More info at: http://stackoverflow.com/questions/22560971/what-is-the-overhead-of-creating-a-new-httpclient-per-call-in-a-webapi-client /// </summary> /// <returns></returns> private BandClient GetBandClient(OAuth2AccessToken accessToken = null) { if (Session["BandClient"] == null) { if (accessToken != null) { BandClient client = new BandClient(_appCredentials, accessToken); Session["BandClient"] = client; return(client); } //throw new Exception("First time requesting a BandClient from the session you must pass the AccessToken."); return(null); } return((BandClient)Session["BandClient"]); }
public void Most_Basic() { var credentials = new FitbitAppCredentials() { ClientId = "SomeID", ClientSecret = "THE Secret ;)" }; var accessToken = new OAuth2AccessToken() { Token = "", TokenType = "", ExpiresIn = 3600, RefreshToken = "" }; var sut = new FitbitClient(credentials, accessToken); Assert.IsNotNull(sut.HttpClient); }
public void Can_Instantiate_Without_Any_Interceptors() { var credentials = new FitbitAppCredentials() { ClientId = "SomeID", ClientSecret = "THE Secret ;)" }; var accessToken = new OAuth2AccessToken() { Token = "", TokenType = "", ExpiresIn = 3600, RefreshToken = "" }; //Ensure not even the auto-token-refresh interceptor is active var sut = new FitbitClient(credentials, accessToken, false); Assert.IsNotNull(sut.HttpClient); }
public void Can_Use_Interceptors_Without_Autorefresh() { var credentials = new FitbitAppCredentials() { ClientId = "SomeID", ClientSecret = "THE Secret ;)" }; var accessToken = new OAuth2AccessToken() { Token = "", TokenType = "", ExpiresIn = 3600, RefreshToken = "" }; //Registere an interceptor, but disable the auto-token-refresh interceptor var sut = new FitbitClient(credentials, accessToken, new InterceptorCounter(), false); Assert.IsNotNull(sut.HttpClient); }
private void Load() { try { OAuth2Helper authenticator = new OAuth2Helper("227H9T", "74e4a047fce979dd36a0edbd626c3939", "http://Miriot.suismoi.fr"); string[] scopes = new[] { "profile", "weight" }; string authUrl = authenticator.GenerateAuthUrl(scopes, null); WebView browser = new WebView(); browser.Height = 300; browser.Width = 300; browser.Source = new Uri(authUrl); browser.DefaultBackgroundColor = Colors.Black; MainGrid.Children.Add(browser); browser.NavigationStarting += async(s, args) => { if (args.Uri.OriginalString.Contains("code=")) { var code = args.Uri.Query.Replace("?code=", ""); AccessToken = await authenticator.ExchangeAuthCodeForAccessTokenAsync(code); AccessToken = await authenticator.RefreshToken(AccessToken.RefreshToken); MainGrid.Children.Remove(browser); try { var w = await GetWeightAsync(DateTime.Now, null); Value.Text = $"{w.Weight.First().Weight}kg"; } catch (Exception ex) { // Access denied ? Debug.WriteLine(ex.Message); } } }; } catch (Exception ex) { // Something went wrong Debug.WriteLine(ex.Message); } }
public async Task <IHttpActionResult> RegistrationResult(string code) { FitbitAppCredentials appCredentials = (FitbitAppCredentials)session[AppCredentials]; var authenticator = new OAuth2Helper(appCredentials, $"{Request.RequestUri.GetLeftPart(UriPartial.Authority)}/fitbit/{nameof(RegistrationResult).ToLowerInvariant()}"); OAuth2AccessToken accessToken = await authenticator.ExchangeAuthCodeForAccessTokenAsync(code); // Store credentials in FitbitClient. The client in its default implementation manages the Refresh process var fitbitClient = GetFitbitClient(accessToken); // register a subscription for the authorized user // TODO: Remove hardcoded subscriber id -- should be the equivalent of our user id await fitbitClient.AddSubscriptionAsync(APICollectionType.user, "123456789"); return(Ok()); }
//Final step. Take this authorization information and use it in the app public async Task <ActionResult> Callback() { FitbitAppCredentials appCredentials = (FitbitAppCredentials)Session["AppCredentials"]; var authenticator = new OAuth2Helper(appCredentials, Request.Url.GetLeftPart(UriPartial.Authority) + "/Fitbit/Callback"); string code = Request.Params["code"]; OAuth2AccessToken accessToken = await authenticator.ExchangeAuthCodeForAccessTokenAsync(code); //Store credentials in FitbitClient. The client in its default implementation manages the Refresh process var fitbitClient = GetFitbitClient(accessToken); ViewBag.AccessToken = accessToken; return(View()); }
/// <summary> /// Sends a request to refresh the access token. /// </summary> /// <param name="accessToken">May contain an access token, which should be refreshed.</param> /// <remarks> /// <para>If <paramref name="accessToken"/> parameter is not specified, it will use the current access token from the same property of the current class instance.</para> /// <para>Token must contain the <b>refresh_token</b>, which was received together with the access token.</para> /// </remarks> /// <exception cref="NotSupportedException"> /// <para>Provider does not support refreshing the access token, or the method is not implemented.</para> /// <para>Use the property <see cref="OAuthBase.SupportRefreshToken"/>, to check the possibility of calling this method.</para> /// </exception> /// <exception cref="AccessTokenException"> /// <para>Access token is not found or is not specified.</para> /// <para>-or-</para> /// <para><b>refresh_token</b> value is empty.</para> /// </exception> /// <exception cref="RequestException">Error during execution of a web request.</exception> public override AccessToken RefreshToken(AccessToken accessToken = null) { var token = (OAuth2AccessToken)base.GetSpecifiedTokenOrCurrent(accessToken, refreshTokenRequired: true); // fix: требуют bearer, но в этом запросе bearer не поддерживают token = new OAuth2AccessToken(token.Value, token.RefreshToken, ""); var parameters = new NameValueCollection { { "client_id", this.ApplicationId }, { "client_secret", this.ApplicationSecret }, { "grant_type", GrantType.RefreshToken }, { "refresh_token", token.RefreshToken } }; var result = OAuthUtility.Post ( "https://appsmail.ru/oauth/token", parameters: parameters, accessToken: token ); return new OAuth2AccessToken(result); }
/// <summary> /// Gets the user details. /// </summary> /// <param name="accessToken">May contain an access token, which will have to be used in obtaining information about the user.</param> /// <returns> /// <para>Returns an instance of the <see cref="UserInfo"/> class, containing information about the user.</para> /// </returns> public override UserInfo GetUserInfo(AccessToken accessToken = null) { // api documentation: // https://developer.linkedin.com/apis // https://developer.linkedin.com/documents/profile-api // https://developer.linkedin.com/documents/profile-fields accessToken = base.GetSpecifiedTokenOrCurrent(accessToken); // fix: server does not return token type, but requires Bearer accessToken = new OAuth2AccessToken ( accessToken.Value, ((OAuth2AccessToken)accessToken).RefreshToken, AccessTokenType.Bearer ); // execute the request var result = OAuthUtility.Get ( endpoint: "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,picture-url,email-address)", accessToken: accessToken, headers: new NameValueCollection { { "x-li-format", "json" } } ); // field mapping var map = new ApiDataMapping(); map.Add("id", "UserId", typeof(string)); map.Add("firstName", "FirstName"); map.Add("lastName", "LastName"); map.Add("pictureUrl", "Userpic"); map.Add("emailAddress", "Email"); // parse the server response and returns the UserInfo instance return new UserInfo(result, map); }