Crm 2011. How get Current user in mvc application - dynamics-crm-2011

I have a custom mvc application, what i want to use as a part of crm 2011
(for example i have a button at crm panel, which call action at my mvc application)
Can I get user credentials, which log in in crm and press button?
I use this code to run organization service. But WhoAmIRequest return system or null (depend of impersonate property in web.config)
var organizationUri = new Uri(Configuration.OrganizationUri());
var credentials = new ClientCredentials();
credentials.Windows.ClientCredential = (DefaultCredentials != null) ? DefaultCredentials : CredentialCache.DefaultNetworkCredentials;
IServiceConfiguration<IOrganizationService> orgConfigInfo = ServiceConfigurationFactory.CreateConfiguration<IOrganizationService>(organizationUri);
var service = new OrganizationServiceProxy(orgConfigInfo, credentials);
WhoAmIResponse response = (WhoAmIResponse)service.Execute(new WhoAmIRequest());
service.CallerId = response.UserId;

You could read the current Username
User.Identity.Name
and compare it with the domainname in MS CRM.

Related

ASP.NET Identity using Azure Active Directory... when/how are AspNetUsers db records created

I have a simple MVC .Core 6 web application that will be used on the corporate extranet (via an azure app service).
I've setup Microsoft Identity for login/authentication. This works really well. User requests a page and they're sent off to the corporate azure active directory login page (include 2fa) and returned to the application authenticated with user claims.
BUT... my Identity database tables remain empty (AspNetUsers et al). I was half expecting a record to be created representing the user that just signed in.
I scaffolded the ExternalLogin.cshtml page expecting it to be displayed after a user logs in (and there I could manually create the user if userManager.GetUserAsync(User) == null). But the page is never shown
I think I want AspNetUsers table entries because my simple app does a bit of audit trail stuff (CreatedByUserId, LastUpdatedByUserId) and I would like these to be foreign keys to the AspNetUsers table.
Thoughts? Are my expectations out of whack?
I was way off base on this.
Microsoft.Identity.Web and Microsoft.Identity.Web.UI don't need/create AspNetUsers table (et al).
If you want to build your own users table when a user logs in to the application you can do the following:
builder.Services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, opts =>
{
opts.Events = new OpenIdConnectEvents()
{
OnTicketReceived = async (context) =>
{
//
// Pull out the user details
//
var objectidentifier = context.Principal.FindFirstValue("http://schemas.microsoft.com/identity/claims/objectidentifier");
var nameidentifier = context.Principal.FindFirstValue(ClaimTypes.NameIdentifier);
var name = context.Principal.FindFirstValue("name");
var email = context.Principal.FindFirstValue("preferred_username");
//
// Demo code to create a record in a users db table
//
using var scope = context.HttpContext.RequestServices.CreateScope();
var ctx = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var isUserExists = await ctx.MyApplicationUser.AnyAsync(u => u.ObjectIdentifier == objectidentifier);
if (!isUserExists)
{
var applicationUser = new MyApplicationUser()
{
ObjectIdentifier = objectidentifier,
NameIdentifier = nameidentifier,
Email = email,
Name = name,
};
ctx.MyApplicationUser.Add(applicationUser);
await ctx.SaveChangesAsync();
};
}
};
});
Note that some care is needed to pull out the correct claims.
Note this should probably update an existing user if their details changed (names do change).
This is slightly modified from what I found at: https://dotnetthoughts.net/azure-active-directory-b2c-in-aspnet-core-mvc-part1/

dotnet Core - Using azure AD authentication to retrive data from sharepoint REST API

My project is set up to use azure ad as login(from the dotnet core template). I have successfully managed to log in.
However, i want to use the same logged in user to retrive data from sharepoint rest api.
I have the following method:
public async Task<FileResults> Test()
{
var siteUrl = "https://xxxxx.sharepoint.com";
var username = "xx#xx.no";
var password = "xxxxxx";
var securePassword = new SecureString();
password.ToCharArray().ToList().ForEach(c => securePassword.AppendChar(c));
var credentials = new SharePointOnlineCredentials(username, securePassword);
var handler = new HttpClientHandler();
handler.Credentials = credentials;
var uri = new Uri(siteUrl);
handler.CookieContainer.SetCookies(uri, credentials.GetAuthenticationCookie(uri));
var json = string.Empty;
using (var client = new HttpClient(handler))
{
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
var response = await client.GetAsync(siteUrl + "/_api/Web/GetFolderByServerRelativeUrl('/Delte%20dokumenter/Test')/Files");
json = await response.Content.ReadAsStringAsync();
var result = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(json);
var files = result.FileResults;
return files;
}
}
This is working fine and im getting documents from sharepoint.
But, this is when using hardcoded credentials. How do i use the credentials of the logged in user via azure AD? Do i retrive the accesstoken?
To use the Azure AD Authentication you need to have one of the Authentication flows.
Note: Username/Password flow is not recommended.
After that you will be getting the tokens according to the scopes that are specified and you need to hit the Microsoft Graph Api, internally you need to hit the SharePoint API endpoints according to your requirement.
You can start exploring with this sample

