Wednesday 30 December 2015

SharePoint Designer Workflow Limitations

The limitations below are listed in relative priority with the most important or most likely to be encountered toward the top.
  • You cannot access the previous value of a field. This means that you cannot check to see if a field changed. There is an action that waits for a field to change, but you must provide the value that it changes to. Alternatively you can compare it to another field, but not the previous value of that field. If the field didn’t change at all but met the condition implied by the action, this wait action likely wouldn’t wait at all and move on the next step in the workflow.
  • Workaround: Use a SharePoint list event to track “ItemUpdating” and pass in the “After” value for a field (the current value will be the old value in a synchronous updating event). If you decide to also start this workflow from any asynchronous event (e.g., “ItemAdded” and/or “ItemUpdated”), you will need to pass in the event trigger (e.g., “Add”, “Updating”, “Updated”) so the workflow can differentiate between them (the current item in the workflow will be the old item for synchronous events, but it will be the new value for asynchronous events).
  • You cannot loop. If you want to perform an action on say all items in a list or all child items for a parent, you simply cannot do it unless you know how to lookup each item in the list at design time and have an action for each of those items.
  • Workaround: Use Events or a Visual Studio 2005 workflow.
  • You cannot lookup an item using two keys. If one key does not uniquely identify an item, you are stuck. You can try to just use one field, but the workflow will act on the first item it finds. You cannot use two fields to identify it.
  • Workaround: Use Events or a Visual Studio 2005 workflow.
  • You cannot copy the contents of one email action to use it within the same or another email action. This is true if there are any lookups within the email contents.
  • Workaround: Copy by hand (re-write the contents) or after saving the .xoml file, open it with an XML editor (right click the .xoml file and choose Open With -> SharePoint Designer (Open as XML)), then copy/paste the appropriate data.
  • You cannot put lookup information in the subject of an email.
  • Workaround: The easiest workaround is to put the lookup information in the email body. More complex solutions involve creating a custom SharePoint Designer workflow action, using a Visual Studio 2005 workflow, or sending the email from an event.
  • You cannot group logical conditions within a step by using parenthesis.
  • Workaround: Modify your expression such that the order takes precedence. For example, instead of “x=1 and (y=2 or z=3)” use “y=2 or z=3 and x=1”. .
  • You cannot easily log a value with context information to the workflow history list.
  • Workaround: Use the Build Dynamic String action to store your log into a workflow variable then use the Log to History List action to log the workflow variable to the history list.
  • You can run actions in parallel, but you cannot run steps in parallel.
  • Workaround: Use a Visual Studio 2005 workflow.
  • You can relate to lists once or more removed from the current list. For example, you can use the current item and lookup to a related list and use that item to lookup to another list (or maybe a different item in the original list).
  • You can build dynamic strings or calculated values and put them into workflow variables then use those variables to set list items. Note that the calculations are simple: plus, minus, multiply by, divide by, mod.
SharePoint Designer 2010​ has a limitation when trying to implement a workflow action to send an email to multiple users based from lookup from a people picker control that accepts more than one user. By default the email action will only email to the first user and will not detect multiple users. 

Friday 25 December 2015

Difference between clientcontext.load() and clientcontext.executeQuery()

our data resides in a remote location (our SharePoint server), so we cannot directly access it. In fact this is true even of any server-side programming, it is only less obvious.

When we call Load, we are only preparing our query. As this article states, in SQL terms think of it of building the SELECT statement.
The  ExecuteQuery , submits our prepared query to the remote server and retrieve the specified data.

The difference between ExecuteQuery and ExecuteQueryAsync is whether you will wait for the web request to return in-place (in the same execution path) or you will submit a callback function to handle the return when it does come back. It has an impact on how you will structure your code, but not so much on the end result.

So, to be clear:

No communication occurs with the remote server until you call ExecuteQuery or ExecuteQueryAsync
You can build up your query by calling Load multiple times, even for properies of different objects, and the client API will construct the appropriate query.
You can narrow down the exact properties to fetch so as to be as brief as possible in your web traffic
Basically these are typical client-server communication patterns, and not at all unique to SharePoint

Simply we can state : Load is to prepare query what you want from the server and executeQueryAsync/executeQuery is to get the data from the server

Tuesday 22 December 2015

How the SharePoint 2013 REST service works

In computing, representational state transfer (REST) is the software architectural style of the World Wide Web.RESTful systems typically, but not always, communicate over Hypertext Transfer Protocol (HTTP) with the same HTTP verbs (GET, POST, PUT, DELETE, etc.) which web browsers use to retrieve web pages and to send data to remote servers. REST interfaces with external systems using resources identified by Uniform Resource Identifier (URI), for example /people/tom, which can be operated upon using standard verbs, such as DELETE /people/tom.

SharePoint 2013 introduces a Representational State Transfer (REST) service that is comparable to the existing SharePoint client object models. Now, developers can interact remotely with SharePoint data by using any technology that supports REST web requests. This means that developers can perform Create, Read, Update, and Delete (CRUD) operations from their SharePoint Add-ins, solutions, and client applications, using REST web technologies and standard Open Data Protocol (OData) syntax.

SharePoint 2013 adds the ability for you to remotely interact with SharePoint sites by using REST. Now, you can interact directly with SharePoint objects by using any technology that supports standard REST capabilities.
To access SharePoint resources using REST, construct a RESTful HTTP request, using the Open Data Protocol (OData) standard, which corresponds to the desired client object model API. For example:
Client object model method:
List.GetByTitle(listname)
REST endpoint:
http://server/site/_api/lists/getbytitle('listname')
The client.svc web service in SharePoint handles the HTTP request, and serves the appropriate response in either Atom or JSON (JavaScript Object Notation) format. Your client application must then parse that response. The figure below shows a high-level view of the SharePoint REST architecture.



