Project Server In premise 2016 CSOM code with Claim based Authentication - csom

One of our clients has enabled ADFS on his Project server 2016 In premise environment . We are using CSOM operation in our custom application and CSOM operations have failed due to this change.
For ADFS Claims based authentication we need to pass Authenticated cookie . Can someone help us with how to add authenticated Cookie with CSOM code.
Existing CSOM Code for getting list of projects:
public static void GetProjectListInpremise()
{
NetworkCredential net = null;
Console.WriteLine("Read Project Online Started ..");
string PWAOnlineUrl = ConfigurationManager.AppSettings ["pwaInpremiseUrl"];
string userName = ConfigurationManager.AppSettings["pwaInpremiseUser"];
string password = ConfigurationManager.AppSettings["pwaInpremiseUserPwd"];
string domain = ConfigurationManager.AppSettings["pwaInpremiseDomian"];
net = new NetworkCredential(userName, password, domain);
ProjectContext projContext = null;
projContext = new ProjectContext(PWAOnlineUrl);
// projContext.AuthenticationMode = ClientAuthenticationMode.FormsAuthentication;
projContext.Credentials = net;
projContext.Load(projContext.Projects);
projContext.ExecuteQuery();
Console.WriteLine("Read Project Execute Query Successful..");
foreach (PublishedProject pubProj in projContext.Projects)
{
Console.WriteLine("Project Name :" + pubProj.Name);
}
Console.ReadLine();
}

Related

Report Server authentication in .net core 2.1 linux container

I am migrating a .net core 2.1 app from windows server to linux container. It uses SQL Server 2008 report server.
The old app version is running on IIS (windows server), application pool with identity configured (active directory user).
The new app version is running on an alpine container using kestrel .net core server standalone, no identity configured.
When the app tries to reach SQL Server 2008 report server there is an error:
LoadReport error: One or more errors occured. (NTLM authentication is not possible with default credentials on this platform.)
How can I configure credentials (username and password)(same one set in my old application pool) in my new app based on linux container?
Part of my appsettings.json:
"Reporting": {
"ServerUrl": "http://myserver/ReportServer",
"ReportPath": "/Folder/Reports/"
},
Part of the source code:
private ServerReport PrepararRelatorio()
{
ReportSettings settings = new ReportSettings
{
ReportServer = this.configuration["Reporting:ServerUrl"]
};
ServerReport serverReport = new ServerReport(settings);
return serverReport;
}
protected FileContentResult CarregarRelatorio(
string nomeRelatorio,
string extensao,
Dictionary<string,string> parametros)
{
var renderType = this.ObterTipoRenderizacao(extensao);
if (ReportRenderType.Null.Equals(renderType))
{
throw new BusinessException("Erro ao definir o tipo do arquivo a ser exportado.");
}
ServerReport serverReport = this.PrepararRelatorio();
ReportRequest request = new ReportRequest
{
RenderType = renderType,
Path = this.configuration["Reporting:ReportPath"] + nomeRelatorio,
Name = nomeRelatorio,
ExecuteType = ReportExecuteType.Export,
Parameters = parametros
};
ReportResponse response = serverReport.Execute(request);
if (response.Status != 0)
{
throw new BusinessException(response.Message);
}
return File(response.Data.Stream, response.Data.MimeType, nomeRelatorio + "." + extensao);
}
Microsoft don't provide support for .NET Core/.NET 5, since the SSRS
library is intricately linked with WebForms, which are no longer
supported.
Refer this link
Usually, we use NetworkCredential option to pass username and password while in ASP.NET MVC.
You can able to supply report server's username and password to ReportSettings.Credential as shown in below.
Configuration:
"Reporting": {
"ServerUrl": "http://myserver/ReportServer",
"ReportPath": "/Folder/Reports/",
"UserName": "xxxxxx",
"Password": "yyyyyy"
},
Source Code:
private ServerReport PrepararRelatorio()
{
ReportSettings settings = new ReportSettings
{
ReportServer = this.configuration["Reporting:ServerUrl"],
Credential = NetworkCredential(this.configuration["Reporting:UserName"], this.configuration["Reporting:Password"])
};
ServerReport serverReport = new ServerReport(settings);
return serverReport;
}

Insufficient privileges to complete the operation Add new user using Azure Active Directory Graph Client API

