Friday, 27 March 2015

SharePoint Online (O365) OAuth Authentication | Authorizing REST API calls against SharePoint Online Site | Get Access token from SharePoint Online | Set up OAuth for SharePoint Online Office 365

Here is my most awaited post on how to set up OAuth for SharePoint Online so that we can authorize REST API calls to the SharePoint site to retrieve data and manipulate the site data.

The steps going to be easy and I will demonstrate along with screenshots and examples with the Google PostMan RESTClient.

I have explained the steps below which follows the OAuth 2.0 protocol. All the steps are straight forward, but constructing the URLs are little tricky!

Below are the detailed steps:
1. Register an app in SharePoint

·         Click Generate for Client Id and Client Secret.
·         Give a name for the app, fill in the app domain (ex:, Enter the Redirect URL, important here is when entering redirect url, it should be https and this is the url, to which the site redirects once you authorize your app and get auth.code (which will be explained later).
·         Click Create.
·         (Imp!) Note down the Client Id, Client Secret and redirect_uri.
Fill in the details:

        2. Get the Realm of your site.
Realm is a constant GUID for a site. Save this realm for future use. Follow below steps to get the realm:
·         Download Google Postmanpackaged app.
·         Install and launch it.
·         Make a Get request as shown in the screenshot:
Authorization: Bearer
·         Get the Bearer realm component from the response header and save it.

  3.   Get the Authorization code from Azure Access Control Service
Construct the authorization url as follows:

As the example show, we need to send OAuth client Id and redirect URI to the SharePoint site as query string parameters. The following is an example of the GET request with sample query string values. Line breaks have been added for clarity. The actual target URL is a single line.
?client_id= d1a20424-c89d-4195-a29e-cf5796d90dd6

·         Client id is the client Id which we have got while registering the app in step. 1 above.
·         Scope which describes the Scope and the Right to be granted for the app.
This parameter is a space-delimited set of permission scope and right requests. (ex: we can also have scope=Web.Read List.Write)

Scope URI
Scope Alias
Available Rights
Read, Write, Manage
Read, Write, Manage
Read, Write, Manage
All Sites
Read, Write, Manage

The table above describes the Scope URI, Scope Alias and the Right. The values listed in the Scope Alias column are shorthand versions of their counterparts in the Scope URI column. For more info on this please refer Understand permission scope aliases and the use of the OAuthAuthorize.aspx page.
·         response_type =code (in order to get the auth.code).
·         redirect_uri    redirect url. Must be same as the redirect url given in step. 1. Note that this url is encoded.

Now the full url will be as follows:
Now, navigate to this url from your browser, login to the site if you have not logged in already.
Opens a consent page prompts the user to grant (or deny) the app the permissions that the app requests. In this case, the user would be granting the app read access to the current Site (Web).

Once you grant the permission (by clicking trust), SharePoint Online site asks ACS to create a short-lived (approximately 5 minutes) authorization code unique to this combination of user and app. ACS sends the authorization code to the SharePoint site.

SharePoint Online site redirects the browser back to the redirect URI that was specified when the app was registered in step.1. It also includes the authorization code as a query string. The redirect URL is structured like the following:

Extract query string value code from above url and it will be used in next step. This is the authorization code and it lasts for approx. 5 minutes!

    4.    Get the access token and refresh token:
What..? Yes! We are in final step to get the access token. In this step I will demonstrate how to get access token and refresh token from Google Postman.

Construct the below post request:<site_realm>/tokens/OAuth/2
Post parameters:
&resource=< audience principal ID>/<site_host>@<site_realm>

As the above structure show, we need to send OAuth client Id, client secret, auth code, redirect URI and resource to the SharePoint site as post body. The following is an example of the POST request with sample values. Line breaks have been added for clarity.
Also observe that I have encoded all the values.

Post parameters:
&code=<paste the long auth.code from previous step here>

·         Grant_type authorization_code (in order to get access token and refresh token).
·         client_id <client id from step1>@<site realm from step2>.
·         client_secret <client secret code from step1>.
·         Code <auth.code from previous step).
·         redirect_uri <redirect url from step1>
·         resource <audience principal ID>/<sharepoint domain>@<site realm>.
audience principal ID is a permanent security principal ID for SharePoint

Google Postman demonstration:
            Open Google Postman and press Alt+n for a new request. Note that it is a POST request.

Follow my screenshot below. Fill the post parameters similar to the example above, replace the value accordingly. Also keep in mind that the auth.code lasts for only 5 minutes. After 5 minutes, you can generate the fresh auth.code by following the step 3 again! Please save the access token and refresh token safely. 

