Microsoft.SharePoint.Client.ServerUnauthorizedAccessException: Access denied - sharepoint

I encountered an exception when I used c# code to create subdirectories in sharepoint's specified directory.
Exception message:
Microsoft.SharePoint.Client.ServerUnauthorizedAccessException: Access denied. You do not have permission to perform this action or access this resource.
Anybody can help me? thanks!
The following is parameters:
file: D:\Repos\helpfilesync\ArtefactUploader\bin\Release\ArtefactUploader.exe
fileName: ArtefactUploader.exe
uploadPath: /sites/Platform/Shared Documents/dailybuild/helpfilesync/
subFolderPath: v0.1.0/
public void Upload()
{
using (ClientContext clientContext = new ClientContext("*****"))
{
SecureString pass = new SecureString();
foreach (char ch in password)
{
pass.AppendChar(ch);
}
clientContext.Credentials = new SharePointOnlineCredentials(user, pass);
Web web = clientContext.Web;
clientContext.Load(web);
clientContext.ExecuteQuery();
if (!string.IsNullOrWhiteSpace(this.subFolderPath))
{
CreateFolder(clientContext.Web, uploadPath, subFolderPath);
}
using (FileStream fs = new FileStream(file, FileMode.Open))
{
Microsoft.SharePoint.Client.File.SaveBinaryDirect
(clientContext, $"{this.uploadPath}{this.subFolderPath}/{fileName}", fs, true);
}
Console.WriteLine("Uploaded File Successfully");
}
}
public void CreateFolder(Web web, string relativePath, string fullFolderPath)
{
if (web == null)
{
throw new ArgumentNullException(nameof(web));
}
if (string.IsNullOrWhiteSpace(relativePath))
{
throw new ArgumentNullException(nameof(relativePath));
}
if (string.IsNullOrWhiteSpace(fullFolderPath))
{
throw new ArgumentNullException(fullFolderPath);
}
Folder relativeFolder = web.GetFolderByServerRelativeUrl(relativePath);
CreateFolderInternal(web, relativeFolder, fullFolderPath);
}
public static Folder CreateFolderInternal(Web web, Folder parentFolder, string fullFolderPath)
{
var folderUrls = fullFolderPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
string folderUrl = folderUrls[0];
var curFolder = parentFolder.Folders.Add(folderUrl);
//web.Context.Load(curFolder);
try
{
web.Context.ExecuteQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
if (folderUrls.Length > 1)
{
var folderPath = string.Join("/", folderUrls, 1, folderUrls.Length - 1);
return CreateFolderInternal(web, curFolder, folderPath);
}
return curFolder;
}
Microsoft.SharePoint.Client.ServerUnauthorizedAccessException: Access
denied. You do not have permission to perform this action or access
this resource. at
Microsoft.SharePoint.Client.ClientRequest.ProcessResponseStream(Stream
responseStream) at
Microsoft.SharePoint.Client.ClientRequest.ProcessResponse() at
Microsoft.SharePoint.Client.ClientContext.ExecuteQuery() at
ArtefactUploader.SharepointUploader.CreateFolderInternal(Web web,
Folder parentFolder, String fullFolderPath) in
D:\Repos\helpfilesync\ArtefactUploader\SharepointUploader.cs:line 96

Did test of your code, works fine. Make sure the user/password is correct.
class Program
{
const string user = "user#teanat.onmicrosoft.com";
const string password = "password";
public static void Upload()
{
using (ClientContext clientContext = new ClientContext("https://tenant.sharepoint.com/sites/lee"))
{
SecureString pass = new SecureString();
foreach (char ch in password)
{
pass.AppendChar(ch);
}
clientContext.Credentials = new SharePointOnlineCredentials(user, pass);
Web web = clientContext.Web;
clientContext.Load(web);
clientContext.ExecuteQuery();
if (!string.IsNullOrWhiteSpace("a"))
{
CreateFolder(clientContext.Web, "/sites/lee/mydoc2", "childA");
}
//using (FileStream fs = new FileStream(file, FileMode.Open))
//{
// Microsoft.SharePoint.Client.File.SaveBinaryDirect
// (clientContext, $"{this.uploadPath}{this.subFolderPath}/{fileName}", fs, true);
//}
Console.WriteLine("Uploaded File Successfully");
}
}
public static void CreateFolder(Web web, string relativePath, string fullFolderPath)
{
if (web == null)
{
throw new ArgumentNullException(nameof(web));
}
if (string.IsNullOrWhiteSpace(relativePath))
{
throw new ArgumentNullException(nameof(relativePath));
}
if (string.IsNullOrWhiteSpace(fullFolderPath))
{
throw new ArgumentNullException(fullFolderPath);
}
Folder relativeFolder = web.GetFolderByServerRelativeUrl(relativePath);
CreateFolderInternal(web, relativeFolder, fullFolderPath);
}
public static Folder CreateFolderInternal(Web web, Folder parentFolder, string fullFolderPath)
{
var folderUrls = fullFolderPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
string folderUrl = folderUrls[0];
var curFolder = parentFolder.Folders.Add(folderUrl);
//web.Context.Load(curFolder);
try
{
web.Context.ExecuteQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
if (folderUrls.Length > 1)
{
var folderPath = string.Join("/", folderUrls, 1, folderUrls.Length - 1);
return CreateFolderInternal(web, curFolder, folderPath);
}
return curFolder;
}
static void Main(string[] args)
{
Upload();
}
}

Related

How to find object type from URL SharePoint online (o365)?

I found out how to determine the object type from URL for SharePoint on prem:
https://blogs.msdn.microsoft.com/sanjaynarang/2009/04/06/find-sharepoint-object-type-from-url/
But I didn't find anything for SharePoint Online (CSOM).
Is it possible for SharePoint online?
For the most scenarios such as:
folder url, e.g. https://contoso.sharepoint.com//Documents/Forms/AllItems.aspx?RootFolder=%2FDocuments%2FArchive
list item url, e.g. https://contoso.sharepoint.com/Lists/ShoppingCart/DispForm.aspx?ID=9
list/library url, e.g. https://contoso.sharepoint.com/Lists/Announcements
page url, e.g. https://contoso.sharepoint.com/Lists/Announcements/Newsletter.aspx
the following example demonstrates how to determine client object type:
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Web;
using Microsoft.SharePoint.Client;
namespace O365Console
{
static class ClientObjectExtensions
{
public static ClientObject ResolveClientObjectFromUrl(string resourceUrl, ICredentials credentials)
{
ClientObject targetObject = null;
var resourceUri = new Uri(resourceUrl);
using (var rootCtx = new ClientContext(resourceUri.Scheme + Uri.SchemeDelimiter + resourceUri.Host))
{
rootCtx.Credentials = credentials;
var webUrl = Web.WebUrlFromPageUrlDirect(rootCtx, resourceUri);
using (var ctx = new ClientContext(webUrl.ToString()))
{
ctx.Credentials = credentials;
var queryBag = System.Web.HttpUtility.ParseQueryString(resourceUri.Query);
if (queryBag["Id"] != null)
{
var listUrl = string.Join(string.Empty,
resourceUri.Segments.Take(resourceUri.Segments.Length - 1));
var list = ctx.Web.GetList(listUrl);
targetObject = TryRetrieve(() => list.GetItemById(Convert.ToInt32(queryBag["Id"])));
}
else if (queryBag["RootFolder"] != null)
{
var folderUrl = HttpUtility.UrlDecode(queryBag["RootFolder"]);
targetObject = TryRetrieve(() => ctx.Web.GetFolderByServerRelativeUrl(folderUrl));
}
else if (queryBag.Count > 0)
{
throw new Exception("Unsupported query string parameter found");
}
else
{
targetObject = TryRetrieve(() => ctx.Web.GetFileByServerRelativeUrl(resourceUri.AbsolutePath));
if (targetObject == null)
{
targetObject = TryRetrieve(() => ctx.Web.GetList(resourceUri.AbsolutePath),list => list.RootFolder);
if (targetObject == null || ((List)targetObject).RootFolder.ServerRelativeUrl != resourceUri.AbsolutePath)
targetObject = TryRetrieve(() => ctx.Web.GetFolderByServerRelativeUrl(resourceUri.AbsolutePath));
}
}
}
}
return targetObject;
}
private static T TryRetrieve<T>(Func<T> loadMethod, params Expression<Func<T,object>>[] retrievals) where T : ClientObject
{
try
{
var targetObject = loadMethod();
targetObject.Context.Load(targetObject, retrievals);
targetObject.Context.ExecuteQuery();
return targetObject;
}
catch
{
}
return default(T);
}
}
}
Usage
var credentials = GetCredentials(userName, password);
var clientObj = ClientObjectExtensions.ResolveClientObjectFromUrl("https://contoso.sharepoint.com/Lists/Announcements", credentials);
Console.WriteLine(clientObj.GetType().Name);
where
static ICredentials GetCredentials(string userName,string password)
{
var securePassword = new SecureString();
foreach (var c in password)
{
securePassword.AppendChar(c);
}
return new SharePointOnlineCredentials(userName, securePassword);
}

Need help to deal with Photo for Xamarin forms

I am using xamarin forms. I want to pick photo from gallery for my iphone app and want to save it in Azure DB. Is there any solution available for xamarin forms. Or Is there any plugin available to deal with Photo, Document, or Audio. Any help is appreciated.
Using dependency service you can take or pick photos from Android / iPhone :-
Please refer to code below and try to implement the similar code:-
This is the interface in PCL:-
public interface IGalleryProvider
{
Task<List<AttachmentMediaFile>> PickPhotoAsync();
Task<List<AttachmentMediaFile>> PickAudioAsync();
Task<List<AttachmentMediaFile>> PickDocumentAsync();
Task<AttachmentMediaFile> PickProfilePhotoAsync();
Task SaveToGalleryAsync(AttachmentMediaFile file);
}
Below is the code using which you can pick or take photos from iPhone only:-
using AssetsLibrary;
using AVFoundation;
using ELCImagePicker;
using Foundation;
using MediaPlayer;
using MobileCoreServices;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using UIKit;
[assembly: Xamarin.Forms.Dependency(typeof(GalleryProvider))]
namespace SanketSample.MobileApp.Sample.iOS.Common
{
public class GalleryProvider : IGalleryProvider
{
private TaskCompletionSource<List<AttachmentMediaFile>> _audioPickedTask;
public async Task<List<AttachmentMediaFile>> PickAudioAsync()
{
_audioPickedTask = new TaskCompletionSource<List<AttachmentMediaFile>>();
var picker = new MPMediaPickerController();
ShowViewController(picker);
picker.ItemsPicked += OnAudioPicked;
picker.DidCancel += OnCancel;
var media = await _audioPickedTask.Task;
return media;
}
private void OnCancel(object sender, EventArgs e)
{
var picker = sender as MPMediaPickerController;
picker.DidCancel -= OnCancel;
picker.DismissViewController(true, null);
_audioPickedTask.TrySetResult(new List<AttachmentMediaFile>());
}
private void OnAudioPicked(object sender, ItemsPickedEventArgs e)
{
var media = new List<AttachmentMediaFile>();
var picker = sender as MPMediaPickerController;
picker.ItemsPicked -= OnAudioPicked;
picker.DismissViewController(true, null);
if (e.MediaItemCollection.Items != null)
{
foreach (var item in e.MediaItemCollection.Items)
{
//var vm1 = (new ViewModelLocator()).AttachmentsVM.SelectedAttachments.Add();
if (!item.IsCloudItem)
{
try
{
//var error = new NSError();
//var asset = new AVUrlAsset(item.AssetURL);
//var exporter = new AVAssetExportSession(asset, item.Title);
//exporter.OutputFileType = "com.apple.m4a-audio";
//AVAssetExportSession session = new AVAssetExportSession(asset, "");
//var reader = new AVAssetReader(asset, out error);
//var settings = new NSDictionary();
//Func<byte[]> bytesGetter = e.MediaItemCollection
//TODO item.Title, item.Title SSSanket,
//var _asset = AVAsset.FromUrl(NSUrl.FromFilename(item.AssetURL.ToString()));
//var _exportSession = new AVAssetExportSession(_asset, AVAssetExportSession.PresetPassthrough);
//_exportSession.OutputFileType = AVFileType.Aiff;
// media.Add(new AttachmentMediaFile(item.AssetURL.AbsoluteString, AttachmentMediaFileType.Audio, null , item.Title));
}
catch (Exception ex)
{
// throw ;
}
}
}
}
_audioPickedTask.TrySetResult(media);
}
public async Task<List<AttachmentMediaFile>> PickDocumentAsync()
{
var task = new TaskCompletionSource<List<AttachmentMediaFile>>();
var allowedUTIs = new string[]
{
UTType.UTF8PlainText,
UTType.PlainText,
UTType.RTF,
UTType.Text,
UTType.PDF,
"com.microsoft.word.doc",
"com.microsoft.excel.xls"
};
var pickerMenu = new UIDocumentMenuViewController(allowedUTIs, UIDocumentPickerMode.Open);
pickerMenu.DidPickDocumentPicker += (sender, args) =>
{
args.DocumentPicker.DidPickDocument += (sndr, pArgs) =>
{
var securityEnabled = pArgs.Url.StartAccessingSecurityScopedResource();
NSError err;
var fileCoordinator = new NSFileCoordinator();
var docs = new List<AttachmentMediaFile>();
// Read bytes.
fileCoordinator.CoordinateRead(pArgs.Url, 0, out err, (NSUrl newUrl) =>
{
NSData data = NSData.FromUrl(newUrl);
docs.Add(new AttachmentMediaFile(pArgs.Url.AbsoluteString, AttachmentMediaFileType.Doc, data.ToArray(),null));
task.TrySetResult(docs);
});
};
ShowViewController(args.DocumentPicker);
};
ShowViewController(pickerMenu);
return await task.Task;
}
public async Task<List<AttachmentMediaFile>> PickPhotoAsync()
{
var media = new List<AttachmentMediaFile>();
var picker = ELCImagePickerViewController.Instance;
picker.MaximumImagesCount = 15;
ShowViewController(picker);
await picker.Completion.ContinueWith(result =>
{
picker.BeginInvokeOnMainThread(() =>
{
picker.DismissViewController(true, null);
if (!result.IsCanceled && result.Exception == null)
{
var imageEditor = new ImageEditor();
var items = result.Result as List<AssetResult>;
foreach (var item in items)
{
var bbytes= imageEditor.ResizeImage(item.Image, 1024, 1024);
media.Add(new AttachmentMediaFile(item.Path, AttachmentMediaFileType.Photo, bbytes, item.Name));
}
}
});
});
return media;
}
public async Task<AttachmentMediaFile> PickProfilePhotoAsync()
{
AttachmentMediaFile selectMediaFile = null;
var picker = ELCImagePickerViewController.Instance;
picker.MaximumImagesCount = 1;
ShowViewController(picker);
await picker.Completion.ContinueWith(result =>
{
picker.BeginInvokeOnMainThread(() =>
{
picker.DismissViewController(true, null);
if (!result.IsCanceled && result.Exception == null)
{
var imageEditor = new ImageEditor();
var items = result.Result as List<AssetResult>;
foreach (var item in items)
{
var bbytes = imageEditor.ResizeImage(item.Image, 1024, 1024);
selectMediaFile = new AttachmentMediaFile(item.Path, AttachmentMediaFileType.Photo, bbytes, item.Name);
}
}
});
});
return selectMediaFile;
}
public async Task SaveToGalleryAsync(AttachmentMediaFile file)
{
var bytes = file.GetBytes();
var originalImage = ImageEditor.ImageFromByteArray(bytes);
var library = new ALAssetsLibrary();
var orientation = (ALAssetOrientation)originalImage.Orientation;
var nsUrl = await library.WriteImageToSavedPhotosAlbumAsync(originalImage.CGImage, orientation);
}
private void ShowViewController(UIViewController controller)
{
var topController = UIApplication.SharedApplication.KeyWindow.RootViewController;
while (topController.PresentedViewController != null)
{
topController = topController.PresentedViewController;
}
topController.PresentViewController(controller, true, null);
}
}
}
Below are useful classes :-
public class AttachmentMediaFile
{
private readonly Func<byte[]> _bytesGetter;
public string LocalPath { get; private set; }
public string Name { get; private set; }
public AttachmentMediaFileType Type { get; private set; }
public AttachmentMediaFile(string localPath, AttachmentMediaFileType type, byte[] bytesGetter, string name = null)
{
LocalPath = localPath;
Type = type;
_bytesGetter = () =>
{
return bytesGetter;
};
if (string.IsNullOrEmpty(name))
{
Name = FileNameHelper.PrepareName(localPath);
}
else
{
Name = name;
}
}
public byte[] GetBytes()
{
return _bytesGetter();
}
}
public enum AttachmentMediaFileType
{
Photo = 0,
Audio = 1,
Doc = 2,
Video = 3,
}
public static class FileNameHelper
{
private const string Prefix = "IMG";
public static string PrepareName(string localPath)
{
var name = string.Empty;
if (!string.IsNullOrEmpty(localPath))
{
name = localPath.Split('/').Last();
}
return name;
}
public static string GenerateUniqueFileName(Extension extension)
{
var format = ".jpg";
var fileName = string.Concat(Prefix, '_', DateTime.UtcNow.Ticks, format);
return fileName;
}
public enum Extension
{
JPG
}
}
Now if you want to store your data to Azure Server Table so you are already using Azure mobile service client SDK similarly you need Blob nuget from Azure using which you can save your photos by making blob objects to Azure server :-
use blob helper nuget from manage nuget package install Microsoft.WindowsAzure.Storage.Auth;
Microsoft.WindowsAzure.Storage.Blob;
this and try to implement the code similarly I given bellow:-
using Acr.UserDialogs;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using SanketSample.MobileApp.sample.Business.Azure;
using SanketSample.MobileApp.sample.Business.Interfaces;
using SanketSample.MobileApp.sample.Models;
using SanketSample.MobileApp.sample.Models.AzureTables;
using SanketSample.MobileApp.sample.Models.Media;
using SanketSample.MobileApp.sample.Utils;
using Xamarin.Forms;
namespace SanketSample.MobileApp.Sanket.Common.Media
{
public class BlobHelper
{
private const string ContainerName = "attachments";
private Dictionary<string, TaskCompletionSource<bool>> _tasks;
private IHttpService _httpservice { get; set; }
#region Singleton Implementation
private static readonly Lazy<BlobHelper> lazyInstance = new Lazy<BlobHelper>(() => new BlobHelper(), true);
private BlobHelper()
{
_tasks = new Dictionary<string, TaskCompletionSource<bool>>();
}
public static BlobHelper Instance
{
get { return lazyInstance.Value; }`enter code here`
}
#endregion Singleton Implementation
public async Task UploadAttachments(IList<AttachmentFile> attachments, long associatedRecordId, string category)
{
foreach (var attachment in attachments)
{
await UploadAttachment(attachment, associatedRecordId, category);
}
}
public async Task UploadAttachment(AttachmentFile attachment, long associatedRecordId, string category)
{
try
{
CommonHelper commonHelper = new CommonHelper();
attachment.ContainerName = ContainerName;
attachment.AssociatedRecordId = associatedRecordId;
//attachment.RecordId = commonHelper.GenerateRecordId();
if (attachment.FileExtension == null)
{
attachment.FileExtension = ConvertType(attachment.MediaFile);
}
attachment.Category = category;
var taskCompletionSource = new TaskCompletionSource<bool>();
if (!_tasks.ContainsKey(attachment.Name))
{ _tasks.Add(attachment.Name, taskCompletionSource); }
else
{
_tasks[attachment.Name] = taskCompletionSource;
}
// _tasks.Add(attachment.Name, taskCompletionSource);
var attachmentsTableOnline = AzureServiceProvider.Instance.GetRemoteTable<AttachmentFile>();
if (CheckInternetConnection.IsConnected())
{
await attachmentsTableOnline.InsertAsync(attachment);
}
var attachmentsTableOffline = AzureServiceProvider.Instance.GetLocalTable<AttachmentFile>();
await attachmentsTableOffline.InsertAsync(attachment);
if (!string.IsNullOrEmpty(attachment.SasQueryString))
{
var credentials = new StorageCredentials(attachment.SasQueryString);
var imageUri = new Uri(attachment.Uri);
var container = new CloudBlobContainer(new Uri(string.Format("https://{0}/{1}",
imageUri.Host, attachment.ContainerName)), credentials);
var blobFromSASCredential = container.GetBlockBlobReference(attachment.Name);
try
{
var bytes = attachment.MediaFile.GetBytes();
await blobFromSASCredential.UploadFromByteArrayAsync(bytes, 0, bytes.Length);
if (CheckInternetConnection.IsConnected())
{
await attachmentsTableOnline.UpdateAsync(attachment);
}
await attachmentsTableOffline.UpdateAsync(attachment);
taskCompletionSource.TrySetResult(true);
}
catch (Microsoft.WindowsAzure.Storage.StorageException ex)
{
// Throws from UploadFromByteArrayAsync, but image uploaded.
System.Diagnostics.Debug.WriteLine($"BlobHelper: {ex}");
taskCompletionSource.TrySetResult(true);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"BlobHelper: {ex}");
taskCompletionSource.TrySetResult(false);
}
}
}
catch (Exception ca)
{
//throw ca;
}
}
/// <summary>
/// Downloads Blob Data boject and returns the Byts[] data
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public async Task<byte[]> DownloadAttachment(AttachmentFile file)
{
byte[] bytes = null;
var fileContainer = file.Uri.Replace(file.Name, string.Empty);
var container = new CloudBlobContainer(new Uri(fileContainer));
var blob = container.GetBlockBlobReference(file.Name);
using (var stream = new MemoryStream())
{
var isExist = await blob.ExistsAsync();
if (isExist)
{
await blob.DownloadToStreamAsync(stream);
bytes = stream.ToArray();
}
}
return bytes;
}
/// <summary>
/// Updates the Attachments Byts in the Azure Local Tables.
/// </summary>
/// <param name="AttachmentFileRecordId">Attachments Byte[] Data.</param>
/// <returns></returns>
public async Task<byte[]> DownloadAttachmentFileDetails(long? AttachmentFileRecordId, IHttpService service)
{
_httpservice = service;
try
{
ResponseWrapper<AttachmentFileDetail> result = new ResponseWrapper<AttachmentFileDetail>();
if (AttachmentFileRecordId != null)
{
var request = Constants.API_BASE_URL + string.Format(Constants.API_ATTACHMENTS_PARAMETERS, AttachmentFileRecordId);
var response = await _httpservice.SendRequestAsync(HttpMethod.Get, request);
result.Status = response.Status;
if (response.IsSuccess)
{
result.Result = JsonConvert.DeserializeObject<AttachmentFileDetail>(response.Result);
if (result.Result == null)
{
result.Status = System.Net.HttpStatusCode.InternalServerError;
}
else
{
var output = result.Result;
var data = new List<AttachmentFileDetail>() { output };
await AzureServiceProvider.Instance.DatabaseService.InsertDataToLocalDB<AttachmentFileDetail>(data);
return result.Result.FileByteArray;
}
}
}
}
catch (Exception ex)
{
////throw ex;
}
finally
{
}
return null;
}
private string ConvertType(AttachmentMediaFile file)
{
switch (file.Type)
{
case AttachmentMediaFileType.Doc:
return "doc";
case AttachmentMediaFileType.Audio:
return "mp3";
}
return "jpeg";
}
}
}
media plugin on github
works pretty well for me.

Azure Graph API Authentication_MissingOrMalformed

I am using Azure Graph API to import users from Azure AD. In the azure portal I have added multiple Applications.
I am getting clientId, tenantId from protal and creating a secret key with one year expiry. Using these values I am creating an access_token and using that token connecting to AD.
Here is the code
public static String loginUrlPrefix = "https://login.windows.net/";
public static String loginUrlSufix = "/oauth2/token";
public static String importUrl = "https://management.core.windows.net/<subscription-id>/services/importexport/";
#SuppressWarnings("deprecation")
public static String getToken(String tenantId,String clientId,String encodedSecretKey) {
try {
String secretKey = EncryptionUtils.decryptAES(encodedSecretKey);
secretKey = URLEncoder.encode(secretKey);
String urltoConnect = loginUrlPrefix+tenantId+loginUrlSufix;
String payLoad = "resource=https%3A%2F%2Fmanagement.core.windows.net%2F&client_id="+clientId+"&grant_type=client_credentials&client_secret=" + secretKey;
URL url = new URL(urltoConnect);
URLConnection connection = null;
connection = url.openConnection();
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setDoOutput(true);
java.io.OutputStreamWriter wr = new java.io.OutputStreamWriter(connection.getOutputStream());
wr.write(payLoad);
wr.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String content;
String html = "";
while ((content = br.readLine()) != null) {
if (!content.equals("") && content.length() != 0)
html += content.trim();
}
return html;
} catch (Exception e) {
e.printStackTrace();
try {
throw e;
} catch (Exception e1) {
e1.printStackTrace();
}
}
return null;
}
#SuppressWarnings("deprecation")
public static Boolean testADConnection(String accessToken,String tenant) {
try {
URL url = new URL(String.format("https://graph.windows.net/%s/tenantDetails?api-version=2013-04-05", tenant,
accessToken));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Set the appropriate header fields in the request header.
conn.setRequestProperty("api-version", "2013-04-05");
conn.setRequestProperty("Authorization","Bearer "+ accessToken);
conn.setRequestProperty("Accept", "application/json;odata=minimalmetadata");
String goodRespStr = HttpClientHelper.getResponseStringFromConn(conn, true);
System.out.println(goodRespStr);
int responseCode = conn.getResponseCode();
if(responseCode == 200){
return true;
}
else{
System.out.println(goodRespStr);
}
} catch (Exception e) {
e.printStackTrace();
try {
throw e;
} catch (Exception e1) {
e1.printStackTrace();
}
}
return false;
}
public static void main(String[] args){
String tokenJSON = getToken(tenantId,clientId,secretKey);
if(tokenJSON != null){
JSONObject j = (JSONObject) JSONValue.parse(tokenJSON);
String token = (String) j.get("access_token");
testADConnection(token,tenantId);
}
}
This works fine with the first application I added. But when I add a second application with the same configuration and permissions this is not working.
I am getting a 403 error
"odata.error": {
"code": "Authentication_MissingOrMalformed",
"message": {
"lang": "en",
"value": "Access Token missing or malformed."
},
"date": "2016-12-02T07:27:59", }
Tenant Id i am passing same for both the applications (copied from show diagnostics in help menu) client id I am copying whatever is generated in Azure and labelled as Application Id.Secret Key I am generating in Azure portal with 1 year validity.

System.UnauthorizedAccessException was unhandled by user code, when deleting user alerts?

I am getting System.UnauthorizedAccessException was unhandled by user code when deleting user alerts by programming. It is working good in my QA farm. But not working in DEV farm.
I added application pool account to farm administation group and database users group as dbowner. Still getting same error.
protected void ChkBx41_CheckedChanged(object sender, EventArgs e)
{
SPUser user = SPContext.Current.Web.CurrentUser;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using(SPSite site=new SPSite(url.Text)){
using (SPWeb eweb = site.OpenWeb())
{
SPUser juser = null;
eweb.AllowUnsafeUpdates = true;
try
{
juser = eweb.AssociatedMemberGroup.Users[user.LoginName];
}
catch (Exception)
{
}
if (ChkBx41.Checked)
{
if (juser == null)
{
eweb.AssociatedMemberGroup.AddUser(eweb.EnsureUser(user.LoginName));
SPUtility.SendEmail(eweb, true, true, user.Email, "Welcome to " + eweb.Title, "Hello " + "<br><br>" + "Welcome to the " + eweb.Title + " ");
createalert(SPAlertFrequency.Daily, eweb, eweb.EnsureUser(user.LoginName),true);
}
RBList4.SelectedValue = "Daily";
RBList4.Enabled = true;
}
else
{
if (juser != null)
{
eweb.AssociatedMemberGroup.RemoveUser(juser);
removealert(eweb, juser);
RBList4.SelectedValue = null;
RBList4.Enabled = false;
}
}
eweb.AllowUnsafeUpdates = false;
}
}
});
}
public void removealert(SPWeb rweb, SPUser ruser)
{
bool oldCatchAccessDeniedException = rweb.Site.CatchAccessDeniedException;
try
{
SPUser cuser = rweb.EnsureUser(ruser.LoginName);
List<Guid> altid = new List<Guid>();
foreach (SPAlert alt in cuser.Alerts)
{
try
{
if (alt.AlertType == SPAlertType.List)
{
altid.Add(alt.ID);
}
}
catch (Exception) { }
}
rweb.Site.CatchAccessDeniedException = false;
foreach (Guid delid in altid)
{
cuser.Alerts.Delete(delid);
}
}
catch (UnauthorizedAccessException)
{
}
finally
{
rweb.Site.CatchAccessDeniedException = oldCatchAccessDeniedException;
}
}
Running from web part, try elevating?
public void removealert(SPWeb rweb, SPUser ruser) {
SPSecurity.RunWithElevatedPrivileges(delegate() {
using(SPSite csite = new SPSite(rweb.Site.Id)) {
using(SPWeb cweb = csite.OpenWeb(rweb.Id)) {
SPUser cuser = cweb.EnsureUser(ruser.LoginName);
List<Guid> altid = new List<Guid>();
foreach (SPAlert alt in cuser.Alerts) {
try {
if (alt.AlertType == SPAlertType.List) {
altid.Add(alt.ID);
}
} catch (Exception) {
}
}
foreach (Guid delid in altid) {
cuser.Alerts.Delete(delid);
}
}
}
});
}
I also would be interested to know where SPWeb rweb comes from. I hope not from SPContext, as you should not Dispose that.
I would recommend also having your SPWebs in a using block, in the same method block for easy reading.

