Azure Graph API Authentication_MissingOrMalformed - azure

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.

Related

IPublicClientApplication GetAccountsAsync returns nothing in Windows Forms App

I am trying to make the sample application available at https://cmatskas.com/modern-authentication-with-azure-ad-for-winforms-native-apps-2/ work.
I registered application in Azure and got Client ID and Tenant ID. Both IDs are GUID-like numbers. These codes were substituted to the program.
I also added a multiline textbox txtLog to the Form1 to show progress messages.
The following procedure does not return accounts:
private async Task<AuthenticationResult> Login()
{
AuthenticationResult authResult = null;
var accounts = await Program.PublicClientApp.GetAccountsAsync();
txtLog.Text += "accounts count " + accounts.ToArray().Count().ToString() + "\r\n";
if (accounts != null)
{ label2.Text += $"GetAccountsAsync passed!"; }
else
{ label2.Text += "PublicClientApp.GetAccountsAsync returned an empty list"; }
var firstAccount = accounts.FirstOrDefault();
if (firstAccount != null)
{ label2.Text += firstAccount.Username; }
else
{ label2.Text += "firstAccount is null"; }
try
{
authResult = await Program.PublicClientApp.AcquireTokenSilent(scopes, firstAccount)
.ExecuteAsync();
label2.Text = "Auth result passed!";
}
catch (MsalUiRequiredException ex)
{
// A MsalUiRequiredException happened on AcquireTokenSilent.
// This indicates you need to call AcquireTokenInteractive to acquire a token
System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");
label2.Text += $"Auth result error: {ex.Message}";
try
{
authResult = await Program.PublicClientApp.AcquireTokenInteractive(scopes)
.WithAccount(accounts.FirstOrDefault())
.WithPrompt(Prompt.SelectAccount)
.ExecuteAsync();
txtLog.Text += "authResult AccessToken: " + authResult.AccessToken + "\r\n";
label2.Text += "AcquireTokenInteractive passed";
}
catch (MsalException msalex)
{
label1.Text = $"Error Acquiring Token:{System.Environment.NewLine}{msalex}";
}
}
catch (Exception ex)
{
label1.Text = $"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}";
}
return authResult;
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Identity.Client;
namespace Modern2
{
static class Program
{
public static string ClientId = "1189b025-e4c7-4265-b3fb-a03e15582165";
public static string Tenant = "223591c8-866c-485c-b6db-35e7d2527da7";
//public static string ClientId = Environment.GetEnvironmentVariable("ClientId", EnvironmentVariableTarget.User);
//public static string Tenant = Environment.GetEnvironmentVariable("Tenant", EnvironmentVariableTarget.User);
private static IPublicClientApplication clientApp;
public static Form1 goFrmMain;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
goFrmMain = new Form1();
goFrmMain.txtLog.Text = "";
InitializeAuth();
Application.Run(goFrmMain);
}
public static IPublicClientApplication PublicClientApp { get { return clientApp; } }
private static void InitializeAuth()
{
clientApp = PublicClientApplicationBuilder.Create(ClientId)
.WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient")
.WithAuthority(AzureCloudInstance.AzurePublic, Tenant)
.Build();
goFrmMain.txtLog.Text += "clientApp.Authority: " + clientApp.Authority + "\r\n";
TokenCacheHelper.EnableSerialization(clientApp.UserTokenCache);
goFrmMain.txtLog.Text += "TokenCacheHelper.CacheFilePath: " + TokenCacheHelper.CacheFilePath + "\r\n";
}
}
}
The company directory in Azure was Unmanaged.
Once the steps of "Take over an unmanaged directory as administrator in Azure Active Directory" at https://learn.microsoft.com/en-us/azure/active-directory/enterprise-users/domains-admin-takeover were implemented, the function started returning the accounts.

Microsoft.SharePoint.Client.ServerUnauthorizedAccessException: Access denied

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();
}
}

MDM (Mobile Device management) in J2ME

