Implementing Authorization in Provider hosted Apps

Hi
I am developing App for SharePoint Online using Chrome control and Apps is hosted at Amzon Cloud(using Windows server 2012 and SQL server 2014).
I want to Implement Authorization in this App based on logged in user  in SharePoint Online.
Can any body Help me on same? Thanks in advance
Kaps

Hi Kaps,
Please check if the links below could help:
OAuth authentication and authorization flow for cloud-hosted apps in SharePoint 2013
http://msdn.microsoft.com/en-us/library/office/fp142382(v=office.15).aspx
How to: Create apps for SharePoint that can be used by anonymous users
http://msdn.microsoft.com/en-us/library/office/dn579415(v=office.15).aspx
SharePoint Online Enterprises App Model Management Policies and Process
http://technet.microsoft.com/en-us/library/dn198209.aspx
Since the forum is specific for SharePoint on-premise, I'd recommend you could also ask the question in our SharePoint online forum for more sufficient resource and professional assistance. Thanks for the understanding.
http://social.technet.microsoft.com/Forums/msonline/en-US/home?forum=onlineservicessharepoint
Regards,
Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
[email protected] .
Rebecca Tu
TechNet Community Support

Similar Messages

  • Provider-hosted Apps debug error: The remote server returned an error: (401) unauthorised

    Hi,
    Any help appreciated!!
    I'm getting this error: "The remote server returned an error: (401) unauthorised when I debug a provider-hosted app.  I get the error on this line:  
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    See code below
    I created a high trust development environment following the instructions provided here:
    http://msdn.microsoft.com/en-us/library/office/fp179901(v=office.15).aspx and
    http://msdn.microsoft.com/library/office/fp179923
    I created a provider-hosted app with the intent to:
    create a SharePoint list in the appweb
    Use self-signed certificate, tokenhepler.cs and sharepointcontext.cs to retrieve current user context and access on SharePoint.  (No changes were made to tokenhelper.cs and sharepointcontext.cs)
    retrieve list items from the SharePoint list in a button click event handler on a default.aspx of the remote web
    What happens:
    The app is deployed successfully to the Dev site
    The SharePoint feature is deployed and activated
    The default.aspx page of the remote web loads
    The error (see image) is returned on clicking of the button
    My environment is an on-premise SharePoint 2013 with AD and my dev box is standalone windows 8.1 running Visual Studio Professional 2013 Update 3.
    The code block below is a copy of the default.aspx code-behind
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Microsoft.SharePoint.Client;
    using Microsoft.IdentityModel.S2S.Tokens;
    using System.Net;
    using System.IO;
    using System.Xml;
    using System.Data;
    using System.Xml.Linq;
    using System.Xml.XPath;
    namespace Idea.GeneratorWeb
    public partial class Default : System.Web.UI.Page
    SharePointContextToken contextToken;
    string accessToken;
    Uri sharepointUrl;
    protected void Page_PreInit(object sender, EventArgs e)
    Uri redirectUrl;
    switch (SharePointContextProvider.CheckRedirectionStatus(Context, out redirectUrl))
    case RedirectionStatus.Ok:
    return;
    case RedirectionStatus.ShouldRedirect:
    Response.Redirect(redirectUrl.AbsoluteUri, endResponse: true);
    break;
    case RedirectionStatus.CanNotRedirect:
    Response.Write("An error occurred while processing your request.");
    Response.End();
    break;
    protected void Page_Load(object sender, EventArgs e)
    //// The following code gets the client context and Title property by using TokenHelper.
    //// To access other properties, the app may need to request permissions on the host web.
    var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
    //var spContext = new ClientContext("MySPDevInstance");
    //spContext.Credentials = new NetworkCredential("username", "password");
    //using (var clientContext = spContext.CreateUserClientContextForSPHost())
    // clientContext.Load(clientContext.Web, web => web.Title);
    // clientContext.ExecuteQuery();
    // Response.Write(clientContext.Web.Title);
    string contextTokenString = TokenHelper.GetContextTokenFromRequest(Request);
    if (contextTokenString != null)
    // Get context token
    contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, Request.Url.Authority);
    // Get access token
    sharepointUrl = new Uri(Request.QueryString["SPAppWebUrl"]);
    accessToken = TokenHelper.GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
    // Pass the access token to the button event handler.
    Button1.CommandArgument = accessToken;
    protected void Button1_Click(object sender, EventArgs e)
    // Retrieve the access token that the Page_Load method stored
    // in the button's command argument.
    string accessToken = ((Button)sender).CommandArgument;
    if (IsPostBack)
    sharepointUrl = new Uri(Request.QueryString["SPAppWebUrl"]);
    // REST/OData URL section
    string oDataUrl = "/_api/Web/lists/getbytitle('Diagrams In Idea Generator')/items?$select=Title,Diagram,SharingStatus";
    // HTTP Request and Response construction section
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(sharepointUrl.ToString() + oDataUrl);
    request.Method = "GET";
    request.Accept = "application/atom+xml";
    request.ContentType = "application/atom+xml;type=entry";
    request.Headers.Add("Authorization", "Bearer " + accessToken);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    // Response markup parsing section
    XDocument oDataXML = XDocument.Load(response.GetResponseStream(), LoadOptions.None);
    XNamespace atom = "http://www.w3.org/2005/Atom";
    XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices";
    XNamespace m = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
    List<XElement> entries = oDataXML.Descendants(atom + "entry")
    .Elements(atom + "content")
    .Elements(m + "properties")
    .ToList();
    var entryFieldValues = from entry in entries
    select new
    Character = entry.Element(d + "Title").Value,
    Actor = entry.Element(d + "Diagram").Value,
    CastingStatus = entry.Element(d + "SharingStatus").Value
    GridView1.DataSource = entryFieldValues;
    GridView1.DataBind();
    Any ideas what I might be doing wrong

    Hi ,
    Use the below code
    Public string GetAccessToken(){
    string sharePointSiteUrlHost =  Page.Request["SPHostUrl"].Tostring();
    string AccessToken = tokenHelper.GetS2SAccessTokenWithWindowsIdentity(sharePointSiteUrlHost, Request.LogonUserIdentity);
    return accessToken;
    Than initialize the ClientCOntext with the below Method
     private static ClientContext GetClientContextWithAccessTokenString(string targetUrl, object accessToken)
                ClientContext clientContext = new ClientContext(targetUrl);
                clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
                clientContext.FormDigestHandlingEnabled = false;
                clientContext.ExecutingWebRequest +=
                    delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
                        webRequestEventArgs.WebRequestExecutor.WebRequest.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)";
                        webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
                            "Bearer " + accessToken;
                return clientContext;
    use this clientCOntext and it will work.
    Do not use
    SharePointContextProvider
    Whenever you see a reply and if you think is helpful,Vote As Helpful! And whenever you see a reply being an answer to the question of the thread, click Mark As Answer

  • How to Use Office 365 api in Provider Hosted App

    Hi,
    I want to use outlook api in SharePoint Provider Hosted App.
    when I use :-
     $.ajax({
                url: 'https://outlook.office365.com/api/v1.0/me/contacts',
                type: 'GET',
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('Authorization', 'Bearer');
                Accept: "application/json",
                "client-request-id": "9de3d763-a8d9-4433-92f3-096d6be36d86",
                success: function () {
                alert("Welcome to Outlook ")},
                error: function (e) {
                    alert(' Error121212 :' +e);
    Error:-
    XMLHttpRequest cannot load https://outlook.office365.com/api/v1.0/me/contacts. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost:44309' is therefore not allowed access. The response had HTTP status code
    401.
    Please Provide me a good example.
    Thanks in Advance

    Hi SharePlus,
    You probably want to use the Office 365 API's to authenticate and communicate with the API's. 
    There's several resources available for this:
    Ultimate LinkRoll for Getting Started with the Office 365 API's
    Download Office 365 API Tools for Visual Studio 2013
    Getting Started with O365 Dev - Communicate with Exchange
    If you don't want to use the pre-compiled typed objects in the Office 365 API's for communicating with the Mail service (Exchange), you can always just make sure to handle the authentication properly and then construct your queries as raw queries, like Chaks
    describes here: http://chakkaradeep.com/index.php/working-with-office365apis-the-raw-version/
    Also, as a general rule; When working with anything Office 365, you should always keep an eye out for the example code, articles and news published from the Office 365 Patterns & Practices team here: https://github.com/OfficeDev/PnP
    I hope this will guide you in the right direction :-)
    Tobias Zimmergren
    Microsoft MCP, MCTS, MCT, MVP (SharePoint)
    Blog: www.zimmergren.net
    Twitter: twitter.com/zimmergren
    Corporate site: www.tozit.com

  • Sharepoint provider hosted app using angularjs

    I am working on a provider hosted app and trying to access the list item through REST call using angularjs. But I am not able to access the list. Is it possible to access the sharepoint list through REST call using angularjs in a provider hosted app?
    Below is the code for angular:
    var hostWebApp = angular.module('HostWebList', []);
    Service:
    hostWebApp.service('$SharePointJSOMService', function ($q, $http) {
        this.getListItems = function ($scope, listTitle) {
            var deferred = $q.defer();
            //First we must call the EnsureSetup method
            JSRequest.EnsureSetup();
            var hostweburl = decodeURIComponent(JSRequest.QueryString["SPHostUrl"]);
            var appweburl = decodeURIComponent(JSRequest.QueryString["SPAppWebUrl"]);
            var restQueryUrl = hostweburl + "/_api/web/lists/getbytitle('ListName')/items";
            var executor = new SP.RequestExecutor(hostweburl);
            executor.executeAsync({
                url: restQueryUrl,
                method: "GET",
                headers: { "Accept": "application/json; odata=verbose" },
                success: function (data, textStatus, xhr) {
                    deferred.resolve(JSON.parse(data.body));
                error: function (xhr, textStatus, errorThrown) {
                    alert("request failed");
                    alert(textStatus);
    //getting -1003
                    alert(JSON.stringify(xhr));
    //{"responseAvailable":false,"body":,"Header":null}
                    deferred.reject(JSON.stringify(xhr));
            return deferred.promise;
    Controller:
    hostWebApp.controller('HostWebListController', function ($scope, $SharePointJSOMService) {
        $scope.listItem = null;
        var listName = "IncomingEmail";
        var promise = $SharePointJSOMService.getListItems($scope, listName);
        promise.then(function (data) {
            $scope.listItem = data.d.results;
            alert($scope.listItem);
            console.log("came inside the promise success method");
        }, function (data) {
            console.log("Error " + data);
    Following javascript files I have included:
     <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
      <script type="text/javascript" src="/_layouts/15/sp.js"></script>
     <script type="text/javascript" src="/_layouts/15/SP.RequestExecutor.js"></script>
     <script type="text/javascript" src="/_layouts/15/init.debug.js"></script>
    angular.js included. 
    I don't know what is the problem. Can anybody walk me through the problem. will be great help.

    Your REST request must be authenticated. So you must send the access token in the authorization header along with your request. The following link explains how you can get the access token when you using a provider hosted app.
    http://blog.mastykarz.nl/using-sharepoint-rest-api-in-provider-hosted-apps/
    Blog | SharePoint Field Notes Dev Tools |
    SPFastDeploy | SPRemoteAPIExplorer

  • HTTPS SharePoint site with HTTPS Provider hosted app - The remote certificate is invalid according to the validation procedure

    We have SharePoint 2013 site configured with SSL and we have developed a provider hosted app which interacts with SharePoint list.
    If we try accessing the Provider hosted app from the SharePoint site with HTTP [http://mysharepointsite.com/] there are no any errors thrown.
    But whenever the same Provider hosted app is tried accessing from the same SharePoint site using https address
    [https://mysharepointsite.com/] we are getting below error:
    The remote certificate is invalid according to the validation procedure.
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
    Exception Details: System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
    Source Error:
    An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
    Stack Trace:
    [AuthenticationException: The remote certificate is invalid according to the validation procedure.]
    System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, Exception exception) +2983172
    System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest) +473
    System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest) +86
    System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest) +262
    System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest) +473
    System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest) +86
    System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest) +262
    System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest) +473
    System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest) +86
    System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest) +262
    System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest) +473
    System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest) +8530566
    System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult) +230
    System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) +645
    System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) +9
    System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) +87
    System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result) +1467
    System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size) +84
    System.Net.PooledStream.Write(Byte[] buffer, Int32 offset, Int32 size) +22
    System.Net.ConnectStream.WriteHeaders(Boolean async) +761
    [WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.]
    System.Net.HttpWebRequest.GetResponse() +8534156
    Microsoft.SharePoint.Client.SPWebRequestExecutor.Execute() +58
    Microsoft.SharePoint.Client.ClientRequest.ExecuteQueryToServer(ChunkStringBuilder sb) +975
    ProviderHostedHTTPSWeb.Default.Page_Load(Object sender, EventArgs e) +348
    System.Web.UI.Control.LoadRecursive() +71
    System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3178
    We have already added the certificate used for the SharePoint site and the provider hosted app in the SharePoint central admin trusts.
    Any idea's how can I resolve this issue?

    Hi,
    According to your post, my understanding is that you failed to access provider host app using https.
    The reason for this is that SharePoint implements its own certificate validation policy to override .NET certificate validation.
    Fix is to setup a trust between SharePoint and the server requiring certificate validation.
    For more information, you can refer to:
    http://blogs.technet.com/b/sharepointdevelopersupport/archive/2013/06/13/could-not-establish-trust-relationship-for-ssl-tls-secure-channel.aspx
    Best Regards,
    Linda Li
    Linda Li
    TechNet Community Support

  • Sharepoint Idle timeout on page with Provider hosted app

    We have a Sharepoint idle timeout implemented using javascript which triggers on every page load initializes and timer counts to say 60sec as configured when idle .On reaching the time the script triggers a window.href to the ADFS logout page.This is fine.
    Issue comes when user is working on a provider hosted app in a sharepoint page.Since any postback inside the app(iframe) does not reload sharepoint page the js timer reaches the value and logs
    out.
    How can this be achieved.any inputs.

    https://social.technet.microsoft.com/Forums/lync/en-US/85f52c85-f2e3-4930-894e-2d7a198a39de/redirecting-user-from-app-part-to-a-list-in-host-web?forum=sharepointdevelopment 
    Please mark as answer if you find it useful else vote for it if it is close to answer..happy sharepointing

  • Why do we need UPA for rehydrating users in Sharepoint provider hosted app scenario?

    Our on prem. SPS 2013 environment is configged to authenticate through ADFS against a third party IDP. We know nothing about these users, the returned SAML contains a role and based on this role we authorize user in SPS. This works great.
    No we are investigating high-trust provider hosted apps (on prem, no azure acs). We have created a simple MVC, and configged it to use ADFS. Now if users are authenticated from SPS they can call the MVC and the ADFS token is reused. Works perfect. Only thing
    is that whenever we need to call Sharepoint code through the client objectmodel, we get a 401 and the ULS shows that SPS is not able to map the incoming user to a user in User Profile DB. Off course it can't because the user is not in UPA and cannot be in
    UPA beacuse the users are stored outside our domain and there is no way to sync these to our SPS environment. I read a couple of blogs about this issue and the all say that we ned to sync with the user repository to fill upa; but again that cannot be (suppose
    on of our IDP's was facebook...?)
    The construction works if we use apponly security, but now we lose our SPS security. So my real question is, can we some how workaround User Profile service in the scenario, or at least without needing to sync these users.
    Any help/guidance is much appreciated!
    Sander

    Hi John,
    No we were not able to find a solution. The provider hosted app-model of SPS 2013 just does not take into account that in some cases useraccounts are not available. We could not find a way around user rehydration. Off course you can all ways use another
    security model like app-only policies, but that was not sufficient for us. It was also kind of disappointing there was no way to handle this; th emost problematic for me personal is that I cannot think of a reason why the rehydration can not be skipped in
    some way. If you configure it to run within SPS itself, rehydration is not necessary, so why it seams mandatory in provider hosted app beats me ;-)
    We went back to good old farm-solutions with webparts. 
    Sorry 
    Sander

  • Claims aware Provider Hosted Apps - The SecurityToken was not well formed

    Dear Friends,
    Please help me,
    I have Created a Provider hosted apps and converted Basic Provider Hosted Application into Claims Aware Provider Hosted Application in SharePoint 2013.
    I did all configuration based on ADFS implementation.
    The error we got is
    Server Error in '/' Application.
    ID4230: The SecurityToken was not well formed. Expecting element name 'SecurityContextToken', found 'SP'.
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
    Exception Details: System.IdentityModel.Tokens.SecurityTokenException: ID4230: The SecurityToken was not well formed. Expecting element name 'SecurityContextToken', found 'SP'.
    Source Error:
    An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
    Stack Trace:
    [SecurityTokenException: ID4230: The SecurityToken was not well formed. Expecting element name 'SecurityContextToken', found 'SP'.]
    System.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(XmlReader reader, SecurityTokenResolver tokenResolver) +1082000
    System.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(Byte[] token, SecurityTokenResolver tokenResolver) +100
    System.IdentityModel.Services.SessionAuthenticationModule.ReadSessionTokenFromCookie(Byte[] sessionCookie) +623
    System.IdentityModel.Services.SessionAuthenticationModule.TryReadSessionTokenFromCookie(SessionSecurityToken& sessionToken) +164
    System.IdentityModel.Services.SessionAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs eventArgs) +173
    System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80
    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +165
    Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.19453 
    Regards
    Jenkins NS
    Thanks &amp; Regards Jenkins

    Dear Friends,
    Please help me,
    I have Created a Provider hosted apps and converted Basic Provider Hosted Application into Claims Aware Provider Hosted Application in SharePoint 2013.
    I did all configuration based on ADFS implementation.
    The error we got is
    Server Error in '/' Application.
    ID4230: The SecurityToken was not well formed. Expecting element name 'SecurityContextToken', found 'SP'.
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
    Exception Details: System.IdentityModel.Tokens.SecurityTokenException: ID4230: The SecurityToken was not well formed. Expecting element name 'SecurityContextToken', found 'SP'.
    Source Error:
    An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
    Stack Trace:
    [SecurityTokenException: ID4230: The SecurityToken was not well formed. Expecting element name 'SecurityContextToken', found 'SP'.]
    System.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(XmlReader reader, SecurityTokenResolver tokenResolver) +1082000
    System.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(Byte[] token, SecurityTokenResolver tokenResolver) +100
    System.IdentityModel.Services.SessionAuthenticationModule.ReadSessionTokenFromCookie(Byte[] sessionCookie) +623
    System.IdentityModel.Services.SessionAuthenticationModule.TryReadSessionTokenFromCookie(SessionSecurityToken& sessionToken) +164
    System.IdentityModel.Services.SessionAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs eventArgs) +173
    System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80
    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +165
    Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.19453 
    Regards
    Jenkins NS
    Thanks &amp; Regards Jenkins

  • Provider hosted app - Site Provisioning activities

    Hi ,
    I am creating a Provider hosted app which does site provisioning activities like create site , create site columns, content types etc. I have almost 50 or more fields to be added. I am using the Provider hosted app - Process Event, and used SPRemoteEventType
    - App Installed.
    When the app is installed the above functionalities are done, as I need to code to do these activities synchronously.
    I am facing an issue in App Installed event that,during the code execution (consider the field creation method), since it takes some time to add all the fields, after some time limit,  the runtime comes to the start point of code execution , which is
    creation of token helper, and the methods already executed is also called again.
    I have executed the code in Release mode, the logs show the above behavior.
    I am not sure how I am getting this weird behavoir.
    Please advise.

    msdn (Handling events in apps for SharePoint):
    Your implementation of the App Installed event must complete and return an SPRemoteEventResult object
    within 30 seconds or the SharePoint installation infrastructure will think it has failed. The infrastructure will rerun the event, and repeat your code from the beginning, up to four times. After four timeouts,
    SharePoint will roll back the entire app installation. We recommend the following practices:
    If there is any code in your handler that should not be repeated after a timeout, put it in a conditional block that tests to see if it has already run. You must test the actual installed component. Simply setting
    a variable to true when a block of code completes does not work as a test because all variables are reinitialized when the event times out and restarts.
    Move installation code that takes more than 30 seconds into the app itself. You can add it to "first run" logic that executes the first time the app is launched. Alternatively, the app can prompt the
    user to run the installation code.
    If the preceding bullet item is not feasible for your app, another option is to have your event handler start a remote asynchronous process and then immediately return a SPRemoteEventResultobject.
    A weakness of this strategy is that if the remote process fails, it has no way to tell SharePoint to roll back the app installation.
    [custom.development]

  • Provider hosted App certificates (.cer & .pfx)

    I have a implemented a provider hosted App inside the SharePoint 2013 server (the certificates .cer & .pfx  taken from the IIS of same server) and able to get the result. However I am not clear about taking the certificates in the multi server
    environment (SharePoint Server & IIS server for remote web app).
    can anyone please suggest from which server (Sharepoint Server or IIS server)  do I need to take the .cer & .pfx files to configure multi server environment ?
    Thanks

    Hi,
    According to your post, my understanding is that you want to create a provider hosted app and use NLB in premise environment.
    You need to use a different certificate on this ‘Listener’ web application.
    Configuring SharePoint 2013 Apps and Multiple Web Applications on SSL with a
    Single IP Address
    For more information, you can refer to:
    Aspiring Architect: Sharepoint 2013 - Avoiding Azure on Dev Box
    More TroubleShooting Tips for High Trust Apps on SharePoint 2013
    You need to ensure that all connections to the SharePoint servers are secure and encrypted
    Best Regards,
    Linda Li
    Linda Li
    TechNet Community Support

  • Provider hosted App Error: You do not have permission...

    Hi everyone,
    i'm using SharePoint online. I opened a provider hosted app and when I run this I get this error:
    "Access denied. You do not have permission to perform this action or access this resource."
    when I did debug I notice that it fall in this line:
    webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"]
    and "webRequestEventArgs.WebRequestExecutor.RequestHeaders"
    is empty.
    what can I do?
    thank you!

    i'm trying to add an item ti my list:
    protected void Page_Load(object sender, EventArgs e)
    //constant string SharePoint principal
    string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
    var contextToken = TokenHelper.GetContextTokenFromRequest(Page.Request);
    Uri hostWeb = new Uri(Page.Request["SPHostUrl"]);
    string realm = TokenHelper.GetRealmFromTargetUrl(hostWeb);
    string appOnlyAccessToken = TokenHelper.GetAppOnlyAccessToken(SharePointPrincipal, hostWeb.Authority, realm).AccessToken;
    using (ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(hostWeb.ToString(), appOnlyAccessToken))
    if (clientContext != null)
    //ShariqTest is a custom List in my SharePoint site
    var myList = clientContext.Web.Lists.GetByTitle("ListName");
    ListItemCreationInformation listItemCreate = new ListItemCreationInformation();
    Microsoft.SharePoint.Client.ListItem newItem = myList.AddItem(listItemCreate);
    newItem["ColumnName"] = "Testing ";
    newItem.Update();
    clientContext.ExecuteQuery();
     "[and the  webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization
    is in TokenHelper.cs.
    what do you think my problem is?

  • Retrieve data from a list in SharePoint 2013 provider hosted App using CSOM

    I have developed a provider hosted app in SharePoint 2013. As you already know, Visual Studio creates web application and SharePoint app. The web application gets hosted inside IIS and the SharePoint App in SharePoint site collection. I'm trying to get
    data from a list hosted in SharePoint using CSOM. But I get ran insecure content error. 
    here is my code in Default.aspx
        <script type="text/javascript" src="../Scripts/jquery-1.8.2.js"></script>
        <script type="text/javascript" src="../Scripts/MicrosoftAjax.js"></script>
        <script type="text/javascript" src="../Scripts/SP.Core.js"></script>
        <script type="text/javascript" src="../Scripts/INIT.JS"></script>
        <script type="text/javascript" src="../Scripts/SP.Runtime.js"></script>
        <script type="text/javascript" src="../Scripts/SP.js"></script>
        <script type="text/javascript" src="../Scripts/SP.RequestExecutor.js"></script>
        <script type="text/javascript" src="../Scripts/App.js"></script>
        <html xmlns="http://www.w3.org/1999/xhtml">
        <head runat="server">
            <title></title>
        </head>
        <body>
            <form id="form1" runat="server">
            <div>
                <input id="Button1" type="button" value="Get title via CSOM" onclick="execCSOMTitleRequest()" /> <br />
                <input id="Button2" type="button" value="Get Lists via CSOM" onclick="execCSOMListRequest()" />
            </div>
                <p ID="lblResultTitle"></p><br />
                <p ID="lblResultLists"></p>
            </form>
        </body>
        </html>
    and App.js is:
        var hostwebUrl;
        var appwebUrl;
        // Load the required SharePoint libraries
        $(document).ready(function () {
            //Get the URI decoded URLs.
            hostwebUrl =
                decodeURIComponent(
                    getQueryStringParameter("SPHostUrl")
            appwebUrl =
                decodeURIComponent(
                    getQueryStringParameter("SPAppWebUrl")
            // resources are in URLs in the form:
            // web_url/_layouts/15/resource
            var scriptbase = hostwebUrl + "/_layouts/15/";
            // Load the js files and continue to the successHandler
            //$.getScript(scriptbase + "/MicrosoftAjax.js",
            //   function () {
            //       $.getScript(scriptbase + "SP.Core.js",
            //           function () {
            //               $.getScript(scriptbase + "INIT.JS",
            //                   function () {
            //                       $.getScript(scriptbase + "SP.Runtime.js",
            //                           function () {
            //                               $.getScript(scriptbase + "SP.js",
            //                                   function () { $.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest); }
        function execCrossDomainRequest() {
            alert("scripts loaded");
        function getQueryStringParameter(paramToRetrieve) {
            var params = document.URL.split("?")[1].split("&");
            var strParams = "";
            for (var i = 0; i < params.length; i = i + 1) {
                var singleParam = params[i].split("=");
                if (singleParam[0] == paramToRetrieve)
                    return singleParam[1];
        function execCSOMTitleRequest() {
            var context;
            var factory;
            var appContextSite;
            var collList;
            //Get the client context of the AppWebUrl
            context = new SP.ClientContext(appwebUrl);
            //Get the ProxyWebRequestExecutorFactory
            factory = new SP.ProxyWebRequestExecutorFactory(appwebUrl);
            //Assign the factory to the client context.
            context.set_webRequestExecutorFactory(factory);
            //Get the app context of the Host Web using the client context of the Application.
            appContextSite = new SP.AppContextSite(context, hostwebUrl);
            //Get the Web
            this.web = context.get_web();
            //Load Web.
            context.load(this.web);
            context.executeQueryAsync(
                Function.createDelegate(this, successTitleHandlerCSOM),
                Function.createDelegate(this, errorTitleHandlerCSOM)
            //success Title
            function successTitleHandlerCSOM(data) {
                $('#lblResultTitle').html("<b>Via CSOM the title is:</b> " + this.web.get_title());
            //Error Title
            function errorTitleHandlerCSOM(data, errorCode, errorMessage) {
                $('#lblResultLists').html("Could not complete CSOM call: " + errorMessage);
        function execCSOMListRequest() {
            var context;
            var factory;
            var appContextSite;
            var collList;
            //Get the client context of the AppWebUrl
            context = new SP.ClientContext(appwebUrl);
            //Get the ProxyWebRequestExecutorFactory
            factory = new SP.ProxyWebRequestExecutorFactory(appwebUrl);
            //Assign the factory to the client context.
            context.set_webRequestExecutorFactory(factory);
            //Get the app context of the Host Web using the client context of the Application.
            appContextSite = new SP.AppContextSite(context, hostwebUrl);
            //Get the Web
            this.web = context.get_web();
            // Get the Web lists.
            collList = this.web.get_lists();
            //Load Lists.
            context.load(collList);
            context.executeQueryAsync(
                Function.createDelegate(this, successListHandlerCSOM),
                Function.createDelegate(this, errorListHandlerCSOM)
            //Success Lists
            function successListHandlerCSOM() {
                var listEnumerator = collList.getEnumerator();
                $('#lblResultLists').html("<b>Via CSOM the lists are:</b><br/>");
                while (listEnumerator.moveNext()) {
                    var oList = listEnumerator.get_current();
                    $('#lblResultLists').append(oList.get_title() + " (" + oList.get_itemCount() + ")<br/>");
            //Error Lists
            function errorListHandlerCSOM(data, errorCode, errorMessage) {
                $('#lblResultLists').html("Could not complete CSOM Call: " + errorMessage);
    Any solution is appreciated.

    Hi,
    To retrieve data from list in your provider-hosted app using SharePoint Client Object Model(CSOM), you can follow the links below for a quick start:
    http://msdn.microsoft.com/en-us/library/office/fp142381(v=office.15).aspx
    http://blogs.msdn.com/b/steve_fox/archive/2013/02/22/building-your-first-provider-hosted-app-for-sharepoint-part-2.aspx
    Best regards
    Patrick Liang
    TechNet Community Support

  • SharePoint Provider Hosted App that can update existing SharePoint Task List

    Note: I am unable to take advantage of the Microsoft.SharePoint library directly. Adding a reference results in a 32bit/64bit library mismatch error.
    I have to find a solution that uses only the Microsoft.SharePoint.Client extension. 
    I am looking for example code where provider-hosted SharePoint App loads a SharePoint Task List View that allows users to interact with the tasks.
    So far I have only been able to programmatically create and then load the SharePoint tasks list, create and populate a DataTable object and set the datasource of a GridView object to that DataTable.
    I am unable to trigger my method linked to my checkbox within the gridview.
    Ideally I would like to just customize a Task View that already has this functionality.
    Here is my default.aspx.cs code-behind file:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    using SP = Microsoft.SharePoint.Client;
    namespace SPAppBasicWeb
    public partial class Default : System.Web.UI.Page
    protected void Page_PreInit(object sender, EventArgs e)
    Uri redirectUrl;
    switch (SharePointContextProvider.CheckRedirectionStatus(Context, out redirectUrl))
    case RedirectionStatus.Ok:
    return;
    case RedirectionStatus.ShouldRedirect:
    Response.Redirect(redirectUrl.AbsoluteUri, endResponse: true);
    break;
    case RedirectionStatus.CanNotRedirect:
    Response.Write("An error occurred while processing your request.");
    Response.End();
    break;
    protected void Page_Load(object sender, EventArgs e)
    // The following code gets the client context and Title property by using TokenHelper.
    // To access other properties, the app may need to request permissions on the host web.
    var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
    using (var clientContext = spContext.CreateUserClientContextForSPHost())
    //clientContext.Load(clientContext.Web, web => web.Title);
    //clientContext.ExecuteQuery();
    //Response.Write(clientContext.Web.Title);
    SP.ClientContext cc = new SP.ClientContext("http://server/sites/devapps");
    SP.Web web = cc.Web;
    SP.List list = web.Lists.GetByTitle("General Tasks");
    SP.CamlQuery caml = new SP.CamlQuery();
    Microsoft.SharePoint.Client.ListItemCollection items = list.GetItems(caml);
    cc.Load<Microsoft.SharePoint.Client.List>(list);
    cc.Load<Microsoft.SharePoint.Client.ListItemCollection>(items);
    //try
    //const int ColWidth = 40;
    cc.ExecuteQuery();
    DataTable dt = new DataTable();
    dt.Columns.Add("Task Name", typeof(string));
    dt.Columns.Add("ID", typeof(int));
    foreach (Microsoft.SharePoint.Client.ListItem liTask in items)
    DataRow dr = dt.NewRow();
    dr["Task Name"] = liTask["Title"];
    dr["ID"] = liTask["ID"];
    //dr["chkTask"] = liTask["Checkmark"];
    dt.Rows.Add(dr);
    GridView1.DataSource = dt;
    GridView1.DataBind();
    protected void chkTask_CheckedChanged(object sender, EventArgs e)
    //add code here to update Task Item by ID
    Response.Write("checkbox event triggered");
    Here is my simple default.aspx:
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="SPAppBasicWeb.Default" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <title></title>
    </head>
    <body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView ID="GridView1" runat="server">
    <Columns>
    <asp:TemplateField>
    <ItemTemplate>
    <asp:CheckBox ID="chkTask" runat="server" OnCheckedChanged="chkTask_CheckedChanged" AutoPostBack="true" />
    </ItemTemplate>
    </asp:TemplateField>
    </Columns>
    </asp:GridView>
    </div>
    </form>
    </body>
    </html>
    http://www.net4geeks.com Who said I was a geek?

    Hi,
    Please try to modify your code as below:
    using (var clientContext = spContext.CreateUserClientContextForSPHost())
    SP.Web web = clientContext.Web;
    SP.List list = web.Lists.GetByTitle("General Tasks");
    SP.CamlQuery caml = new SP.CamlQuery();
    Microsoft.SharePoint.Client.ListItemCollection items = list.GetItems(caml);
    clientContext.Load(items);
    clientContext.ExecuteQuery();
    If the code still not works, I suggest you debug the code or following the blog below to create a Provider-Hosted App for SharePoint and read list items from SharePoint list.
    http://blogs.msdn.com/b/steve_fox/archive/2013/02/22/building-your-first-provider-hosted-app-for-sharepoint-part-2.aspx
    Best Regards
    Dennis Guo
    TechNet Community Support

  • Using powershell to deploy provider-hosted app and specify remote Url instead of using appinv.aspx page

    Hello all,
    Could you possibly help me with provider-hosted app development/deployment process.
    We developed SharePoint provider-hosted app that works just fine in development environment. Now we need to automate it's installation in test environment via powershell.
    In AppManifest.xml that we are deploying we have key instead of explicit URL:
    <App xmlns="http://schemas.microsoft.com/sharepoint/2012/app/manifest" Name="ShowAllRoomsApp" ProductID="{922a18aa-5592-b59a-4da9-4791baef02e7}" Version="1.0.0.0"
    SharePointMinVersion="15.0.0.0">
      <Properties>
        <Title>SomeTitle</Title>
        <StartPage>~remoteAppUrl/Pages/Default.aspx?{StandardTokens}</StartPage>
    If we use as
    https://technet.microsoft.com/en-us/library/jj655398.aspx recommends, we cannot specify Redirect Url as we can do this on
    /_layouts/appinv.aspx
    So now it seems like the only way to deploy this kind of solution is using appinv.aspx page.Or must we apply this URL in AppManifest on developing stage in Visual Studio?
    What did I miss?
    P. S. Even if I use /_layouts/appinv.aspx after powershell commandlets, I get error.

    hi,
    to deploy provider hosted app you need 2 things
    1. Client ID
    2. Redirect URL.
    What you can do you can generate app from visual studio using clientID and URL from developer enviornment.
    Now a app file is just a simple compressed zip file if you rename it as .zip and extract you will find AppManifest
    inside it. So to create an app for Testing enviornment what you have to to Get the CLient ID (from AppRegNew.aspx) in testing enviornment. Unzip .App file change the AppManifest with testing client ID and URL than again zip file and rename as .app.
    Now if you upload this file it will work.
    To automate this scenerio i have created a simple windows Application in which i Pass the Client ID and StartURl and an App File it unzips the app file make changes to app and again zip it.
    public static class AppPackageHelper
    public const string StartUrlExpression = "{0}?{1}";
    public const string StandardToken = "{StandardTokens}";
    public static string Publish(string appPath, string ClientId,string StartUrl)
    string tempDir = string.Empty;
    string outPutFile = string.Empty;
    try
    string parentDir = System.IO.Path.GetDirectoryName(appPath);
    outPutFile = System.IO.Path.Combine(parentDir, ClientId + "-Winshuttle.app");
    tempDir = System.IO.Path.Combine(parentDir, ClientId.ToString());
    Directory.CreateDirectory(tempDir);
    int lastInd = appPath.LastIndexOf('.');
    string tempPath = string.Empty;
    string targetFilePath = string.Empty;
    string cabPath = System.IO.Path.Combine(tempDir, System.IO.Path.GetFileNameWithoutExtension(appPath) + ".cab");
    FileInfo fInfo = new FileInfo(appPath) { IsReadOnly = false };
    File.Copy(appPath, cabPath);
    XDocument doc = null;
    string appManifest = string.Empty;
    using (ZipArchive zipArch = ZipFile.Open(cabPath, ZipArchiveMode.Update))
    appManifest = string.Format(@"{0}\AppManifest.xml", Directory.GetParent(cabPath).FullName);
    ZipArchiveEntry manifestEntry = zipArch.Entries.LastOrDefault(e => e.Name.ToLower() == "appmanifest.xml");
    manifestEntry.ExtractToFile(appManifest);
    doc = XDocument.Load(appManifest);
    XNamespace ns = doc.Root.GetDefaultNamespace();
    string defaultUrl = string.Format(StartUrlExpression, StartUrl.TrimEnd('/'), StandardToken);
    doc.Descendants(XName.Get("StartPage", ns.NamespaceName)).First().Value = defaultUrl;
    doc.Descendants(XName.Get("RemoteWebApplication", ns.NamespaceName)).First().Attribute(XName.Get("ClientId")).Value = setupInfo.ClientId.ToString();
    doc.Save(appManifest);
    if (manifestEntry != null)
    manifestEntry.Delete();
    zipArch.CreateEntryFromFile(appManifest, "AppManifest.xml");
    int totEnt = zipArch.Entries.Count;
    for (int e = 0; e < totEnt; e++)
    if (zipArch.Entries[e].Open().Length == 0)
    //if (zipArch.Entries.Count > totEnt && e >= totEnt) break;
    //zipArch.CreateEntry(zipArch.Entries[e].FullName);
    File.Delete(appManifest);
    if (File.Exists(outPutFile))
    File.Delete(outPutFile);
    File.Move(cabPath, outPutFile);
    return outPutFile;
    catch
    throw;
    finally
    if (System.IO.Directory.Exists(tempDir))
    System.IO.Directory.Delete(tempDir, true);
    return outPutFile;
    using System.IO.Compression.FileSystem.dll.
    Also if you want to do it using powershell You need to do the same thing unzip-> changes values-> zip
    So basic thing is You need to ahve only valid AppManifest file which contains 2 valid values Client Id and StartUrl
    if you changes it inside appmanifest manuall than it will also work. Using above code you can create a console Application to do it. You can use powershell it just that i dont know how to zip unzip in powershell but i am pretty sure you can easily find it
    on searching.
    Whenever you see a reply and if you think is helpful,Vote As Helpful! And whenever you see a reply being an answer to the question of the thread, click Mark As Answer

  • Error with Provider Hosted App on Edit Form of a list item

    We have an error on the Edit Form of one of our pages.
    We have developed a SharePoint Online Provider Hosted app which replaces the standard edit form of a list item and has some further events behind the save button. Since this is rather new territory for us, we're using a roundabout way of achieving this by
    using a script editor web part to display an iFrame of our app. That way we can pass the Url through to our app and retrieve query strings from them.
    Our issue comes quite intermittently in that we sometimes get a "web page cannot be found" error or sometimes a "resource cannot be found" error, however, when we load another app on the site (from the same app project, but using an app
    part), then go back to the Edit Form, the information in the iFrame suddenly renders.
    Any ideas on what might be causing this issue at all? Ideally, we should be rendering the app to the Edit Form is the proper manner, rather than scripting an iFrame that points to out app in Azure. Would this be the cause of the problem?
    Thanks
    Tom

    Hi thumper, if you have access to InfoPath, you can add the form to a page using the InfoPath web part. Otherwise, use SP Designer with instructions below:
    http://sharepoint.stackexchange.com/questions/70287/display-new-form-of-a-list-in-a-web-part-page
    cameron rautmann

Maybe you are looking for