Not able to get DirContext ctx using Spring Ldap

Hi i am using Spring ldap , after execution below program It display I am here only and after that nothing is happening, program is in continue execution mode.
public class SimpleLDAPClient {
public static void main(String[] args) {
Hashtable env = new Hashtable();
System.out.println("I am here");
String principal = "uid="+"a502455"+", ou=People, o=ao, dc=com";
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "MYURL");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, principal);
env.put(Context.SECURITY_CREDENTIALS,"PASSWORD");
DirContext ctx = null;
NamingEnumeration results = null;
try {
ctx = new InitialDirContext(env);
System.out.println(" Context" + ctx);
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
results = ctx.search("", "(objectclass=aoPerson)", controls);
while (results.hasMore()) {
SearchResult searchResult = (SearchResult) results.next();
Attributes attributes = searchResult.getAttributes();
Attribute attr = attributes.get("cn");
String cn = (String) attr.get();
System.out.println(" Person Common Name = " + cn);
}
} catch (NamingException e) {
throw new RuntimeException(e);
} finally {
if (results != null) {
try {
results.close();
} catch (Exception e) {
}
}
if (ctx != null) {
try {
ctx.close();
} catch (Exception e) {
}
}
}
}
}
Try fixing the below lines, i removed "ao" and it works fine.
results = ctx.search("", "(objectclass=Person)", controls);
You need to give search base as well
env.put(Context.PROVIDER_URL, "ldap://xx:389/DC=test,DC=enterprise,DC=xx,DC=com");
Refer this link as well http://www.adamretter.org.uk/blog/entries/LDAPTest.java

Resources