Thursday 3 December 2015

oAuth in SharePoint 2013

In order to use a context token with SharePoint 2013 apps, you will need to create a provider-hosted app that uses a client ID and a client secret.  This requires that the target SharePoint farm has a trust configured to Azure Access Control Services, or ACS.  Office365 automatically configures this trust for you, so if you create your app using Office365 then this works just fine.  If you create your app using your own SharePoint farm, then you will need to configure low-trust apps for on-premises deployments in order to establish a trust with Azure ACS for your SharePoint farm.

When you use a client ID and a client secret to build your app, you are using Azure ACS as the authentication server.

The following is an example of how the client id and client secret are entered in the web.config file.
<configuration>
  <appSettings>
    <add key="ClientId" value="c78d058c-7f82-44ca-a077-fba855e14d38"/>
    <add key="ClientSecret" value="SbALAKghPXTjbBiLQZP+GnbmN+vrgeCMMvptbgk7T6w="/>

  </appSettings>

</configuration>
Step 1:
The user enters a URL pointing to the SharePoint Online site: https://fabrikam.sharepoint.com/.

Step 2 : The add-in redirects to the SharePoint site authorization URL.
 This redirect is a HTTP 302 Redirect Response.
If you're using Microsoft .NET, Response.Redirect is one of several ways you can do the redirect from your code. Using the TokenHelper.cs (or .vb) file in your project, your code can call the overloaded GetAuthorizationUrl method (using the overload with three arguments). This method constructs the OAuthAuthorize.aspx redirect URL for you. Or, your code can manually construct the URL.
For example, if you choose to call the GetAuthorizationUrl method to construct the OAuthAuthorize.aspx redirect URL for you, using the TokenHelper.cs (or .vb) in your project, the code is as follows:
Response.Redirect(TokenHelper.GetAuthorizationUrl(
   sharePointSiteUrl.ToString(),
   "Web.Read List.Write",
   "https://contoso.com/RedirectAccept.aspx"));
If you look at the three-parameter overload of the GetAuthorizationUrl method in TokenHelper.cs (or .vb), you see that the second parameter is a permission scope parameter, which is a space-delimited list of permissions the add-in requests in shorthand format. For more information about permission scopes, see Understand permission scope aliases and the use of the OAuthAuthorize.aspx page. The third parameter must be the same redirect URI that is used when the add-in is registered.


If you prefer, you can manually construct the OAuthAuthorize.aspx redirect URL. For example, the URL that the Contoso photo-printing add-in redirects the user to in this case is:
https://fabrikam.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, the Contoso photo-printing add-in sends the OAuth client Id and redirect URI to the Fabrikam 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.
GET /authcode HTTP/1.1
Host: fabrikam.sharepoint.com

/oauthauthorize.aspx
    ?client_id= c78d058c-7f82-44ca-a077-fba855e14d38
    &scope=list.read
    &response_type=code
    &redirect_uri= https%3A%2F%2Fcontoso%2Ecom%2Fredirectaccept.aspx
If you want a separate consent pop-up dialog, you can add the query parameter IsDlg=1 to the URL construct as shown here:
/oauthauthorize.aspx?IsDlg=1&client_id= c78d058c-7f82-44ca-a077-fba855e14d38&scope=list.read&response_type=code&redirect_uri= https%3A%2F%2Fcontoso%2Ecom%2Fredirectaccept.aspx


If the user is not already signed into the Fabrikam SharePoint Online site, the user is prompted to sign in. When the user is signed in, SharePoint renders an HTML consent page.
The consent page prompts the user to grant (or deny) the Contoso photo-printing add-in the permissions that the add-in requests. In this case, the user would be granting the add-in read access to the user's picture library on Fabrikam.

The Fabrikam SharePoint Online site asks ACS to create a short-lived (approximately 5 minutes) authorization code unique to this combination of user and add-in.
ACS sends the authorization code to the Fabrikam site.

The Fabrikam SharePoint Online site redirects the browser back to Contoso via HTTP 302 Response. The URL construct for this redirection uses the redirect URI that was specified when the photo-printing add-in was registrated. It also includes the authorization code as a query string. The redirect URL is structured like the following:
https://contoso.com/RedirectAccept.aspx?code=<authcode>

The add-in uses the authorization code to request an access token from ACS, which validates the request, invalidates the authorization code, and then sends access and refresh tokens to the add-in.
Contoso retrieves the authorization code from the query parameter, and then includes it, along with the client ID and client secret, in a request to ACS for an access token.
If you are using managed code and the SharePoint CSOM, the TokenHelper.cs (or .vb) file, the method that makes the request to ACS is GetClientContextWithAuthorizationCode. In this case the code looks similar to the following (where authCode is a variable to which the authorization code has been assigned):
TokenHelper.GetClientContextWithAuthorizationCode(
    "https://fabrikam.sharepoint.com/",
    "00000003-0000-0ff1-ce00-000000000000",
    authCode,
    "1ee82b34-7c1b-471b-b27e-ff272accd564",
    new Uri(Request.Url.GetLeftPart(UriPartial.Path)));