Fill in the values:


     5.    Get access token if  it is expired by using refresh token:
Last but not the least, once you have access code, you can make use of powerful SharePoint 2013 REST APIs. But access code has a validity of 12 hours. So after 12 hours access code will get expired and you will need to get a new access token again!

Don’t panic! J You don’t need to follow all the steps againJ. You can make use of the refresh token and get a fresh access token again.

Here is how you get a new access token using refresh token:
This step is almost similar to step 4, except 2 differences. Here the difference is that we use:
·         grant_type as refresh_token and
·         refresh_token instead of code in step4 and use the refresh token which we have saved in step4.

Post parameters:
grant_type= refresh_token
&refresh_token =<refresh_token_from_step_4>
&resource=< audience principal ID>/<site_host>@<site_realm>

Note that it is a POST request.
Check out my Postman screenshot below:
Fill in the values:


Save the refresh token, which is valid for next 12 hours.

Auth. Code: about 5 minutes.
Access token: 12 hours.
Refresh token: 6 months.

OK J what next?!
Use access token to make REST calls to your SharePoint site.

Read my posts related to SharePoint 2013 REST APIs:

Cheers :) :) :) 
Comment below if have any difficulties :) 
Thank you for you time .

If this post was helpful to you, please consider visiting one or more advertisements on the page.Writing detailed post takes time, patience and advertising revenue helps to offset the effort.

Tuesday, 3 March 2015

JQery helper methods

In this post I am gonna give you some of the JQuery helper methods which I am using in my application frequently. Below are some of them , with explanation:


Copy all the codes given at the end of this post to a js  file and add a reference of it to your page.
Or Click here to download the file

1. Remove Special Characters from a string:
var str="Hello%how%are$you";
output: Hellohowareyou

2. Trim from left:
var str="%hello";
Output: hello

3. Trim from right:
var str="hello%";
Output: hello

4. String Contains:
var str="welcome to SPShell. The SharePoint blog";
Output: true

5. IsUndefined.
var undefinedVar;
Output: true

6. isIEBrowser (check is browser is IE)

Output: false (my browser is chrome when I excecuted this code) .

7. checkChrome
 Output: true(my browser is chrome when I excecuted this code) .

8. getQueryStrings

Now here my URL was:
Output : (a javascript object)
                {q: "sharepoint", state: "active", live: "true"}

9. IsValidEmail
 Output: true.

Here is the Source Code (js):
You can also download this code here.
String.prototype.removeSplChars = function () {
    return this.replace(/[^a-zA-Z0-9 ]/g, "");
String.prototype.trimStart = function (c) {
    if (this.length == 0)
        return this;
    c = c ? c : ' ';
    var i = 0;
    var val = 0;
    for (; this.charAt(i) == c && i < this.length; i++);
    return this.substring(i);
String.prototype.trimEnd = function (c) {
    c = c ? c : ' ';
    var i = this.length - 1;
    for (; i >= 0 && this.charAt(i) == c; i--);
    return this.substring(0, i + 1);
String.prototype.contains = function(it) { return this.indexOf(it) != -1; };
function IsUndefined(value) {
    if (typeof value == 'undefined') {
        return true;
    else if (value == null) {
        return true;
    else return false;
function getInternetExplorerVersion() {
    var rv = -1;
    if (navigator.appName == 'Microsoft Internet Explorer') {
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            rv = parseFloat(RegExp.$1);
    else if (navigator.appName == 'Netscape') {
        var ua = navigator.userAgent;
        var re = new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            rv = parseFloat(RegExp.$1);
    return rv;
function isIEBrowser() {
    if (getInternetExplorerVersion() > -1) {
        return true;
    else return false;
function checkChrome() {
    var isChromium =,
    vendorName = window.navigator.vendor;
    if (isChromium !== null && isChromium !== undefined && vendorName === "Google Inc.")
        return true;    // is chrome
    else       // not  chrome
        return false;
function getQueryStrings() {
    var assoc = {};
    var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
    var queryString =;
    var keyValues = queryString.split('&');
    for (var i in keyValues) {
        var key = keyValues[i].split('=');
        if (key.length > 1) {
            assoc[decode(key[0])] = decode(key[1]);
    return assoc;
function IsValidEmail(email) {
    if (!IsUndefined(email)) {
        var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        return regex.test(email);
    else return false;
Hope it helped you :)