I want to implement MDM in J2ME. Whenever I update App, I am able to upload New App in Mobile, I can upload it successfully. But My Problem is that, I want to replace existing App and then want to upload new App. As of now I can add App on Device with Different name (Same App Name is not working) but cant replace App.
Here is my code for MDM:
public void getUpdateApp() {
new Thread(new Runnable() {
public void run() {
try {
DataHelper dh = new DataHelper(parent);
dh.openRecord();
String response_rms = dh.getupdateAppinfo_str();
System.out.println("response from RMS of Update App info in appupdate---" + response_rms);
System.out.println("Sending update App Call.");
HttpConn httpConnect = new HttpConn(parent);
UserInfo userInfo = getUserInfo();
String data = "AppCode=" + AppData.appCode+ "&CurrentVersion=" + AppData.currentversion
+ "&TerminalNumber=" + userInfo.getTerminalNumber()
+ "&apifunction=" + "GetAppUpdate";
httpConnect.sendPostRequest_appupdate(AppData.AppUpdateURL, data, new ConnectionListener() {
public void onRequestFailure(Object title, Object message) {
System.out.println("==>GetUpdateApp Failure\nTitle:"
+ (String) title
+ "\n Failure Message" + (String) message);
showMessageDialog((String) title, (String) message, new SettingsForm("Settings", parent), 2000);
}
public void onRequestSuccess(Object httpResponse) {
try {
System.out.println("==>On Success--of Update App");
String response = (String) httpResponse;
System.out.println("==>Login Form--Update App \nResponse:" + response);
JSONObject jsonObject = new JSONObject(response);
int responseCode = Integer.parseInt(jsonObject.getString("ResponseCode"));
switch (responseCode) {
case 000: {
String latestbuild = jsonObject.getString("LatestBuild");
String latestversion = jsonObject.getString("LatestVersion");
String downloadURL = jsonObject.getString("DownloadURL");
if (latestversion != null) {
if (!latestversion.equals(AppData.currentversion) || !latestbuild.equals(AppData.currentBuild)) {
if (Integer.parseInt(latestbuild) > Integer.parseInt(AppData.currentBuild)) {
System.out.println("Download URL--" + downloadURL);
// parent.platformRequest(downloadURL);
System.out.println("platform request boolean variable returns---"+ parent.platformRequest(downloadURL));
parent.platformRequest(downloadURL);
parent.destroyApp(true);
} else {
System.out.println("Incomapatible types");
showMessageDialog("Alert", "No new updates available", new SettingsForm("Settings", parent),2000);
}
} else {
System.out.println("App Version Number is same,No New Build Available");
showMessageDialog("Alert", "Application is already upto date", new SettingsForm("Settings", parent),2000);
}
} else {
System.out.println("App version not available on server");
showMessageDialog("Alert", "No new updates available", new SettingsForm("Settings", parent),2000);
}
break;
}
}
} catch (JSONException ex) {
ex.printStackTrace();
showdisplayExceptionDialog(ex, new SettingsForm("Settings", parent));
} catch (ConnectionNotFoundException ex) {
showdisplayExceptionDialog(ex, new SettingsForm("Settings", parent));
}
}
});
} catch (Exception e) {
showdisplayExceptionDialog(e, new SettingsForm("Settings", parent));
}
}
}).start();
}
If any 1 has any idea regarding Replacing App in J2ME then please Help me. Thanks a lot in Advance.

Google Docs API - Impersonate User File Download

Using the Google Docs Java API with a Google Apps account, is it possible to impersonate a user and download a file?
When I run the program below, it is clearly logging on to the domain and impersonating the user because it retrieves the details of one of the files and prints out the file title. However, when it tries to download the file, a ServiceForbiddenException is thrown.
If it is not possible with the Java API, does anyone know if it is possible for my program to write an HTTP request to download the file using the Protocol API?
public class AuthExample {
private static DocsService docService = new DocsService("Auth Example");
public static void main(String[] args)
throws Exception
{
String adminUser = args[0];
String adminPassword = args[1];
String authToken = args[2];
String impersonatedUser = args[3];
loginToDomain(adminUser, adminPassword, authToken);
URL url = new URL( "https://docs.google.com/feeds/" + impersonatedUser + "/private/full" );
DocumentListFeed feed = docService.getFeed(url, DocumentListFeed.class);
DocumentListEntry entry = feed.getEntries().get(0);
String title = entry.getTitle().getPlainText();
System.out.println( title );
String type = entry.getType();
if ( type.equals("document") )
{
String encodedAdminUser = URLEncoder.encode(adminUser);
String resourceId = entry.getResourceId();
String resourceIdNoPrefix = resourceId.substring( resourceId.indexOf(':')+1 );
String downloadUrl =
"https://docs.google.com/feeds/download/documents/Export" +
"?xoauth_requestor=" + encodedAdminUser +
"&docId=" + resourceIdNoPrefix +
"&exportFormat=doc";
downloadFile( downloadUrl, title + ".doc" );
}
}
private static void loginToDomain(String adminUser, String adminPassword, String authToken)
throws OAuthException, AuthenticationException
{
String domain = adminUser.substring( adminUser.indexOf('#')+1 );
GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey(domain);
oauthParameters.setOAuthConsumerSecret(authToken);
oauthParameters.setOAuthType(OAuthType.TWO_LEGGED_OAUTH);
oauthParameters.setScope("https://docs.google.com/feeds/ http://spreadsheets.google.com/feeds/ http://docs.googleusercontent.com/");
docService.useSsl();
docService.setOAuthCredentials(oauthParameters, new OAuthHmacSha1Signer());
docService.setUserCredentials(adminUser, adminPassword);
}
// Method pasted directly from Google documentation
public static void downloadFile(String exportUrl, String filepath)
throws IOException, MalformedURLException, ServiceException
{
System.out.println("Exporting document from: " + exportUrl);
MediaContent mc = new MediaContent();
mc.setUri(exportUrl);
MediaSource ms = docService.getMedia(mc);
InputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = ms.getInputStream();
outStream = new FileOutputStream(filepath);
int c;
while ((c = inStream.read()) != -1) {
outStream.write(c);
}
} finally {
if (inStream != null) {
inStream.close();
}
if (outStream != null) {
outStream.flush();
outStream.close();
}
}
}
}
Impersonation will work as intended if you use Oauth2 with ServiceAccounts

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