TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Paul John
NA
6
602
Generate Access Token For Dynamics 365 Single Tenant Server To Server
Nov 9 2020 9:16 AM
Hi Experts,
I am new to console app . using OAuth, I am trying to connect to crm and retrieve all accounts records as show in below code.
using
Microsoft.IdentityModel.Clients.ActiveDirectory;
using
System;
using
System.Net.Http;
using
System.Net.Http.Headers;
using
System.Text;
using
System.Threading.Tasks;
using
System.Net.Sockets;
namespace
CRMConnection
{
class
Program
{
static
void
Main(
string
[] args)
{
var accounts = CrmRequest(HttpMethod.Get,
"crmurl/api/data/v9.1/accounts"
).Result.Content.ReadAsStringAsync();
}
/// Method-to-generate-Access-Token
public
static
async Task<
string
> AccessTokenGenerator()
{
string
clientId =
"ID"
;
string
clientSecret =
"Secret code"
;
string
authority =
"login.microsoft.com/tenantID/oauth2/v2.0/token"
;
string
resourceUrl =
"CRMUrl"
;
var credentials =
new
ClientCredential(clientId, clientSecret);
var authContext =
new
Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority);
var result = await authContext.AcquireTokenAsync(resourceUrl, credentials);
return
result.AccessToken;
}
public
static
async Task<HttpResponseMessage> CrmRequest(HttpMethod httpMethod,
string
requestUri,
string
body =
null
)
{
var accessToken = await AccessTokenGenerator();
var client =
new
HttpClient();
var msg =
new
HttpRequestMessage(httpMethod, requestUri);
msg.Headers.Add(
"OData-MaxVersion"
,
"4.0"
);
msg.Headers.Add(
"OData-Version"
,
"4.0"
);
msg.Headers.Add(
"Prefer"
,
"odata.include-annotations=\"*\""
);
// Passing AccessToken in Authentication header
msg.Headers.Add(
"Authorization"
, $
"Bearer {accessToken}"
);
if
(body !=
null
)
msg.Content =
new
StringContent(body, UnicodeEncoding.UTF8,
"application/json"
);
return
await client.SendAsync(msg);
}
}
}
I am getting below error: The program '[24580] CRMConnection.exe' has exited with code 0 (0x0).
Reason: I need to check the roles in another call and assign system admin access. can anyone please provide the code on how to achieve this?
Reply
Answers (
1
)
how to convert its first character to upper
using variables from another class