I am Trying to Add new user in my AD but getting error as insufficient privileges to complete the operation not able to understand which permission is required to the Azure Active Directory Graph API which will not have this issue below is my code snippet which is making api call to AD Graph
using Microsoft.Azure.ActiveDirectory.GraphClient;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
namespace AuthenticationPortal
{
public class ActiveDirectoryClientModel
{
// These are the credentials the application will present during authentication
// and were retrieved from the Azure Management Portal.
// *** Don't even try to use these - they have been deleted.
static string clientID = ConfigurationManager.AppSettings["ida:ClientId"];
static string clientSecret = ConfigurationManager.AppSettings["ida:ClientSecret"];
static string tenantId = ConfigurationManager.AppSettings["ida:TenantId"];
static string domain = ConfigurationManager.AppSettings["ida:Domain"];
// The Azure AD Graph API is the "resource" we're going to request access to.
static string resAzureGraphAPI = "https://graph.windows.net";
// This is the URL the application will authenticate at.
static string authString = "https://login.microsoft.com/" + tenantId;
// The Azure AD Graph API for my directory is available at this URL.
static string serviceRootURL = "https://graph.windows.net/" + domain;
private ActiveDirectoryClient GetAADClient()
{
try
{
Uri serviceroot = new Uri(serviceRootURL);
ActiveDirectoryClient adClient = new ActiveDirectoryClient(serviceroot, async () => await GetAppTokenAsync());
return adClient;
}
catch (Exception ex)
{
return null;
}
}
private static async Task<string> GetAppTokenAsync()
{
try
{
// Instantiate an AuthenticationContext for my directory (see authString above).
AuthenticationContext authenticationContext = new AuthenticationContext(authString, false);
// Create a ClientCredential that will be used for authentication.
// This is where the Client ID and Key/Secret from the Azure Management Portal is used.
ClientCredential clientCred = new ClientCredential(clientID, clientSecret);
// Acquire an access token from Azure AD to access the Azure AD Graph (the resource)
// using the Client ID and Key/Secret as credentials.
AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(resAzureGraphAPI, clientCred);
// Return the access token.
return authenticationResult.AccessToken;
}
catch (Exception ex)
{
return null;
}
}
public async Task CreateUser()
{
var adClient = GetAADClient();
var newUser = new User()
{
// Required settings
DisplayName = "Atul Gandhale",
UserPrincipalName = "atulm#"+ domain,
PasswordProfile = new PasswordProfile()
{
Password = "Asdf1234!",
ForceChangePasswordNextLogin = true
},
MailNickname = "atulg",
AccountEnabled = true,
// Some (not all) optional settings
GivenName = "Atul",
Surname = "Gandhale",
JobTitle = "Programmer",
Department = "Development",
City = "Pune",
State = "MH",
Mobile = "1234567890",
};
try
{
// Add the user to the directory
adClient.Users.AddUserAsync(newUser).Wait();
}
catch (Exception ex)
{
}
}
}
}
Please help me out i have already send couple of hours but not able to get the solution for this.
You need following permission to create new user in azure portal from your application:
Permission Type : Delegated permissions
Permission Name : Directory.ReadWrite.All
You could see the official docs
Step: 1
Step: 2
Point To Remember:
Once you successfully added your permission afterwords you must have to add Grant consent as shown step 2.
PostMan Test:
Azure Portal:
Note: But my suggestion is to use Microsoft Graph API Which is mostly recommended now. For Microsoft Graph you could refer this docs

I want to use office 365 Api for my Asp.net with C# non mvc Project

