Authenticate to Dynamics 365 On premise - odata

I am trying connect to Dynamics 365 On-premise with the OData client for .net
I tried to authenticate through basic authentication, however this is not working.
var c = new Microsoft.Dynamics.CRM.System(new Uri("https://mycrm01/crm/api/data/v8.2/"));
c.SendingRequest2 += (o, requestEventArgs) => {
var creds = username + ":" + password;
var encodedCreds = Convert.ToBase64String(Encoding.ASCII.GetBytes(creds));
requestEventArgs.RequestMessage.SetHeader("Authentication", "Basic" + encodedCreds);
};
var contacts = c.Contacts.Where(x => x.Firstname=="testuser");
foreach (var contact in contacts)
{
}
The error I recieve is: HTTP Error 401 - Unauthorized: Access is denied
Can someone help me how this is done?

In general I only use the OData client from JavaScript. When using .NET, I use the SDK libraries that provide authentication and access via the CrmServiceClient class.
To use the OData client from C#, this article outlines the various authentication methods: https://msdn.microsoft.com/en-us/library/mt595798.aspx
Web API authentication patterns
There are three different ways to manage authentication when using the
Web API. With JavaScript in web resources
When you use the Web API with JavaScript within HTML web resources,
form scripts, or ribbon commands you don’t need to include any code
for authentication. In each of these cases the user is already
authenticated by the application and authentication is managed by the
application. With on-premises deployments
When you use the Web API for on-premises deployments you must include
the user’s network credentials. The following example is a C# function
that will return an HttpClient configured for a given user’s network
credentials: C#
private HttpClient getNewHttpClient(string userName,string
password,string domainName, string webAPIBaseAddress) {
HttpClient client = new HttpClient(new HttpClientHandler() { Credentials = new NetworkCredential(userName, password, domainName)
});
client.BaseAddress = new Uri(webAPIBaseAddress);
client.Timeout = new TimeSpan(0, 2, 0);
return client;
}
With Microsoft Dynamics 365 (online) or internet facing deployments
When you use the Web API for Dynamics 365 (online) or an on-premises
Internet-facing deployment (IFD) you must use OAuth as described in
Connect to Microsoft Dynamics 365 web services using OAuth.
If you’re creating a single page application (SPA) using JavaScript
you can use the adal.js library as described in Use OAuth with
Cross-Origin Resource Sharing to connect a Single Page Application to
Microsoft Dynamics 365.

Related

Service account authentication with Microsoft Graph API?

