Yes, you can use app-only policy to access SharePoint Online. First step is to allow it in your app.manifest.
Second step may be little tricky. I did it about a year ago and it required to modify TokenHelper.cs
file.
My case was simple, as I was making exclusively app-only calls. I did not use SharePointContext
or SharePointContextFilterAttribute
, so I removed them from my code. I relied on TokenHelper
to create ClientContext
. By default it was throwing exceptions when
I see now, that with current version of TokenHelper.cs
no user was loggedmodifications are required. I've created new SharePoint App project in Visual Studio, removed files mentioned earlier and edited (NullReference if I recall correctly)HomeController
. Eventually using debugger I was able to find place where this exception originated and modify TokenHelperuser.Title
to ignore userreturns "SharePoint App".
I know this answer isn't too specific, but I just wanted to point out that it is possible to do it this way.
public ActionResult Index()
{
var uri = new Uri("https://sample.sharepoint.com/sites/sample/");
var accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, uri.Authority, TokenHelper.GetRealmFromTargetUrl(uri));
using (var context = TokenHelper.GetClientContextWithAccessToken(uri.ToString(), accessToken.AccessToken))
{
var web = context.Web;
var user = web.CurrentUser;
context.Load(user, u => u.Title);
context.ExecuteQuery();
ViewBag.UserName = user.Title;
}
return View();
}
}