SharePoint REST service architecture

SharePoint REST service architecture

Construct REST URLs to access SharePoint resources

Whenever possible, the URI for these REST endpoints closely mimics the API signature of the resource in the SharePoint client object model. The main entry points for the REST service represent the site collection and site of the specified context.
To access a specific site collection, use the following construction:
http://server/site/_api/site
To access a specific site, use the following construction:
http://server/site/_api/web
In each case, server represents the name of the server, and site represents the name of, or path to, the specific site.
From this starting point, you can then construct more specific REST URIs by ''walking" the object model, using the names of the APIs from the client object model separated by a forward slash (/).

SharePoint REST endpoint examples
Description
URL endpoint
HTTP method
Body content
Retrieves the title of a list
web/title
GET
Not applicable
Retrieves all lists on a site
lists
GET
Not applicable
Retrieves a single 'list's metadata
lists/getbytitle('listname')
GET
Not applicable
Retrieves items within a list
lists/getbytitle('listname')/items
GET
Not applicable
Retrieves a specific property of a document. (In this case, the document title.)
lists/getbytitle('listname')?select=Title
GET
Not applicable
Creates a list
lists
POST
{
  '_metadata':{'type':SP.List},
  'AllowContentTypes': true,
  'BaseTemplate': 104,
  'ContentTypesEnabled': true,
  'Description': 'My list description',
  'Title': 'RestTest'
}
Adds an item to a list
lists/getbytitle('listname')/items
POST
{
  '_metadata':{'type':SP.listnameListItem},
  'Title': 'MyItem'
}






Thursday 3 December 2015

How to check that a user is Admin in SharePoint CSOM

SharePoint 2013 CSOM
Use User.IsSiteAdmin property to get or set a Boolean value that specifies whether the user is a site collection administrator, for example:
using (var ctx = new ClientContext(webUri))
{
    var currentUser = ctx.Web.CurrentUser;
    ctx.Load(currentUser);
    ctx.ExecuteQuery();

    Console.WriteLine(currentUser.IsSiteAdmin);
}
SharePoint 2010 CSOM
Since User object does not expose IsSiteAdmin property in SharePoint 2010 CSOM, below is demonstrated how to determine whether current user is Site Administrator using User Information List:
using (var ctx = new ClientContext(url))
{ 
     var currentUser = ctx.Web.CurrentUser;
     ctx.Load(currentUser);
     ctx.ExecuteQuery();

     var isCurrentUserSiteAdmin = IsUserSiteAdmin(ctx, currentUser.Id);
}


public static bool IsUserSiteAdmin(ClientContext ctx,int userId)
{
   var userInfoList = ctx.Site.RootWeb.SiteUserInfoList;
   var item = userInfoList.GetItemById(userId);
   ctx.Load(item);
   ctx.ExecuteQuery();
   return (bool)item["IsSiteAdmin"];
}                  

oAuth (Authentication) in remote apps in Office 365 and SharePoint Online

This post is detailing about how you perform authentication and authorization from a remote app in SharePoint Online. 
Especially, when the remote apps are running on a Non .Net technology platforms. Which means we can’t use the OOTB ‘TokenHelper’ class. 
The entire flow needs to only use simple HttpRequests.
I am going to break this into 3 parts:
  1. Register a Remote App in SharePoint
  2. Get the 'AccessToken’ via the Azure ACS and SharePoint dance
  3. Call SharePoint REST Service with the AccessToken
Right now I am using the .Net HttpRequest class to perform this entire example and understand the entire flow. I am going to convert this into a JavaScript library soon so that it can be easily consumed by any external platforms. Ok, so lets get started. 

Register a Remote App in SharePoint

There is some good guidance around registering an app for SharePoint but in our case we just want to register an app to perform the OAuth from a remote application so the only good option is to register it via ‘/_layouts/15/appregnew.aspx’. 

image 
There are 3 pieces of information that we need from the app registration:
  • client_id          = App Id
  • client_secret   = App Secret
  • redirect_uri     = Redirect URI

Get the 'AccessToken’ via the Azure ACS and SharePoint dance

There are 3 steps to this dance:
Step 1: Get the Request token 
Getting the request token just requires a well formed Url with all the 3 pieces of information that we collected during the app registration. 

image 
(See this app permissions section for all the Scope and Rights available in SharePoint Online.) This Url would redirect to the msonline login screen and after you enter the credentials if you prompt you with the trust screen: 

image
 
image 

Once you trust the app, it would redirect back to the ‘redirect_uri’ configured during the app registration along with the request token in the querystring 

image 

Step 2: Get the Realm

image 
(This method is taken directly from TokenHelper class. The targetApplicationUri is the SharePoint Online url) 
Step 3: And finally, Get the Access Token 
Now that we have the requestToken and realm, we need to create a POST request to ACS to get back the access token 

image

Call SharePoint REST Service with the AccessToken

The only thing to remember before calling the SharePoint REST API’s is to make sure that we requested the correct Scope and Rights while generating the access token. In the code above I request ‘AllProfile.Manage’ as my scope so I can call the User Profile REST API’s.
image 
That’s it. Once we have the access token we can call all the SharePoint REST API’s that fetches the data.

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