I'm building a server on top of MS Graph API and all I need to do is upload and download images to OneDrive. End users of the application will not access OneDrive directly nor will they all even have accounts. The files need only be accessible to the application itself and a handful of power users who do have their own credentials.
I would like to be able to just configure the credentials for a service account to be the only one accessing the bucket, but it seems all the auth flows require an end user to login. Is there an API-centric way to do this transparently? Or should I infer from the lack of explicit support that this isn't a valid use case for OneDrive and I should look at Azure Blob Storage?
You can authenticate to MS Graph API with username + password using the class UserPasswordCredential (https://learn.microsoft.com/en-us/dotnet/api/microsoft.identitymodel.clients.activedirectory.userpasswordcredential?view=azure-dotnet). Sample:
UserCredential creds = new UserPasswordCredential("fred#contoso.onmicrosoft.com","password");
var bearerToken = AcquireToken("https://graph.microsoft.com", "d1ddf0e4-d672-4dae-b554-9d5bdfd93547", creds).Result;
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + result.AccessToken);
var graphInfo = client.GetAsync("https://graph.microsoft.com/v1.0/me/").Result;
Warning: There are only few use cases where using username + password directly is legitimate (see http://www.cloudidentity.com/blog/2014/07/08/using-adal-net-to-authenticate-users-via-usernamepassword/). Additionally, UserPasswordCredential is not available in DotNetCore.

BOT framework External client authentication

I launch the client web application from the BOT framework to process the thrid party authentication. The client application process the the third party authentication using OAuth and Owin. Is there any way to send the useridentity back to the BOT framework?
and able to get the access token from the client browser. But the same api call is not working from the BOT framework or from other client. (Ex: Httpget (clientappurl/api/GetToken)
Any ideas?
//api/GetToken ---GET
public string GetToken()
{
var identity = new ClaimsIdentity (User.Identity.AuthenticateType)
identity.AddClaim ("sub", User.Identity.GetUserName()))
AuthenticationTicket ticket = new AuthenticationTicket (identity,
AuthenticationProperties());
string token = Startup. OAuthOptions.AccessTokenFormat.Protect(ticket);
return token;
}
I think what you are looking for is called the backchannel. There is an example in this link that may be all you need. There is also another example here https://github.com/Microsoft/BotFramework-WebChat/blob/master/samples/backchannel/index.html. The backchannel will allow you to communicate between the client and the bot.

ASPNet Identity Authentication MVC5 Client web site->Auth Server-> Web API server

I'm a newbie for ASPnet identity services and we require a following requirement.
Following is the architecture setup
1. Appserver
Appsever having
a. Entity Framework
b. ASP.Net Web API2 Odata services
c. Authorization server
2. Webserver
ASP.Net MVC 5 application (Client which access the App server)
The flow needs to be
MVC5 Cleint application having a login / Register form
While register / login the information needs to send to the authorization server int he app server, Authorize and creating the claims using Identity Services.
Once the Identity has been created in the Authorization server, the client application should logged in
I'm aware of getting bearer token from authentication server and that will be used as header information to access the API service
All we are lacking is the MVC client application should use the same identity claims that have created in the Authorization server.
Is there any way to access the claims which are created in the auth server.
I have got some samples about how to authenticate in the auth server and receiving token though OWIN and from this token we can access the API securely but I need of the client web application needs to sign in based on the token
I have gone through the following links
http://blogs.msdn.com/b/webdev/archive/2013/09/20/understanding-security-features-in-spa-template.aspx
Also, I require to add claims when ever it requires after login as well
I have resolve this issue as follows, but I'm not sure this is the effective method
Once log-in and retrieve the bearer token (this token should assigned with claims identity already such as username, role .. etc)
In the web api AccountController, need to create a method to retrieve the default claims which requires for client web application. Please check the follows
[Authorize]
[HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
[Route("UserInfo")]
public UserInfoViewModel GetUserInfo()
{
var firstname = ((ClaimsIdentity)User.Identity).Claims.Where(c => c.Type.Equals("FirstName")).SingleOrDefault();
var lastname = ((ClaimsIdentity)User.Identity).Claims.Where(c => c.Type.Equals("LastName")).SingleOrDefault();
var IsApproved = ((ClaimsIdentity)User.Identity).Claims.Where(c => c.Type.Equals("IsApproved")).SingleOrDefault();
var userinfo = new UserInfoViewModel
{
UserName = User.Identity.GetUserName(),
FirstName = firstname.Value.ToString(),
LastName = lastname.Value.ToString(),
UserApproved = Convert.ToBoolean(IsApproved.Value.ToString()),
HasRegistered = externalLogin == null,
LoginProvider = externalLogin != null ? externalLogin.LoginProvider : null
};
return userinfo;
}
From the client, this actin will be called through the token as a header.
Once we have got the information (is in Json string format) needs to serialize with the UserInfoViewModel class (user defined viewmodel is based on the info we require and send from webapi account) with javascript serializer
Using these viewmodel information, assign them to local storage and using (cookies for my case) as a identity at local
keep logout webapi too when ever you logs out from web app.
Please let me know if you need more info or code

How to build secured api using ServiceStack as resource server with OAuth2.0?

I have build a OAuth2.0 Authorization server using dotnetopenauth that will manage authentication, authorization, and assign accessToken to the caller. The caller will use the access token to access the api (webservices) at resource server.
If follow the sample provided by dotnetopenauth in Resource Server, api that builded using WCF can be authenticated by OAuthAuthorizationManager
If using ServiceStack to build my api in Resource Server, how to build the authentication process that verify the incoming api request based on assigned OAuth2.0 access token? The functionality should similar to OAuthAuthorizationManager in the dotnetopenid sample and not based on login session.
Just some update
I didn't use the AuthenticateAttribute or RequiredRoleAttribute from ServiceStack.ServiceInterface.
I create 2 custom RequestFilterAttribute to replace the functions provided by AuthenticateAttribute and RequiredRoleAttribute.
In each custom RequestFilterAttribute's Execute method, I'm using method in dotnetopenauth to verify the access token.
//httpReq==req from Execute(IHttpRequest req, IHttpResponse res, object requestDto)
The code for the access token verification as following, reference the relevant documentation from both servicestack and dotnetopenauth for more info. ResourceServer is class from dotnetopenauth
HttpRequestBase reqBase = new HttpRequestWrapper((System.Web.HttpRequest)httpReq.OriginalRequest);
var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(AuthorizationServerPublicKey, ResourceServerPrivateKey));
IPrincipal ip = null;
resourceServer.VerifyAccess(reqBase, out ip);
If the ip is null then not authenticated, if not null, the incoming request is valid and can use the ip to check the role e.g. ip.IsInRole(requiredRole)
I'm not sure this is the correct way to do the checking or not, but it's works for me. Any better solution are welcome.

How to develop user-authenticated REST service with Azure ACS

I'm developing a REST service that uses MS Azure Access Control Service for authentication. If the examples are any indication, the typical way to secure a REST service this way would be to provide a global username and pw, private key, or X.509 cert for the protected service. However, I want to use the passive user login mechanism on a mobile device with a flow more like the following:
Unauthenticated user attempts to access protected service from app
Mobile app redirects to browser app (or embedded browser)
User selects identity provider to use for login (facebook, google, etc.) from ACS login page
User enters credentials for identity provider
Browser redirects back to app
App somehow gets the SWT token to use with subsequent REST requests.
I'm stuck at about step 5--getting the SWT token, and the existing examples I've found don't seem to address this scenario. In addition, I'm actually trying to build a proof of concept with a desktop client in WPF, which may complicate things. Can anyone suggest a specific tutorial or a path to pursue that uses the per-user authentication vs. per-service? Thanks.
EDIT:
As I'm digging into this deeper, I've realized that the examples posted below (and most others) are based on OAuth WRAP, which has been deprecated in favor of OAuth 2.0. Can anyone suggest a more up to date reference? Googling has turned up http://blogs.msdn.com/b/adventurousidentity/archive/2011/09/18/acs-v2-oauth-2-0-delegation-support-explained.aspx and http://connect.microsoft.com/site1168/Downloads/DownloadDetails.aspx?DownloadID=32719 but they're not the most intuitive.
You should look into the ACS Windows Phone sample:
http://msdn.microsoft.com/en-us/library/gg983271.aspx
Here instead of using Silverlight you will be using WPF. Most of the code should be re-usable. Note that since you are using WPF you will need to register your own object for scripting e.g:
[ComVisibleAttribute(true)]
public class NotifyHandler
{
public void Notify(string notifyString)
{
// Here I have the token.
}
}
this.webBrowser1.ObjectForScripting = new NotifyHandler();
Update:
The sample above uses OAuth Wrap to contact the secured service. If you would like to use OAuth2 you should change the way the "Authorization" header set:
OAuth WRAP case:
WebClient client = new WebClient();
client.Headers["Authorization"] = "OAuth " + _rstrStore.SecurityToken;
OAuth2 case:
WebClient client = new WebClient();
client.Headers["Authorization"] = string.Format("OAuth2 access_token=\"{0}\"", token);
You can use the "Simple Service" sample as a guide to implement your token validation in your REST service:
http://msdn.microsoft.com/en-us/library/gg185911.aspx
Yet if you would like to implement a more complete sample you can look at how CustomerInformationService is protected in the CTP version 1.4:
https://connect.microsoft.com/site1168/Downloads/DownloadDetails.aspx?DownloadID=35417
Take a look at this one:
WPF Application With Live ID, Facebook, Google, Yahoo!, Open ID
http://social.technet.microsoft.com/wiki/contents/articles/4656.aspx

Resources