working on it ...

Filters

Explore Public Snippets

Sort by

Found 42 snippets matching: accesstoken

    public by cghersi  5835  1  8  3

    How to retrieve GMail contacts via API, using OAuth2 token and not username/password credentials

    This class takes charge of the interaction with Google Contacts API, authenticating with an AccessToken authorization flow. In this way the final user should type the credentials in the Google form and not in your form. The "token" parameter of GetContacts() method is the one sent by Google to the callback url specified in the static constant "s_
    using System;
    using System.Linq;
    using System.Collections.Generic;
    using Google.Contacts;
    using Google.GData.Contacts;
    using Google.GData.Client;
    using Google.GData.Extensions;
    
    namespace Contact.Utils
    {
      /// <summary>
      /// Summary description for GmailHelper
      /// </summary>
      public class GmailHelper
      {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    
        private static fastJSON.JSON jsonUtils = EntityUtils.InitJSONUtils();
    
        private static readonly string APP_NAME = "my app name";
        private static readonly string s_ClientId = "client id given by Google";
        private static readonly string s_ClientSecret = "secret given by Google;
        private static readonly string s_accessTokenUrl = "https://accounts.google.com/o/oauth2/token";
        private static readonly string s_redirUri = WebConfig.Current.PublicPath + "User/GmailCallback";
    
        #region PUBLIC API
        //////////////////////////////////////////////////////////////////////////////////////////////////////
    
        public static string GetRedirUriForContacts()
        {
          return string.Format("https://accounts.google.com/o/oauth2/auth?scope=https://www.google.com/m8/feeds&redirect_uri={0}&response_type=code&client_id={1}",
            s_redirUri, s_ClientId);
        }
    
        public static List<SimpleContact> GetContacts(string token)
        {
          List<SimpleContact> results = new List<SimpleContact>();
    
          //exchange the code for a token:
          string postData = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code",
            token, s_ClientId, s_ClientSecret, s_redirUri);
          string accessTokenResp = Utilities.SendHttpRequest(s_accessTokenUrl, postData, true);
          if (string.IsNullOrEmpty(accessTokenResp))
            return results;
    
          AccessTokenStruct parsedJson = null;
          try
          {
            parsedJson = jsonUtils.ToObject<AccessTokenStruct>(accessTokenResp); 
          }
          catch (Exception e)
          {
            log.ErrorFormat("Cannot deserialize access token response: '{0}' due to {1}", accessTokenResp, e.Message);
            return results;
          }
          if (parsedJson == null)
            return results;
    
          //ask for contacts:
          RequestSettings settings = new RequestSettings(APP_NAME, parsedJson.access_token); 
          settings.AutoPaging = true;
          ContactsRequest cr = new ContactsRequest(settings);
          Feed<Contact> contactsFeed = cr.GetContacts();
          IEnumerable<Contact> contacts = null;
          if (contactsFeed != null)
            contacts = contactsFeed.Entries;
          if (contacts == null)
            return results;
    
          try
          {
            foreach (SimpleContact c in contacts)
            {
              if (c.PrimaryEmail == null)
                continue;
              string preferredEmail = c.PrimaryEmail.Address;
              if (string.IsNullOrEmpty(preferredEmail))
                continue;
              string[] otherEmails = null;
              if (c.Emails != null)
                otherEmails = c.Emails.Select(e => e.Address).ToArray();
              S2CContact contact = new S2CContact((c.Name == null ? "" : c.Name.FullName), 
                                                  preferredEmail, otherEmails);
              results.Add(contact);
            }
          }
          catch (Exception e)
          {
            log.ErrorFormat("Cannot retrieve contacts due to {0}", e.Message);
            return results;
          }
    
          return results;
        }
    
        #endregion
        //////////////////////////////////////////////////////////////////////////////////////////////////////
      }
    
      public class AccessTokenStruct
      {
        public string access_token { get; set; }
        public int expires_in { get; set; }
        public string token_type { get; set; }
    
        public AccessTokenStruct() { }
      }
    
      public class SimpleContact
      {
        public string PreferredEmail { get; set; }
        public string Name { get; set; }
        public string[] Emails { get; set; }
    
        public SimpleContact(string name, string preferredEmail, string[] emails = null)
        {
          Name = name;
          PreferredEmail = preferredEmail;
          if (emails == null)
            Emails = new string[] { preferredEmail };
          else
          {
            List<string> allEmails = new List<string>(emails);
            allEmails.Add(preferredEmail);
            Emails = allEmails.Distinct().ToArray();
          }
        }
    
        public override string ToString()
        {
          if (string.IsNullOrEmpty(Name))
            return PreferredEmail;
          else
            return string.Format("{0} [{1}]", Name, PreferredEmail);
        }
      }
    
    }            

    public by msdn  4888  8  7  0

    GetClientContextWithAccessToken: Uses the specified access token to create a client context

    Uses the specified access token to create a client context Url of the target SharePoint site Access token to be used when calling the specified targetUrl A ClientContext ready to call targetUrl with the specified access token
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Collections.ObjectModel;
    using System.Globalization;
    using System.IdentityModel.Selectors;
    using System.IdentityModel.Tokens;
    using System.IO;
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    using System.Security.Principal;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    using System.Text;
    using System.Web.Configuration;
    using System.Web.Script.Serialization;
    using Microsoft.IdentityModel;
    using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
    using Microsoft.IdentityModel.S2S.Tokens;
    using Microsoft.SharePoint.Client;
    using Microsoft.SharePoint.Client.EventReceivers;
    
    /// <summary>
    /// Uses the specified access token to create a client context
    /// </summary>
    /// <param name="targetUrl">Url of the target SharePoint site</param>
    /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
    /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
    public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
    {
        Uri targetUri = new Uri(targetUrl);
    
        ClientContext clientContext = new ClientContext(targetUrl);
    
        clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
        clientContext.FormDigestHandlingEnabled = false;
        clientContext.ExecutingWebRequest +=
            delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
            {
                webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
                    "Bearer " + accessToken;
            };
    
        return clientContext;
    }

    public by msdn  2381  1  6  0

    RenewAccessTokenIfNeeded: Renews the access token if it is not valid.

    Renews the access token if it is not valid. The access token to renew. The token renewal handler.
    using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
    using Microsoft.IdentityModel.Tokens;
    using Microsoft.SharePoint.Client;
    using System;
    using System.Net;
    using System.Security.Principal;
    using System.Web;
    using System.Web.Configuration;
    
    /// <summary>
    /// Renews the access token if it is not valid.
    /// </summary>
    /// <param name="accessToken">The access token to renew.</param>
    /// <param name="tokenRenewalHandler">The token renewal handler.</param>
    private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
    {
        if (IsAccessTokenValid(accessToken))
        {
            return;
        }
    
        DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
    
        if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
        {
            // Make the access token get renewed a bit earlier than the time when it expires
            // so that the calls to SharePoint with it will have enough time to complete successfully.
            expiresOn -= AccessTokenLifetimeTolerance;
        }
    
        accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
    }

    public by msdn  1701  1  6  0

    CreateClientContext: Creates a ClientContext with the specified SharePoint site url and the access token.

    Creates a ClientContext with the specified SharePoint site url and the access token. The site url. The access token. A ClientContext instance.
    using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
    using Microsoft.IdentityModel.Tokens;
    using Microsoft.SharePoint.Client;
    using System;
    using System.Net;
    using System.Security.Principal;
    using System.Web;
    using System.Web.Configuration;
    
    /// <summary>
    /// Creates a ClientContext with the specified SharePoint site url and the access token.
    /// </summary>
    /// <param name="spSiteUrl">The site url.</param>
    /// <param name="accessToken">The access token.</param>
    /// <returns>A ClientContext instance.</returns>
    private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
    {
        if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
        {
            return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
        }
    
        return null;
    }

    public by msdn  1451  0  6  0

    IsAccessTokenValid: Determines if the specified access token is valid. It considers an access token as not valid if it is null, or it has expired.

    Determines if the specified access token is valid. It considers an access token as not valid if it is null, or it has expired. The access token to verify. True if the access token is valid.
    using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
    using Microsoft.IdentityModel.Tokens;
    using Microsoft.SharePoint.Client;
    using System;
    using System.Net;
    using System.Security.Principal;
    using System.Web;
    using System.Web.Configuration;
    
    /// <summary>
    /// Determines if the specified access token is valid.
    /// It considers an access token as not valid if it is null, or it has expired.
    /// </summary>
    /// <param name="accessToken">The access token to verify.</param>
    /// <returns>True if the access token is valid.</returns>
    protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
    {
        return accessToken != null &&
               !string.IsNullOrEmpty(accessToken.Item1) &&
               accessToken.Item2 > DateTime.UtcNow;
    }

    public by msdn  1368  0  6  0

    GetAccessTokenString: Ensures the access token is valid and returns it.

    Ensures the access token is valid and returns it. The access token to verify. The token renewal handler. The access token string.
    using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
    using Microsoft.IdentityModel.Tokens;
    using Microsoft.SharePoint.Client;
    using System;
    using System.Net;
    using System.Security.Principal;
    using System.Web;
    using System.Web.Configuration;
    
    /// <summary>
    /// Ensures the access token is valid and returns it.
    /// </summary>
    /// <param name="accessToken">The access token to verify.</param>
    /// <param name="tokenRenewalHandler">The token renewal handler.</param>
    /// <returns>The access token string.</returns>
    private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
    {
        RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
    
        return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
    }

    public by msdn  1367  0  6  0

    IsAccessTokenValid: Determines if the specified access token is valid. It considers an access token as not valid if it is null, or it has expired.

    Determines if the specified access token is valid. It considers an access token as not valid if it is null, or it has expired. The access token to verify. True if the access token is valid.
    using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
    using Microsoft.IdentityModel.Tokens;
    using Microsoft.SharePoint.Client;
    using System;
    using System.Net;
    using System.Security.Principal;
    using System.Web;
    using System.Web.Configuration;
    
    /// <summary>
    /// Determines if the specified access token is valid.
    /// It considers an access token as not valid if it is null, or it has expired.
    /// </summary>
    /// <param name="accessToken">The access token to verify.</param>
    /// <returns>True if the access token is valid.</returns>
    protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
    {
        return accessToken != null &&
               !string.IsNullOrEmpty(accessToken.Item1) &&
               accessToken.Item2 > DateTime.UtcNow;
    }

    external by Stuart Leeks  2831  18  3  0

    Hack to get AccessToken for ARM from current PowerShell context

    Hack to get AccessToken for ARM from current PowerShell context: AzureRmAuth.ps1
    # Working on 1.0.0 preview of Azure PowerShell cmdlets
    function GetAccessToken(){
        $psContext = Get-AzureRmContext
    
        $context = [Microsoft.Azure.Common.Authentication.Models.AzureContext] $psContext
        $account = $context.Account
        $environment=  $context.Environment
        $tenant = $context.Tenant
    
        $authFactory = [Microsoft.Azure.Common.Authentication.AzureSession]::AuthenticationFactory
    
        $accessToken = $authFactory.Authenticate($account, $environment, $tenant.Id, $null, "Never")
    
        return $accessToken.AccessToken
    }
    function GetAuthorizationHeader(){
        $token = GetAccessToken
        return @{ "Authorization" = "Bearer $token"}
    }
    
    
    function GetSubscriptions(){
        $uri = "https://management.azure.com/subscriptions?api-version=2014-04-01"
        $headers = GetAuthorizationHeader
        $response1 = Invoke-RestMethod -Method Get -Uri $uri -Headers $headers
        $response1.value
    }
    function GetResourceGroups($subscriptionId){
        $uri = "https://management.azure.com/subscriptions/$subscriptionId/resourceGroups?api-version=2014-04-01"
        $headers = GetAuthorizationHeader
        $response1 = Invoke-RestMethod -Method Get -Uri $uri -Headers $headers
        $response1.value
    }
    
    
    $subscriptions = GetSubscriptions
    $subscriptions
    
    Write-Host ""
    
    $resourceGroups = GetResourceGroups $subscriptions[0].subscriptionId
    $resourceGroups
    
    
    

    external by thanhcs94  35  0  1  0

    get accesstoken ,sigin google plus

    get accesstoken ,sigin google plus: googlesignin_getaccestoken.java
    package com.google.devrel.samples.gmstest.app;
    
    import android.app.Activity;
    import android.content.Intent;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.TextView;
    
    import com.google.android.gms.auth.GoogleAuthException;
    import com.google.android.gms.auth.GoogleAuthUtil;
    import com.google.android.gms.auth.UserRecoverableAuthException;
    import com.google.android.gms.plus.Account;
    import com.google.android.gms.plus.Plus;
    
    import java.io.IOException;
    
    
    public class RetrieveAccessTokenActivity extends Activity implements View.OnClickListener {
    
        private static final String TAG = "RetrieveAccessToken";
        private static final int REQ_SIGN_IN_REQUIRED = 55664;
    
        private String mAccountName;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_retrieve_access_token);
            findViewById(R.id.button_token).setOnClickListener(this);
    
            // Manual integration? Pop an account chooser to get this:
            mAccountName = "me@example.com";
            // Or if you have a GoogleApiClient connected:
            // mAccountName = Plus.AccountApi.getAccountName(mGoogleApiClient);
        }
    
        @Override
        public void onClick(View view) {
            if (view.getId() == R.id.button_token) {
                new RetrieveTokenTask().execute(mAccountName);
            }
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (requestCode == REQ_SIGN_IN_REQUIRED && resultCode == RESULT_OK) {
                // We had to sign in - now we can finish off the token request.
                new RetrieveTokenTask().execute(mAccountName);
            }
        }
    
        private class RetrieveTokenTask extends AsyncTask<String, Void, String> {
    
            @Override
            protected String doInBackground(String... params) {
                String accountName = params[0];
                String scopes = "oauth2:profile email";
                String token = null;
                try {
                    token = GoogleAuthUtil.getToken(getApplicationContext(), accountName, scopes);
                } catch (IOException e) {
                    Log.e(TAG, e.getMessage());
                } catch (UserRecoverableAuthException e) {
                    startActivityForResult(e.getIntent(), REQ_SIGN_IN_REQUIRED);
                } catch (GoogleAuthException e) {
                    Log.e(TAG, e.getMessage());
                }
                return token;
            }
    
            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                ((TextView) findViewById(R.id.token_value)).setText("Token Value: " + s);
            }
        }
    }
    
    

    external by Simon (Big Chief) Morley  11  0  1  0

    Medium, creating a google+ splash page, accessToken helper adjustment

    Medium, creating a google+ splash page, accessToken helper adjustment: gistfile1.js
    var formatAuthResponse = function() {
      if ($scope.authResponse.member_id !== undefined) {
        auth.accessToken = $scope.authResponse.access_token;
        auth.memberId = $scope.memberId;
      } else if ($scope.authResponse.userID !== undefined) {
        auth.accessToken = $scope.authResponse.accessToken;
        auth.userID = $scope.authResponse.userID;
        auth.expires = $scope.authResponse.expires;
      } else if ($scope.authResponse.client_id !== undefined) {
        auth.accessToken = $scope.authResponse.access_token;
        auth.clientID = $scope.authResponse.client_id;
      }
    };
    
    
    
    • Public Snippets
    • Channels Snippets