1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

OAuth in SharePoint 2013

Discussion in 'ASP.NET' started by MinalS, May 1, 2015.

  1. MinalS

    MinalS New Member

    Jul 8, 2014
    Likes Received:
    Trophy Points:
    In SharePoint 2013, the apps use OAuth for authorizing the calls. For accessing a list using the API, SharePoint application checks for the identity whether a valid one or not. It later confirms that the user has an access to the resource. There are some naming conventions that needs to be followed while using OAuth.
    1. Client application: The SharePoint app uses the API for accessing and making calls to the context server
    2. Content server: It is the environment of SharePoint that has resources the client apps might need
    3. Authentication server: It is the service trusted by the client app and the content server. It created various tokens used in the OAuth process. The Azure Access Control Serrvices ( ACS ) are used for the Office 365 or Security Token Service ( STS ) for SharePoint
    4. Client app: The app uses an API for accessing and making calls to the content server
    There are categories for the authentication and authorization of the SharePoint apps. They are as mentioned below:
    1. Internally authenticated apps: These authentication includes the SharePoint hosted apps.
    2. Externally authenticated apps: They contain the auto hosted, provider hosted apps

    Application Authentication

    When an app is based on external authentication, it needs to make an API call to the SharePoint. It must confirm if it is valid and a useful set of authentication tokens. The two tokens are as mentioned below:
    1. Context token
    2. Access token
    The context token is passed when the application is launched. The data about the calling user and about the SharePoint site where the application is launched are stored.

    The access token is used for making the application calls to the SharePoint API.

    The steps used for authentication flow when the tokens are issued are as mentioned below:
    1. The user logs in the SharePoint system
    2. The context token is received by the SharePoint
    3. The token is passed to the app
    4. The context token is utilized by the app for requesting the token access
    5. The token is passed with the API calls
    The process of app authentication is mentioned in the stepwise format.
    1. The user request the SharePoint page that contains the App Part
    2. SharePoint requests for the context token from the server for the user. It contains the information about the user. A refresh token is requested which is used for requesting access tokens
    3. The signed token is returned to the SharePoint
    4. SharePoint returns the page along with an iFrame for the App part. It contains content token as a query string parameter on the URL
    5. The page and iFrame are rendered by the browser. A request is made to the remote app to render the App Part to the iFrame contents. The content token is passed on the URL.
    6. The content token is validated by the app code for ensuring the authenticity using the shares secret between the app and the SharePoint.
    7. The ACS returns the access token. They can be cached and used multiple times.
    8. The app makes use of the API call to SharePoint as CSOM or REST API request.
    9. The data requested by the user is returned by the API call
    10. The page content and result are returned by the app

    User Context and App in API calls

    The apps can make calls to the SharePoint using the access tokens. The tokens are either on user behalf or without user context. They are known as app only context. When the access token is used, it treats the call as the user call. The permissions are similar to the one user has. An app can make app only call to SharePoint. It states that no user context is passed. Only the permission for the app has granted.

    The TokenHelper class is used to provide helper methods for accessing the tokens. The following method is used to get an access token consisting of user context.

    For accessing the app-only token, use the following method.

    Tokens in an Application

    When an application is launched by the user, a context token is passed. The application needs to handle and store them. The application needs to manage the SharePoint because it has no knowledge of the application. The user decides to manage the tokens when the application passes them after the launch.

    The different options are as mentioned below:
    1. The tokens are cached after a period of time
    2. The tokens needs to be passed and are not stored
    The following steps snippet shows the cache of tokens that can be used between page requests.
    1. Create a new SharePoint App project by selecting File, New, Project.
    2. Select the appropriate App for SharePoint 2013
    3. Name the app and click OK
    4. Specify the URL of the SharePoint site used for debugging
    5. Check Autohosted from the drop down menu. Click finish
    6. Open the TokenHelper.cs file
    7. Locate the CreateJsonWebSecurityTokenHandler function and make it as public
      public static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
    8. Open the Default.aspx file and add the following code
      <asp:Button ID="Button1" runat="server" Text="Process" OnClick="Button1_Click" />
    9. Open the Default.aspx.cs file and add the following code.
      using System;
      using System.Collections.Generic;
      using System.IdentityModel.Tokens;
      using System.Web;
      using System.Web.UI;
      namespace AppWeb.Pages
          public partial class Default: System.Web.UI.Page
              protected void Page_Load(object sender, EventArgs e)
                      var context1 = TokenHelper.GetContextFromRequest(Page.Request);
                      var host1 = Page.Request("hostUrl");
                      JsonWebSecurityTokenHandler token = TokenHelper.CreateJsonWebSecurityToeknHandler();
                      SecurityToken sec = token.HeadToken(context1);
                      JsonWebSecurityToken token2 = securityToken as JsonWebSecurityToken;
                      SharePointContextToken token3=SharePointContextToken.Create(token2);
                      Application[token.CacheKey] = context1;
                      Button1.CommandArgument = token.CacheKey;
              protected void Button1_Click(object sender, EventArgs e)
                  var context1 = ( string )Application[(Button) sender.CommandArgument];
                  var host = Page.Request["hostUrl"];
                  using ( var clientContext = TokenHelper.GetClientContextWithContentToken(host,context1,Request.Url.Authority) )
                      clientContext.Load(clientContext.Web, web => web.Title);
    10. Run and debug the project
    11. Click Trust it when prompted for application trust
    12. When it is located in the apps lists, locate and click the new application
    13. The web page with the Process button appears on it. The title of the web site is displayed

    Application Authroization

    Once the application call to the SharePoint API is authenticated, the chain of security processing to check the app has appropriate resources is done.

    There are two ways of assigning the permissions as mentioned below:
    1. Statically
    2. Dynamically
    Statically assigned permissions are defined as one or more permission request in the AppManifest.xml file. They are defined by the developer. They are the permissions that the app request when installed. Once the user grants application the permissions, the application management shared service records it.

    An application can dynamically request permission during the execution. They are used for the scenarios where the application might start with the basic rights and then request.
    User can statically define permission request in the AppManifest.xml file. The example is as shown below:
        <AppPermissionRequest Scope="http://sharepoint/content/sitecollection/web"
        Right="FullControl" />
    The contents required for the permission request are Scope and Right. The Scope defines the components the permission requested. The Right defines the level of access requested by the user. There are various rights available for a particular scope. They are as Read, Write, Manage, and Full control

    Requesting Permissions Dynamically

    There are situations when an application does not know the permissions needed by an application. The situation is when an app will not know the document libraries reside in. The application need to request permissions dynamically from the user. The TokenHelper class contains a Helper method to assist the URL construction.
    TokenHelper.GetAuthorizationUrl(SiteUrl.ToString(), "Web List.Write", "https://app.com/Accept.aspx"));
    It returns a URL pointing OAuthAuthorize.aspx page with the permissions requested by the user. The Respone.Redirect() method is used for directing the user to the URL.

    The authorization code present in the query string parameter code used for representing the request an access token. The TokenHelper class has a method for assisting it.
    TokenHelper.GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;

    App-Only Policy

    The three context in which authorization is validated in SharePoint are as mentioned below:
    1. User – only policy
    2. App + user policy
    3. App- only policy
    User only policy is evaluated when users are using SharePoint Web UI. It checks permissions for performing actions and allows or denies the activity.

    App+user policy is used when an app makes an API call to SharePoint. Both the app and user have permissions in SharePoint to complete action.

    When an application model allows apps to make calls to SharePoint only in context of the application and not user. It is known as app – only context.

    App Authentication with S2S

    There are requirements when SharePoint environment and solutions are needed. They are for security, technical reasons. The use of Azure Access Control Serivces ( ACS ) and Office 365 is not useful. User can host the apps on premises and use the Server to Server ( S2S) authentication.

    The applications that work on S2S are known as high trust apps. The high trust apps must authenticate user independently. The Windows Authentication ( NTLM ) is used for authentication.

    The set up of S2S authentication needs a number of manual setup steps for efficient working. The following two components must be setup and configured before starting S2S configuration.
    1. User Profile Service application
    2. App isolation
    Once the prerequisites are setup, the following tasks are completed.
    1. Create and export a certificate
    2. Register the app
    3. Create a provider hosted app
    Once the above steps are completed, user can start building the Provider hosted apps and deploy on IIS and SharePoint. The app and SharePoint generate and verify the tokens based on trust set up with the certificate. A certificate needs to be created and the app can generate and verify the token. A self - signed certificate is a certificate that user signs himself and not from the issuing authority.

    To create a self-signed certificate, follow the steps mentioned below:
    1. Open the IIS Manager
    2. Select Server Certificates
    3. Select Create Self – signed certificate from the menu
    4. Add a certificate name, click OK. Once the task is completed, the new certificate is present
    5. The new certificate is opened
    6. Click Copy to File, Click Next
    7. Add the certificate a filename. Right click the certificate in the IIS manager, select Export
    8. Add a password in the field
    The new app identity is registered in SharePoint. The PowerPoint Shell script is useful. A new GUID is generated for the $clientid value. Add a path to the certificate. Set the name to app.
    $publicCertificatePath = "C:\MyAppCert.cer";
    $certificate = Get-PfxCertificate $publicCertificatePath
    $web =Get-SPWeb "http://servername"
    $realm = Get-SPAuthenticationRealm –ServiceContext $web.Site
    $fullAppIdentifier = $issueid + ‘@’ + $realm
    New –SPTrustedSecurityTokenIssuer –Name "App1" 
    -Certificate $certificate –RegisteredIssuerName $fullAppIdentifier
    Register –SPAppPrincipal –NameIdentifier $fullAppIdentifier –Site $web –DisplayName "App1"
    $serviceConfig = Get –SPSecurityTokenServiceConfig
    $serviceConfig.AllowOAuthOverHttp = $true
    The above code sets a new security token issuer, a new app identity, and SSL is turned Off.

    A provider hosted app is created in Visual Studio through the Office Developer Tools. The following steps are mentioned below:
    1. Create a new SharePoint app project in Visual Studio application
    2. Provide a provider hosted app
    3. Select the Use a Certificate option, specify the path of PFX certificate file to be exported. Add the password specified during export
    4. Add the $clientid GUID created by the user.
    5. Complete the wizard and application development
    6. Press F5 and deploy the application
    shabbir likes this.

Share This Page