My IIS MVC web site connects to Microsoft CRM 2013. User/Domain/Password are set in web.config, this works fine.
Now I want to remove hard coded credentials in web.config. To Access CRM I want to use credentials of AppPool Identity. This user has enough rights on server and administrator role in MS CRM. I tried this way:
Uri organizationUri = new Uri(WebConfigurationManager.AppSettings["CrmUrl"]);
var credentials = new ClientCredentials();
credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
var orgProxy = new OrganizationServiceProxy(organizationUri, null, credentials, null);
This does not work. DefaultNetworkCredentials are empty.
I need help to manage this problem. Thanks!
Instead of creating the credentials and the organization service proxy yourself, rather let CrmConfiguration handle this:
Your Web.config will look something like this:
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="microsoft.xrm.client" type="Microsoft.Xrm.Client.Configuration.CrmSection, Microsoft.Xrm.Client"/>
</configSections>
<connectionStrings>
<!-- On-Premise with integrated Authentication -->
<add name="MyOnPremiseConnection" connectionString="Url=http://SERVER-NAME/ORG-NAME/XRMServices/2011/Organization.svc;" />
</connectionStrings>
<microsoft.xrm.client>
<contexts default="MyOnPremiseContext">
<!-- On Premise CRM-->
<add name="MyOnPremiseContext" connectionStringName="MyOnPremiseConnection" serviceName="MyService" />
</contexts>
<services default="MyService">
<add name="MyService" serviceCacheName="Xrm" />
</services>
<serviceCache default="Xrm">
<add name="Xrm" type="Microsoft.Xrm.Client.Services.OrganizationServiceCache, Microsoft.Xrm.Client" cacheMode="Disabled" />
</serviceCache>
</microsoft.xrm.client>
</configuration>
Your code will connect to CRM like this:
using (var servicecontext = CrmConfigurationManager.CreateContext("MyOnPremiseConnection", true) as CrmOrganizationServiceContext)
{
var query = new QueryExpression
{
EntityName = "account",
ColumnSet = new ColumnSet("name"),
TopCount = 10,
};
var top10accounts = servicecontext.RetrieveMultiple(query).Entities;
}
Reference: Simplified connection to Microsoft Dynamics CRM
Related
I'm trying to connect to AWS DynamoDb by creating an AmazonDynamoDBClient.
I'm getting the following exception:
Amazon.Runtime.AmazonClientException: No RegionEndpoint or ServiceURL configured
at Amazon.Runtime.ClientConfig.Validate()
at Amazon.Runtime.AmazonServiceClient..ctor(AWSCredentials credentials, ClientConfig config)
I have the following lines in my App.Config file (the actual keys are in my code):
<appSettings>
<add key="AWSProfileName" value="development" />
<add key="AWSAccessKey" value="XXXXXXXXXX" />
<add key="AWSSecretKey" value="YYYYYYYYYY" />
<add key="AWSRegion" value="us-east-2" />
</appSettings>
I also have a credentials file under the AWS folder. Includes the following:
[development]
aws_access_key_id = XXXXXXXX
aws_secret_access_key = YYYYYYYYYY
In my code, I'm simply calling to:
AmazonDynamoDBClient client = new AmazonDynamoDBClient();
I'm working in visual-studio 2019. This used to work when I was working in a simple console application environment. Now I am working under Azure-Functions template project.
Why am I getting error?
Not sure why it is not working since you have added AWSRegion to the config. I suggest to add the below to your credentials file
[development]
aws_access_key_id = XXXXXXXX
aws_secret_access_key = YYYYYYYYYY
region = us-east-2
I want to verify user payment whether its authentic or not. I am getting response from pay pal but i want to resend that response to pay pal to verify it. I am getting all the details regarding payments and user.
You can verify your by using pay pal api.
First install payPal from nuget packages
Install-Package PayPal
Secondly configure your webconfig like this.
<configSections>
<section name="paypal" type="PayPal.SDKConfigHandler, PayPal" />
</configSections>
<configuration>
<paypal>
<settings>
<add name="mode" value="sandbox"/>
<add name="clientId" value="client_id"/>
<add name="clientSecret" value="client_secret_id"/>
</settings>
</paypal>
</configuration>
Then from server side i mean C# end you can verify your payment like this.
var config = ConfigManager.Instance.GetProperties();
var accessToken = new OAuthTokenCredential(config).GetAccessToken();
var apiContext = new APIContext(accessToken);
// --verify payment ---
var payment = Payment.Get(apiContext, "PAY-YourCheckNo");
Here payment variable will populate with different status defending upon your pay-yourcheckNo. This is how you can verify your payment done through paypal.
I have been asked to create a remote selenium web driver using browserstack to test the functionality across all browsers. I have checked the repository to which I have received some of the felds needed:
RemoteUrl: http://hub.browserstack.com:80/wd/hub/
browserstack.user = username
browserstack.key = password
browserstack.debug = true/false
browserstack.tunnel = true/false
os
OS_version
Version = the browser version
I have got the code to create the driver below:
DesiredCapabilities capability = DesiredCapabilities.Firefox();
capability.SetCapability("browserstack.user", "username");
capability.SetCapability("browserstack.key", "password");
driver = new RemoteWebDriver(
new Uri("http://hub.browserstack.com/wd/hub/"), capability
);
this creates the remote webdriver. However as i am using this with specbind I need to create this driver within the app.config. which will be stored under a <browserfactory> however I am unsure on how to do this, please help!
I have now resolved this issue. From the start URL you need to then put in this browser factory setting:
<browserFactory
provider="SpecBind.Selenium.SeleniumBrowserFactory, SpecBind.Selenium">
<settings>
<add name="RemoteUrl" value="http://hub.browserstack.com:80/wd/hub/"/>
<add name="browser" value="IE" />
<add name="browser_version" value="8.0"/>
<add name="os" value ="Windows"/>
<add name="os_version" value="7" />
<add name="browserstack.user" value="username" />
<add name="browserstack.key" value="key" />
</settings>
The various settings configure this to Windows 7 and IE 8. This can be changed accordingly and the Username and Key is given to you by browser stack.
I have a project which uses ADFS authentication in some cases. The configuration is read from a database and the URLs are different from customer to customer, so there are many configuration options which I can't hard-code in my Web.config.
The problem is that I get the following error:
ID1032: At least one 'audienceUri' must be specified in the SamlSecurityTokenRequirement when the AudienceUriMode is set to 'Always' or 'BearerKeyOnly'
But I don't get it always, and I can't reproduce it. This is pretty annoying since I can't really debug it as long as I can't reproduce it. And I'm not sure whether I did everything correct. Maybe some ADFS expert can have a look at it.
(Trusts between my relying parties and their corresponding ADFS servers have been established, of course.)
Here is my code (only interesting parts of it), please ask if anything is missing or unclear.
Some snippets from my Web.config:
<system.webServer>
<modules>
<add name="WSFederationAuthenticationModule" type="Microsoft.IdentityModel.Web.WSFederationAuthenticationModule, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" preCondition="managedHandler" />
<add name="SessionAuthenticationModule" type="Microsoft.IdentityModel.Web.SessionAuthenticationModule, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" preCondition="managedHandler" />
<add name="ClaimsPrincipalHttpModule" type="Microsoft.IdentityModel.Web.ClaimsPrincipalHttpModule, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" preCondition="managedHandler" />
<!-- ... -->
</modules>
<!-- ... -->
</system.webServer>
<microsoft.identityModel>
<service>
<securityTokenHandlers>
<remove type="Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler" />
<add type="MyProject.MachineKeySessionSecurityTokenHandler" />
</securityTokenHandlers>
<federatedAuthentication>
<wsFederation passiveRedirectEnabled="false"
issuer="https://fail/IssuerEndpoint"
realm="https://fail/FederationResult"
homeRealm="https://fail"
requireHttps="true" />
</federatedAuthentication>
</service>
</microsoft.identityModel>
Those fail values will be overridden per request (see my Login() method below), but I have to specify something in my Web.config, so I chose to specify a valid URI at least. The default SessionSecurityTokenHandler had to be replaced because my service runs on multiple machines with DNS Round-Robin (sharing the same machine key).
Then I have a class I called AdfsTrustFilter which implements IAuthorizationFilter. I know it's bit of overhead, but due to the project structure, this filter is used as a global filter on every request (order is the least value in the whole project). In the OnAuthorization method, I complete the configuration as follows:
public sealed class AdfsTrustFilter : IAuthorizationFilter
public void OnAuthorization(AuthorizationContext filterContext)
// ...
var fam = FederatedAuthentication.WSFederationAuthenticationModule;
fam.ServiceConfiguration = new ServiceConfiguration
{
AudienceRestriction = new AudienceRestriction(AudienceUriMode.Always),
CertificateValidationMode = X509CertificateValidationMode.PeerOrChainTrust,
// MyIssuerNameRegistry checks whether a fingerprint is known and some other stuff
IssuerNameRegistry = new MyIssuerNameRegistry()
};
// config.OwnPath contains something like "https://my.app.com/AppRoot/"
fam.ServiceConfiguration.AudienceRestriction.AllowedAudienceUris.Add(new Uri(config.OwnPath));
}
}
This is the code that starts the authentication:
public ActionResult Login()
{
// ...
// again something like "https://my.app.com/AppRoot/"
string baseUrl = Config.OwnPath.TrimEnd('/') + "/";
// adfs endpoint for this customer: i.e. "https://identity.provider.net/adfs/ls/"
string endpoint = Config.AdfsConfig.IdentityProvider.Endpoint;
// the code behind FederationResult is shown below
var signIn = new SignInRequestMessage(new Uri(endpoint), baseUrl + "/Adfs/FederationResult")
{
Context = baseUrl
};
var url = signIn.WriteQueryString();
return Redirect(url);
}
And finally the FederationResult callback:
public ActionResult FederationResult()
{
WSFederationAuthenticationModule fam = FederatedAuthentication.WSFederationAuthenticationModule;
HttpRequest request = System.Web.HttpContext.Current.Request;
if (fam.CanReadSignInResponse(request, true))
{
var id = (IClaimsIdentity) User.Identity;
// do something
}
// ...
}
P.S.: The ADFS server was recently upgraded from 2008 R2 to 2012, but this didn't change anything. ADFS version was always 2.0.
Since the exception says that you need the audienceUri, I would start by adding one under
<microsoft.IdentityModel>
<service>
<audienceUris>
<add value="https://yourdomain/theaudienceuri" />
The audienceUri is the Uri adfs returns to your application. You can override the engine to accept arbitrary return results which doesn't change the fact that indeed you need at least one uri in the config.
I am using basic authentication for my web api and am getting the following error
*{"Message":"An error has occurred.","ExceptionMessage":"A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL *
It works absolutely fine when i remove the basic auth implementation from my APIs. So am guessing the problem should be something related to system.web.providers which am using for the basic auth implementation.
This is how my connection string looks like
<connectionStrings>
<add name="DefaultConnection" connectionString="Password=password;Persist Security Info=True;User ID=wbuser;Initial Catalog=WinBouts_com;Data Source=WINBOUTSAPIVM"
providerName="System.Data.SqlClient" />
<add name="WinBoutsConnectionString" connectionString="Password=password;Persist Security Info=True;User ID=wbuser;Initial Catalog=WinBouts_com;Data Source=WINBOUTSAPIVM"
providerName="System.Data.SqlClient" />
And i see an error in my web.config where a session provider is added. The error says "the connectionStringName attribute is not allowed". But if i remove it then it asks for the connectionStringName. This is the code for it.
<!--
If you are deploying to a cloud environment that has multiple web server instances,
you should change session state mode from "InProc" to "Custom". In addition,
change the connection string named "DefaultConnection" to connect to an instance
of SQL Server (including SQL Azure and SQL Compact) instead of to SQL Server Express.
-->
<sessionState mode="Custom" customProvider="DefaultSessionProvider">
<providers>
<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="WinBoutsConnectionString" />
</providers>
</sessionState>
Can anyone please tell me where i might be going wrong? Any suggestions or ideas would be deeply appreciated.
Finally Resolved the issue. The problem was in my Basic Authentication filter class.
private bool TryGetPrincipal(string username, string password, out IPrincipal principal)
{ string connectionString = ConfigurationManager.ConnectionStrings["WinBoutsConnectionString"].ConnectionString;
username = username.Trim();
password = password.Trim();
//only supporting SSO login atm
// var valid = Membership.Provider.ValidateUser(username, password);
serviceContext = new WinBoutsDataContext<DataAccess.Model.UserInfo>(connectionString);
userRepository = new UserRepository(serviceContext);
var valid = this.userRepository.ValidateAccount(username, password);
if (valid)
{
// once the user is verified, assign it to an IPrincipal with the identity name and applicable roles
principal = new GenericPrincipal(new GenericIdentity(username), System.Web.Security.Roles.GetRolesForUser(username));
return true;
}
//user wasn't found, unauthorised
principal = null;
return false;
}
I have hardcoded my DataContext here but earlier i didnt pass my connection string into it. I just went for the default constructor of the WinBoutsDataContext which didnt work when i put the code on to the server.
If you want to use a defined connectionString, you have to use the name of the connection string to fill the "sqlConnectionString" attribute and use SqlServer mode :
<configuration>
<connectionStrings>
<add name = "myString"
connectionString = "data source=local;user id=User;password=password" />
</connectionStrings>
<system.web>
<sessionState
mode="SQLServer"
sqlConnectionString="myString"
cookieless="false"
timeout="20"
/>
</system.web>
</configuration>