Microsoft Modern Authentication - SSO

 In some company, getting application level permissions might be hard to do due to security reason.  Within those environment, setting up a job that runs periodically could be difficult.  One of the way to do it is to make sure your job running account has enough permissions and you have a SPN with enough delegated permissions.

The below code show how to use the logged in account to get access token for SharePoint scope.

public async Task<string> GetSSOUserAccessToken(Uri spSiteUrl) {

var _clientId = "";

var _tenantId = "";

var _scheme = siteUrl.Scheme;

var _hostUrl = siteUrl.host;

var _scope = "AllSites.FullControl";

string[] _scopes = new string[] {string.Format("{0}://{1}/{2}", _schem, _hostUrl, _scope);

var authority = string.Format(CultureInfo.InvariantCulture, "{0}/{1}/", "https://login.microsoftonline.com", _tenantId);

try {

    IPublicClientApplication app = PublicClientApplicationBuilder.Create(_clientId).WithAurhority(new     Uri(authority)).Build();

    var accounts = await app.GetAccountsAsync();

    if (accounts.Any()){

        AuthResult = await app.AcquireTokenSilent(_scopes, accounts.FirstOrDefault()).ExecuteAsync();

    }

    else{

        AuthResult = await app.AcquireTokenByIntegratedWindowsAuth(_scope).ExecuteAsync(CancellationToken.None);

    }

    return AuthResult.AccessToken;

    }

    catch (Exception ex){

        Log.Log(ex.ToString());

    }

}


And then below code would be how to create SharePoint ClientContext from the access token

public async Task<ClientContext> GetSSOUserContext(string spUrl, string userAgent, string clientTag = ""){

    var context = new ClientContext(spUrl);

    string token = await GetSSOUserAccessToken(new Uri(spUrl));

    context.ExecutingWebRequest += (s, e) => {

        e.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + token;

        e.WebRequestExecutor.WebRequest.UserAgent = userAgent;

    };

    if (!String.InNullOrEmpty(clientTag)){

        context.CliengTag = clientTag;

    }

    return   context; 

}

Comments

Popular posts from this blog

SharePoint 2013 - Working with Display Template for Content Search Web Part

How to Customize MOSS Site Manager (Site Content and Structure Page)

Add spell check dictionary in SharePoint 2010, SharePoint 2013, and Office 365