Crm 2011 test the crm4 metadata endpoint

I'm having trouble with a third party product that suppose to connect to a CRM2011 CRM4 metadata endpoint. Basically the product is AVAYA EMC version 6.3.1, I'm aware that this specific version is not compatible with CRM2011, but the documents released by the company are not really clear if this involved the CRM2011 CRM4 metadata endpoint.
Long story short, there is this plugin ASMSCRMGuiPlugin.dll that is not able to authenticate the metadata endpoint provided as:
(this should be the metadata attribute endpoint for crm4)
http://server/MSCRMServices/2007/MetadataService.asmx
to confirm that the endpoint was working i wrote a console that was querying the metadata endpoint on that address with the provided credentials (the ones that in the plugin were not working), and i was able to retrieve all the contacts attributes.
Now I'm not a crm4 developer and I entered the CRM world when 2011 was already established, is there any setting on CRM2011 side that I have to tweak to allow this component to work?
I will append the code i used to connect to the metadata endpoint. Is there any other way for me to prove that is not a crm configuration issue? Anyone out there ever managed to configure AVAYA EMC6.3.1 with CRM 2011, using the endpoint crm4?
CrmAuthenticationToken token = new CrmAuthenticationToken();
token.OrganizationName = "Org";
token.AuthenticationType = 0;
MetadataService mdSevice = new MetadataService();
mdSevice.Credentials = new System.Net.NetworkCredential("User", "Passw", "domain");
mdSevice.Url = "http://org/MSCRMServices/2007/MetadataService.asmx";
mdSevice.UseDefaultCredentials = false;
mdSevice.CrmAuthenticationTokenValue = token;
RetrieveEntityRequest entityRequest = new RetrieveEntityRequest();
entityRequest.RetrieveAsIfPublished = false;
entityRequest.LogicalName = EntityName.contact.ToString();
entityRequest.EntityItems = EntityItems.IncludeAttributes;
RetrieveEntityResponse entityResponse = (RetrieveEntityResponse)mdSevice.Execute(entityRequest);
Console.WriteLine("Retrieved fields: ");
EntityMetadata retrievedEntityMetadata = entityResponse.EntityMetadata;
foreach (AttributeMetadata att in retrievedEntityMetadata.Attributes)
{
{
Console.WriteLine(att.LogicalName);
}
}

How to Authenticate and Authorize Asp.Net Web application through QuickBooks?

how to Authenticate and Authorize Asp.Net Web application through QuickBooks.
I want to integrate QuickBooks Accounts System in ASP.NET web Application I have successfully make developer account on quickbooks and make an app and got consumer key, consumer Secret and App Token and all URL's
Know I need some asp.net web api code snipped to successfully authenticate and authorize my web user's and than show there accounting detail
Please help me i Google alot but have no success.
I'm Strange this form is 0% active related to quickbooks API's or etc, after alot of struggling i found an answer of above mention question,
Download Quickbooks IPP.NET SDK it will provide you different classes for CURD.
var appToken = "";
var consumerKey = "";
var consumerSecret = "";
// the above 3 fields you can get when create your app on quickbook go to My app----> select youre app--->goto KEYS
var accessToken = "";
var accessTokenSecret = "";
// this two tookens you will get from URL on the same above page
var realmId = "1400728630"; //1400728630
// this is youre company ID which can be used when you create youre //company on freshbook
var serviceType = IntuitServicesType.QBO;
var validator = new OAuthRequestValidator(accessToken, accessTokenSecret, consumerKey, consumerSecret);
var context = new ServiceContext(appToken,realmId, serviceType, validator);
var service = new DataService(context);
try
{
Customer customer = new Customer();
//Mandatory Fields
customer.GivenName = "Mary";
customer.Title = "Ms.";
customer.MiddleName = "Jayne";
customer.FamilyName = "Cooper";
service.AddAsync(customer);
//service.Add(entity);
}catch(Exception ex)
{
System.Console.WriteLine(ex);
}

SharePoint 2010 Client Object Model: How to retrieve subwebs for a specified user?

I have a need to retrieve a list of subwebs for a specified user using the client object model. The challenge is that this is being called from a C# web service that is running under the identity of a SharePoint user with access to all the subwebs. Is there a way to filter this list to only return those that belong to a specified user? I only have the username and do not have the password for this account so direct impersonation using NetworkCredential is not going to work.
Pseudo code below:
var clientContext = new ClientContext(siteUrl);
var site = clientContext.Web;
var user = site.CurrentUser;
clientContext.Load(site);
clientContext.Load(user);
clientContext.ExecuteQuery();
var webCollection = site.GetSubwebsForCurrentUser(null);
clientContext.Load(webCollection);
clientContext.ExecuteQuery();
foreach (var web in webCollection)
{
// should I check permissions here?
}

Resources