Hello Folks I am new to using API into my project.
I am using Asp.Net with C# which does not have MVC architecture.
My client needed to integrate office 365 API into the project so that any user who want to access our service can login through their office 365 credentials.
while I searched on internet about the sources it said I needed ASP.net with MVC to use office 365 . Please suggest what could be done.
You could use Active Directory Authentication Library .NET to easily authenticate users to cloud or on-premises Active Directory (AD), and then obtain access tokens for securing API calls . In web form , code below is for your reference :
protected void Page_Load(object sender, EventArgs e)
{
string authCode = Request.Params["code"];
if (!string.IsNullOrEmpty(authCode))
{
Authorize(authCode);
}
string token = (string)Session["access_token"];
if (string.IsNullOrEmpty(token))
{
return;
}
try
{
// get user name
getUserName(token);
}
catch (AdalException ex)
{
}
}
public void getUserName(string token)
{
using (var client = new HttpClient())
{
//Enable signon and read users' profile
using (var request = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/beta/me"))
{
request.Headers.Add("Authorization", "Bearer " + token);
request.Headers.Add("Accept", "application/json;odata.metadata=minimal");
using (var response = client.SendAsync(request).Result)
{
if (response.StatusCode == HttpStatusCode.OK)
{
var json = JObject.Parse(response.Content.ReadAsStringAsync().Result);
Response.Write(json["displayName"].ToString());
}
}
}
}
}
public void Authorize(string authCode) {
AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/common");
// The same url we specified in the auth code request
string redirectUri = "http://localhost:55065/Default.aspx";
// Use client ID and secret to establish app identity
ClientCredential credential = new ClientCredential(ConfigurationManager.AppSettings["ClientID"], ConfigurationManager.AppSettings["ClientSecret"]);
try
{
// Get the token
var authResult = authContext.AcquireTokenByAuthorizationCode(
authCode, new Uri(redirectUri), credential, "https://graph.microsoft.com/");
// Save the token in the session
Session["access_token"] = authResult.AccessToken;
Response.Redirect(redirectUri.ToString());
}
catch (AdalException ex)
{
//return Content(string.Format("ERROR retrieving token: {0}", ex.Message));
}
}
public void signin()
{
var authContext = new AuthenticationContext("https://login.microsoftonline.com/common");
// The url in our app that Azure should redirect to after successful signin
string redirectUri = "http://localhost:55065/Default.aspx";
// Generate the parameterized URL for Azure signin
Uri authUri = authContext.GetAuthorizationRequestURL("https://graph.microsoft.com/", ConfigurationManager.AppSettings["ClientID"],
new Uri(redirectUri), UserIdentifier.AnyUser, null);
// Redirect the browser to the Azure signin page
Response.Redirect(authUri.ToString());
}
You could also refer to below link to get some examples with O365 API in GitHub :
https://github.com/dream-365/OfficeDev-Samples/tree/master/samples/Office365DevQuickStart
But I would suggest you could try to use ASP.NET MVC , it is designed with separation of concerns and testability in mind , and you will find a lot of MVC samples with O365 in here:
Office 365 API code samples and videos

Authentication Steps to BigQuery via Windows Service

I've created a project in Big Query and within API Access pane, I've created Service Account so that i can make Big Query API accessible through windows application on behalf of user interaction. Since i am new to using and accessing Google API, I want to know the basic steps so that i can access Big Query via Windows Service.
There are some .NET code samples here using web-based OAuth flows:
Google BigQuery with .NET documentation/ samples
For an example from another dev using service accounts in .NET, see this:
Google OAuth2 Service Account Access Token Request gives 'Invalid Request' Response
These manually implement service accounts on top of the .NET library. The .NET library has recently added native support for service accounts, though I haven't yet found an official example.
Here's an unofficial sample working with the Analytics API. It should be directly analogous to using service accounts with BigQuery:
How do I use a Service Account to Access the Google Analytics API V3 with .NET C#?
Finally here's the working code for Authentication process to Big Query API and retrieving records from Big Query table:-
I've created a class having a method of return type OAuth2Authenticator<AssertionFlowClient>.
internal class clsGetOAuth2Authentication
{
public OAuth2Authenticator<AssertionFlowClient> objGetOAuth2(string strPrivateFilePath, string strPrivateFilePassword, string strServiceAccEmailId,string strScope)
{
AuthorizationServerDescription objAuthServerDesc;
X509Certificate2 objKey;
AssertionFlowClient objClient;
OAuth2Authenticator<AssertionFlowClient> objAuth = null;
string ScopeUrl = "https://www.googleapis.com/auth/" + strScope;
string strSrvAccEmailId = strServiceAccEmailId;
string strKeyFile = strPrivateFilePath; //KeyFile: This is the physical path to the key file you downloaded when you created your Service Account.
string strKeyPassword = (strPrivateFilePassword != "") ? strPrivateFilePassword : "notasecret"; //key_pass: This is probably the password for all key files, but if you're given a different one, use that.
objAuthServerDesc = GoogleAuthenticationServer.Description; //objAuthServerDesc: Description of the server that will grant Authentiation.
objKey = new X509Certificate2(strKeyFile, strKeyPassword, X509KeyStorageFlags.Exportable); //objkey: Load up and decrypt the key.
objClient = new AssertionFlowClient(objAuthServerDesc, objKey) { ServiceAccountId = strSrvAccEmailId, Scope = ScopeUrl }; //objClient: Using the AssertionFlowClient, because we're logging in with our certificate.
objAuth = new OAuth2Authenticator<AssertionFlowClient>(objClient, AssertionFlowClient.GetState); //objAuth: Requesting Authentication.
return objAuth;
}
}
Now, another class calls the above method:-
clsGetOAuth2Authentication objOAuth2 = new clsGetOAuth2Authentication();
try
{
var objAuth = objOAuth2.objGetOAuth2(strKeyFile, strKeyPassword, strSrvAccEmailId, strScope); //Authentication data returned
objBQServ = new BigqueryService(objAuth); //Instantiate BigQueryService with credentials(objAuth) as its parameter
#region Retrieving Records:-
JobsResource j = objBQServ.Jobs;
QueryRequest qr = new QueryRequest();
qr.Query = strQuery;
DateTime dtmBegin = DateTime.UtcNow;
QueryResponse response = j.Query(qr, strProjId).Fetch();
DateTime dtmEnd = DateTime.UtcNow;
string strColHead = "";
foreach (var colHeaders in response.Schema.Fields)
{
strColHead += colHeaders.Name.ToString() + "\t";
}
Console.WriteLine(strColHead);
int intCount = 0;
foreach (TableRow row in response.Rows)
{
intCount += 1;
List<string> list = new List<string>();
foreach (var field in row.F)
{
list.Add(field.V);
}
Console.WriteLine(String.Join("\t", list));
}
TimeSpan tsElapsed = dtmEnd - dtmBegin;
Console.WriteLine("\n" + "Total no. of records:- " + intCount + ". Time taken:- " + tsElapsed);
#endregion
}
catch (Exception ex)
{
Console.WriteLine("Error Occured!" + "\n\n" + "Statement:- " + ex.Message.ToString() + "\n\n" + "Description:- " + ex.ToString() + "\n\n");
Console.WriteLine("\nPress enter to exit");
Console.ReadLine();
}

WSDL 1.1 Basic question on endpoint salesforce Apex code

From my WSDL I have the following service part:
<service name="BAPI_CUSTOMER_DISPLAYService">
<documentation>SAP Service BAPI_CUSTOMER_DISPLAY via SOAP</documentation>
<port name="BAPI_CUSTOMER_DISPLAYPortType" binding="s0:BAPI_CUSTOMER_DISPLAYBinding">
<soap:address location="http://2.3.4.100:8000/sap/bc/soap/rfc"/>
</port>
</service>
then what will be endpoint reference for this?
I am giving it as "http://2.3.4.100:8000/sap/bc/soap/rfc" in my salesforce client and it gives the following error.
"This service requires client certificate for authentication procedure."
I am sure that i need to give user name and password not knowing how i can set them in my client which is a Apex code.
Help is appreciated.
I imported the Enterprise WSDL and used the uri from the loginResult. Here's some code from my project:
LoginResult loginResult = null; // Login Result (save and make static)
SessionHeader sessionHeader = null; // Session Header (save and make static)
SoapClient soapClient = null; // This is the Enterprise WSDL
SecureStatusClient SecureStatusClient = null; // This is my custom #WebService
// Create Login Request
LoginScopeHeader loginScopeHeader = new LoginScopeHeader
{
organizationId = configuration["OrganizationId"],
portalId = configuration["PortalId"]
};
// Call Login Service
string userName = configuration["UserName"];
string password = configuration["Password"];
string securityToken = configuration["SecurityToken"];
using (SoapClient loginClient = new SoapClient())
{
loginResult = loginClient.login(loginScopeHeader, userName, password + securityToken);
if (result.passwordExpired)
{
string message = string.Format("Salesforce.com password expired for user {0}", userName);
throw new Exception(message);
}
}
// Create the SessionHeader
sessionHeader = new SessionHeader { sessionId = loginResult.sessionId };
// Create the SoapClient to use for queries/updates
soapClient = new SoapClient();
soapClient.Endpoint.Address = new EndpointAddress(loginResult.serverUrl);
// Create the SecureStatusServiceClient
secureStatusClient = new SecureStatusServiceClient();
Uri apexUri = new Uri(SoapClient.Endpoint.Address.Uri, "/services/Soap/class/SecureStatusService");
secureStatusClient.Endpoint.Address = new EndpointAddress(apexUri);

Resources