If you look at the TokenHelper.cs (or .vb) file, the second parameter of theGetClientContextWithAuthorizationCode method is the targetPrincipalName. This value is always the constant "00000003-0000-0ff1-ce00-000000000000" in an add-in that is accessing SharePoint. You will also see, if you trace the call hierarchy from GetClientContextWithAuthorizationCode, that it obtains the client ID and secret from the web.config file.
ACS receives Contoso's request and validates the client ID, client secret, redirect URI, and authorization code. If all are valid, the ACS invalidates the authorization code (it can be used only once) and creates a refresh token and an access token, which it returns to Contoso.
The Contoso application can cache this access token for reuse on later requests. By default, access tokens are good for about 12 hours. Each access token is specific to the user account that is specified in the original request for authorization, and grants access only to the services that are specified in that request. Your add-in should store the access token securely.
The Contoso application can also cache the refresh token. By default, refresh tokens are good for 6 months. The refresh token can be redeemed for a new access token from ACS whenever the access token expires. For more information about tokens, see Handle security tokens in provider-hosted low-trust SharePoint Add-ins.

The add-in can now use the access token to request data from the SharePoint site which it can display to the user.
Contoso includes the access token to make a REST API call or CSOM request to SharePoint, passing the OAuth access token in the HTTP Authorization header.
SharePoint returns the information that Contoso requested. For more about how this request is made, see Handle security tokens in provider-hosted low-trust SharePoint Add-ins.

 Sample code behind for a page that accesses SharePoint


The following is code behind for a Default.aspx page. This page assumes a scenario in which the Default page is the start page for the add-in and is also the registered Redirect URL for the add-in. Note the following about this code:
  • The Page_Load method first checks for an authorization code in the query string. There will be one if the browser was redirected to the page by SharePoint. If there is one, the code uses it to get a new refresh token, which it caches in a durable cache that lasts across sessions.
  • The method then checks for a refresh token in the cache.
    • If there isn't one, it gets one by telling SharePoint the permissions it needs (Write permission at Web scope) and asking SharePoint for an authorization code. The user is prompted to grant the permission, and if it is granted, SharePoint gets the authorization code from ACS and sends it back as a query parameter on a redirect to this same page.
    • If there is a cached refresh token, the method uses it to obtain an access token, directly from ACS. Just as in the example at the end of the preceding section of this article, the access token is used to create a SharePoint client context object. Using a cached refresh token to get an access token directly from ACS, avoids the additional network call to SharePoint on session startup, so users rerunning the add-in within the lifespan of the refresh token cache experience faster startup.
  • Just as in the example at the end of the preceding section, this code makes no provision for dealing with an expired access token. Once the client context object is created, it keeps using the same access token. One way to protect against an expired access token is to cache the access token, in addition to the refresh token. You would then modify the code below so that it calls the GetAccessToken method only if there isn't an unexpired access token in the cache. However, while it is acceptable to have the refresh token cached on the client, in a cookie, for example, the access token should only be in a server-side cache for security reasons. The refresh token is encrypted and can only be unencrypted by ACS. But the access token is merely encoded (with Base 64 encoding) and can be easily decoded by a man-in-the-middle attack.
  • The TokenCache class that is referred to in this code is defined below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Samples;
using Microsoft.SharePoint.Client;

namespace DynamicAppPermissionRequest
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Uri sharePointSiteUrl = new Uri("https://fabrikam.sharpoint.com/print/");

            if (Request.QueryString["code"] != null)
            {
                TokenCache.UpdateCacheWithCode(Request, Response, sharePointSiteUrl);
            }

            if (!TokenCache.IsTokenInCache(Request.Cookies))
            {
                Response.Redirect(TokenHelper.GetAuthorizationUrl(sharePointSiteUrl.ToString(), 
                                                                  "Web.Write"));
            }
            else
            {
                string refreshToken = TokenCache.GetCachedRefreshToken(Request.Cookies);
                string accessToken = 
                TokenHelper.GetAccessToken(
                           refreshToken, 
                           "00000003-0000-0ff1-ce00-000000000000", 
                           sharePointSiteUrl.Authority, 
                           TokenHelper.GetRealmFromTargetUrl(sharePointSiteUrl)).AccessToken;

                using (ClientContext context = 
                       TokenHelper.GetClientContextWithAccessToken(sharePointSiteUrl.ToString(), 
                                                                   accessToken))
                {
                    context.Load(context.Web);
                    context.ExecuteQuery();

                    Response.Write("<p>" + context.Web.Title + "</p>");
                }
            }
        }
    }
}
The following is a code example for a token cache module that the previous sample code calls. It uses cookies as the cache. There are other caching options. For more information, see Handle security tokens in provider-hosted low-trust SharePoint Add-ins.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.SharePoint.Samples;

namespace DynamicAppPermissionRequest
{
    public static class TokenCache
    {
        private const string REFRESH_TOKEN_COOKIE_NAME = "RefreshToken";

