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:
·
Click Generate for Client
Id and Client Secret.
·
Give a name for the app,
fill in the app domain (ex: www.google.com, www.salesforce.com). 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:
https://your_site.sharepoint.com/_layouts/15/OAuthAuthorize.aspx?client_id=client_GUID&scope=app_permissions_list&response_type=code&redirect_uri=redirect_uri
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.
https://your_site.sharepoint.com
/_layouts/oauthauthorize.aspx
?client_id= d1a20424-c89d-4195-a29e-cf5796d90dd6
&scope=Web.Read
&response_type=code
&redirect_uri=https%3A%2F%2Flocalhost%2F
/_layouts/oauthauthorize.aspx
?client_id= d1a20424-c89d-4195-a29e-cf5796d90dd6
&scope=Web.Read
&response_type=code
&redirect_uri=https%3A%2F%2Flocalhost%2F
Where:
·
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
|
http://sharepoint/content/sitecollection
|
Site
|
Read, Write, Manage
|
http://sharepoint/content/sitecollection/web
|
Web
|
Read, Write, Manage
|
http://sharepoint/content/sitecollection/web/list
|
List
|
Read, Write, Manage
|
http://sharepoint/content/tenant
|
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:
https://redirect_url/?code=<authcode>
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:
https://accounts.accesscontrol.windows.net/<site_realm>/tokens/OAuth/2
Post
parameters:
grant_type=authorization_code
&client_id=<client_id>@<site_realm>
&client_secret=<client_secret>
&code=<auth_code>
&redirect_uri=<redirect_url>
&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:
grant_type=authorization_code
&client_id=d1axxxx-xxxx-xxxx-xxxx-cf5796d90dd6%40d2076ad6-xxxx-xxxx-xxxx-24716a55ea90
&client_secret=RoYzG%2FAmf%2BaRrfNsdfdgLFsdfsxvMSHrj51BK4dUDqdB3%2BO4%3D
&code=<paste the long
auth.code from previous step here>
&redirect_uri=https%3A%2F%2Flocalhost%2F
&resource=00000003-0000-0ff1-ce00-000000000000%2Fyour_site_name.sharepoint.com%40d2076ad6-6179-41cb-b792-24716a55ea90
Where:
·
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:
Response:
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
&client_id=<client_id>@<site_realm>
&client_secret=<client_secret>
&refresh_token =<refresh_token_from_step_4>
&redirect_uri=<redirect_url>
&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:
Response:
Save
the refresh token, which is valid for next 12 hours.
Validity:
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 .
Hi, how can i call this all parameter in android.
ReplyDeleteChange redirect url
Deletestep 3 not working, says, auth error
DeleteHi, a little question :
ReplyDeleteAfter use your auth code to get Access token and Refresh token, I understand that you can use your Access token for 12 hours and then use your Refresh token to get a new Access token available 12 hours again.
But, when the refresh token become unavailable, after 6 months, how can you gain access to the API ?
You have to generate a new auth code to get a new Access token and a new Refresh token ?
Yes you need to repeat this step
Delete
ReplyDeleteInformative post. Thanks for sharing
Office 365
You're welcome!
DeleteCan this OAuth token be passed to a webUrl in an IFrame (e.g., to show the web-based excel viewer) without requiring sign-in?
ReplyDeleteOne Ask
ReplyDeleteWhat is localhost, if I have to use localhost, will I have to actually develop another app and host it somewhere and use it to validate code? If yes how? can you give more detail on redirect URI processing.
Localhost is nothing but your local computer. once you enable IIS in your computer, you can just type in http://localhost in your browser and it should display the default iis page.
DeleteHello my friend, I would like to get the token of sharepoint, because I redirect to external link, for example, in other aplication I don't need signin.
ReplyDeleteThanks
Create a page in your external application and write the mechanism to read the auth token from redirect query string
Deletecan i get format to use restapi in ajax calls. i got access token from postman but when I use it in ajax call i get forbidden erorr. same access token is owrking fine in postman.
ReplyDeleteThere is no change in the format. it is the same endpoint and JSON data.
DeleteSuper! Thanks alot!
ReplyDeleteSir, your blog helped me in 2017 and again I visited Today in Dec 2019. Thank you very much,
ReplyDeleteRegards,
Hitesh
You're welcome!
DeleteI have a problem with the resource parameter which is not part of the RFC specification and not taked in account by several framework how can I avoid or turn around the use of the resource Parameter
ReplyDeleteCheck out our video for the implementation of spring security with spring boot. This OAuth security video takes you through a simple application to generate OAuth tokens.
ReplyDeleteKnowledgeKafe.com is a world-class mediator connecting knowledge seekers with knowledge providers. We are actively involved in our efforts to make quality training courses and interesting events accessible and affordable for students and professionals in the region to enrol and attend.
ReplyDeleteHi Vikas,
ReplyDeletei am getting below error while trying to refresh the token
{
"error": "invalid_grant",
"error_description": "AADSTS70000: Provided grant is invalid or malformed.\r\nTrace ID: 14b75932-3ff8-4592-8c05-ba38cf3d3400\r\nCorrelation ID: cfc88fa8-ac3a-4056-9859-22eb051e1a53\r\nTimestamp: 2020-12-08 17:44:48Z",
"error_codes": [
70000
],
"timestamp": "2020-12-08 17:44:48Z",
"trace_id": "14b75932-3ff8-4592-8c05-ba38cf3d3400",
"correlation_id": "cfc88fa8-ac3a-4056-9859-22eb051e1a53",
"error_uri": "https://accounts.accesscontrol.windows.net/error?code=70000"
}
Please help that what's is wrong in passing the post parameters
Hi,
ReplyDeleteThis is very useful article and thank you very much. I followed every step and I was able to generate access-token. However,
when I was trying to access site data via REST API using access token, it threw below error,
"Access denied. You do not have permission to perform this action or access this resource"
Could you please let me know how this can be sorted out. And also I cannot find your next article regarding "Use access token to make REST calls to your SharePoint site".
Could you please share the link of that article?
This comment has been removed by the author.
ReplyDeleteHi,
ReplyDeletethis is very useful for me
How to use Sharepoint REST API used in android for login function?
Hello Vikas,
ReplyDeleteThank you for this useful blog. Could you please help me here.
Considering, we have 2 users in Sharepoint.
User A - an admin of Sharepoint Sites. Part of Team Site Owners group.
User B - a regular user of Sharepoint. Not part of any special group.
User A and User B both can log in to the Sharepoint browse through the sites and can open or create folders, and view, download, upload new documents to folders as well.
Now, trying to access Sharepoint via REST API, and authenticating the users, we are able to successfully Authenticate with User A, but when User B logs in via OAuth in our app, he could not complete the login, and in return received access_deined error as a result from OAuth authentication response. We found that User B is only allowed login via OAuth, when he is also added to the Team Site Owner group. Which does not make sense, as it means, every user who wants to access Sharepoint via REST API, need to be an Owner of the Site.
We need to understand why this change of behavior, for the same user, when accessing via Sharepoint Site directly and when using RESt API to authenticate to the same site?
Hello Vikas,
ReplyDeletethank you for sharing all these informations.
Is there way to do something like an "adminconsent", so that in the authorize step (.../_layouts/oauthauthorize.aspx?...) the consent dialog does not appear?
Thanks for any advice.
Went Airdrop to coin, token and cryptocurrency trading platform? WeNetwork.us is a future crypto payment gateway system. We believe in change & crypto is going to be world currency.
ReplyDeleteVisit here:- went token
WhitePaper Writing Services | | ERC20 Token Development Company | Altcoin Creation Services | Dxsale Clone Script |
ReplyDeleteWonderful Post!
ReplyDeleteRarible Clone |
OpenSea Clone |
Cointool App Clone |
Cryptopunks Clone |
Axie Infinity Clone |
Zed Run Clone |
Decentraland Clone |
Thanks for sharing the useful information.
ReplyDeleteRarible Clone |
OpenSea Clone |
Cointool App Clone |
Cryptopunks Clone |
Axie Infinity Clone |
Zed Run Clone |
Decentraland Clone |
Great Post!
ReplyDeleteTinyHero Clone |
NBA Top Shot Clone |
Solsea Clone |
Foundation Clone |
Sorare Clone |
MakerDAO Clone |
Thanks for sharing.
ReplyDeleteOpenSea Clone Script |
Cryptopunks Clone Script |
Sorare Clone Script |
Decentraland Clone Script |
Rarible Clone Script |
Cointool App Clone Script |
Axie Infinity Clone Script |
Zed Run Clone Script |
ICO Development Company
ReplyDeleteNFT Token Development Company |
| White Paper Writing Services |
NFT Game Development Company |
Cryptocurrency Development Services
Token Development Company |Smart Contract Development Company |
You can create a TRC20 or TRC721 Token through our Tron token development services and they will work seamlessly with their Ethereum counterparts.
ReplyDeleteThe Token Migration platform helps projects upgrade their old tokens to new tokens. In essence, if your old token has any flaws or if you want to add some additional features, you can create an entirely new token and users can swap their old tokens with your new tokens through the migration contract.
ReplyDeleteCreate your own DEX with like Uniswap our Uniswap clone script. Get decentralized exchange development from BlockchainX experts.Uniswap clone script
ReplyDeleteExcellent Post!
ReplyDeletePancakeSwap Clone Script |
OpenSea Clone Script |
BEP20 Token Development Company |
Decentraland Clone Script |
NFT Art Marketplace Development Company
NFT Marketplace Development Company |
NFT Marketplace Clone Script
Blockchain Game Development Company |
Smart Contract MLM Software Development Company |
NFT Music Marketplace Development Company |
The migration platform works similarly to a DEX without the Automated Market Maker system. The New or V2 tokens are stored inside the migration smart contract and users can simply connect their web3 wallets to trustlessly migrate their tokens.Token Migration
ReplyDeleteThanks for sharing the informational blog post. For more information on development of your very own DEX and SWAP platform visit Top Blockchain Development Company
ReplyDeleteQuest GLT- India’s Leading Software Consulting & Development Company
https://questglt.com
Fantastic, I Loved it you wrote very good article. I got what you intend; thankyou you for putting up; I also remember one such article about Solana Blockchain Perks Has The Answer To Everything. It is awesome!
ReplyDelete1xbet » Free Bet, Bonus, Deposit & Review | Dec 2021
ReplyDeleteWhat is 1xbet? — 1xbet wooricasinos.info is a worrione casino that offers a selection of online worrione casino games, such as slots, roulette, and poker. 1xbet 먹튀 There are https://deccasino.com/review/merit-casino/
Thanks for sharing the informative blog post.
ReplyDeleteCoin Creation |
DeFi Token Development Company |
Smart Contract Development Company |
Pancakeswap clone script
ReplyDeleteBinance clone script
Opensea clone script
Zed run clone script
NFT Marketplace Development Company
Thanks for sharing the Useful Information.
ReplyDeleteERC20 Token Development Company
Cryptocurency Development Company
Stablecoin Development Company
DeFi Token Development Company
white Label Crypto Exchange Software
ReplyDeletePancakeswap clone script
Opensea clone script
NFT Development Services is changing the way people used to think about music, art, media, games, events, etc. You can buy or sell NFTs with cryptocurrencies. So, every NFT is indivisible and unique, which means that it cannot be copied or duplicated
ReplyDeleteGreat article. If anyone looking for online mba in dubai.
ReplyDeleteWonderful Blog Post! Thanks for Sharing.
ReplyDeleteBEP20 Token Development Company
ERC20 Token Development Company
Solana Token Development Company
NFT Token Development Company
Polygon Token Development Company
Cryptocurency Development Company
Smart Contract Development Company
Token Development Company
ReplyDeleteToken Development Services
BEP20 Token Development Company
ERC20 Token Development Company
Solana Token Development Company
NFT Token Development Company
Polygon Token Development Company
NFT Music Marketplace Development Company
NFT Marketplace Development Company
ReplyDeleteBinance Clone Script
NFT Development Company
Metaverse Clone Script
ReplyDeleteMetaverse NFT Marketplace Development Company
Metaverse Development Company
Decentraland Clone Script
Sandbox Clone Script
Cryptocurrency Exchange script
Crypto Exchange Clone Script
Thanks for sharing this article.
ReplyDeleteif you want to develop a NFT application. Hire Our best NFT developers.
NFT Marketplace Development Company
ReplyDeleteMetaverse NFT Marketplace Development CompanyNFT Launchpad Development
NFT Ticketing Marketplace Development
Metaverse Development Company
White Label Crypto Exchange Software
White Label NFT Marketplace
ReplyDeleteEnterprise Blockchain Solutions
Uniswap Clone Script
Pancakeswap Clone Script
NFT Marketplace Development
ReplyDeleteSandbox clone script
NFT Development Company
NFT Game Development
Binance Clone script
NFT Marketplace Development
ReplyDeleteNFT Game Development Company
Metaverse 3D Space Development
Metaverse Development Company
Cryptocurrency Exchange Software Development Company |
ReplyDeleteCryptocurrency Exchange Software |
Wazirx Clone Script |
Wazirx Clone Software |
Binance Clone script
ReplyDeleteNFT Game Development
Axie Infinity Clone Script
NFT Marketplace Development
Metaverse Development Company
White Label Crypto Exchange Software
p2p cryptocurrency exchange development
ReplyDeletetop BBA colleges in Gurugram
ReplyDeletebest MBA Colleges in Gurugram
Best M.Com College in Gurugram
top BCA colleges in Gurugram
Best MCA College in Gurugram
Best Degree Colleges in Gurugram
This comment has been removed by the author.
ReplyDeleteThank you, for sharing such great post.real estate tokenization company
ReplyDeletesmart contract auditing services
ReplyDeleteaxie infinity clone script
ReplyDeleteCrypto Exchange Software
Cryptocurrency Exchange Script
binance clone Software
bitcoin Exchange Script
binance clone Script
Crypto Exchange Software
ReplyDeleteCryptocurrency Exchange Script
binance clone Software
bitcoin Exchange Script
binance clone Script
Nice to see such an informative post.Thank You, for sharing.Cryptocurrency Exchange Software Development Company
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteGood Post it is usefuu for us
ReplyDeleteToken Development Company
Game Development Company