        public static void UpdateCacheWithCode(HttpRequest request, 
                                               HttpResponse response, 
                                               Uri targetUri)
        {
            string refreshToken = 
                TokenHelper.GetAccessToken(
                    request.QueryString["code"], 
                    "00000003-0000-0ff1-ce00-000000000000", 
                    targetUri.Authority, 
                    TokenHelper.GetRealmFromTargetUrl(targetUri), 
                    new Uri(request.Url.GetLeftPart(UriPartial.Path)))
                   .RefreshToken;
            SetRefreshTokenCookie(response.Cookies, refreshToken);
            SetRefreshTokenCookie(request.Cookies, refreshToken);
        }

        internal static string GetCachedRefreshToken(HttpCookieCollection requestCookies)
        {
            return GetRefreshTokenFromCookie(requestCookies);
        }

        internal static bool IsTokenInCache(HttpCookieCollection requestCookies)
        {
            return requestCookies[REFRESH_TOKEN_COOKIE_NAME] != null;
        }

        private static string GetRefreshTokenFromCookie(HttpCookieCollection cookies)
        {
            if (cookies[REFRESH_TOKEN_COOKIE_NAME] != null)
            {
                return cookies[REFRESH_TOKEN_COOKIE_NAME].Value;
            }
            else
            {
                return null;
            }
        }

        private static void SetRefreshTokenCookie(HttpCookieCollection cookies, 
                                                  string refreshToken)
        {
            if (cookies[REFRESH_TOKEN_COOKIE_NAME] != null)
            {
                cookies[REFRESH_TOKEN_COOKIE_NAME].Value = refreshToken;
            }
            else
            {
                HttpCookie cookie = new HttpCookie(REFRESH_TOKEN_COOKIE_NAME, 
                                                   refreshToken);
                cookie.Expires = DateTime.Now.AddDays(30);
                cookies.Add(cookie);
            }
        }
    }
}


The Summary of these steps can be written as : 
  1. User makes a request to SharePoint
  2. SharePoint requests the context token from Azure ACS
  3. The signed context token is returned
  4. The HTML markup for the SharePoint page is sent to the client
  5. If the SharePoint page contents contain a client app part, then a request is sent to the remote web server for the IFrame’s contents.  If the user simply clicked on the app to launch it, then a page in SharePoint called appredirect.aspx is used to redirect to the app’s start URL.  In either case, a context token is sent along with that page request in a form parameter called SPAppToken. 
  6. The context token is a JWT token.  The JWT token is a set of base64 encoded claims.  One claim is named “refreshtoken” that has a base64 encoded value.  One of the claims is “appctx” which contains a child object, one of the properties is SecurityTokenServiceUri with a valuehttps://accounts.accesscontrol.windows.net/tokens/OAuth/2.  Your app uses the TokenHelper.cs class to extract the refreshtoken and then send it to the SecurityTokenServiceUri to request an access token.
  7. The access token is retrieved from ACS.
  8. The access token is passed to the SharePoint site in the HTTP header Authorization that has a value beginning with “Bearer” and has your access token.  This token is passed in the HTTP header to the CSOM endpoint _vti_bin/client.svc/ProcessQuery when you use the CSOM.
  9. If the app is authorized, SharePoint returns the data requested.
  10. Finally, the app server returns the requested HTML markup as a response. 


What are the claims in the context token?

The following shows the properties for the context token.
audShort for “audience”, means the principal the token is intended for. The format is <client ID>/<target URL authority>@<target realm>. Based on this information, you can determine the client ID for your app and the realm.  In an on-premise environment, there is typically just one realm, and its identifier matches your farm ID.  For Office 365, this is your tenant ID.
issShort for “issuer”, this is the principal that issued the token, in the form of <principal ID>@<realm>.  The principal ID value 00000001-0000-0000-c000-000000000000 is ACS. 
nbfShort for “not before”, this is the number of seconds after January 1, 1970 (part of the JWT specification) that the token starts being valid. 
expShort for “expires”, represents the number of seconds after January 1, 1970 that the token stops being valid.
appctxsenderThe sender of the token in the form <sender ID>@<realm>.  The value00000003-0000-0ff1-ce00-000000000000 is the identifier for SharePoint.  For trivia:

ACS00000001-0000-0000-c000-000000000000
Exchange00000002-0000-0ff1-ce00-000000000000
SharePoint00000003-0000-0ff1-ce00-000000000000
Lync00000004-0000-0ff1-ce00-000000000000
Workflow00000005-0000-0000-c000-000000000000

The realm will be the tenant ID for Office 365, or the farm ID for your on-premise deployment.
appctxContains two properties, CacheKey and SecurityTokenServiceUri.
CacheKey: UserNameId + "," + UserNameIdIssuer + "," + ApplicationId + "," + Realm
This is provided so that you can cache the value in a cookie or in session to identify that the user has already authenticated.

SecurityTokenServiceUri: The URL for Azure ACS where the token is to be validated.  The URL ishttps://accounts.accesscontrol.windows.net/tokens/OAuth/2.  
refreshtokenThe contents of the refresh token that are sent to Azure ACS.
isbrowserhostedappIndicates if the request initiated from a user interacting with the browser and not an app event receiver

 

No comments: