Get refresh token additionally to access token with Microsoft.Identity.Client - c#

I use several properties like tenant id, client id, client secret, redirect uri and an authorization code generated for a user. I need to get the access and refresh token, but with the API that don't return anything like a refresh token. I need a refresh token additionnally to the access token and the expire in time.
I use this following code:
ConfidentialClientApplicationOptions options = new ConfidentialClientApplicationOptions();
options.ClientId = clientId;
options.TenantId = tenantId;
options.ClientSecret = clientSecret;
options.RedirectUri = redirectUri;
ConfidentialClientApplicationBuilder builder = ConfidentialClientApplicationBuilder.
CreateWithApplicationOptions(options);
IConfidentialClientApplication app = builder.Build();
AcquireTokenByAuthorizationCodeParameterBuilder acquireTokenBuilder =
app.AcquireTokenByAuthorizationCode(ServiceConstants.ALL_SCOPE_AUTHORIZATIONS.Split(' '), authorizationCode);
AuthenticationResult result = await acquireTokenBuilder.ExecuteAsync();
string accessToken = result.AccessToken;
// NO string refreshToken = result.RefreshToken
Its very strange because in several example, I see the RefreshToken available in AuthenticationResult, but not in mine. Do you know why ? And how I can get the refresh token plz ?
Because after that I will need to refresh the access token when will expire and I only have the access token, tenant id, client id, secret (or certificate) and redirect uri. BTW How to regenerate it after access token expiration ?
thank a lot and best regards
Adrien

You need to check what is passed as ServiceConstants.ALL_SCOPE_AUTHORIZATIONS in both /authorize and /token requests. The list of scopes should contain offline_access scope as it tells Azure that your application will need a refresh token for extended access to resources.
The refresh token will have a longer lifetime than the access token, therefore whenever your access token expires you will be able to call the /token endpoint again providing the previously received refresh token and using the parameter grant_type=refresh_token.

I tried to reproduce the same in my environment and got the results like below:
I created an Azure AD Application and added API permissions:
Note that: To get refresh token make sure to grant offline_access API permission in your Azure AD Application and include it in the scope while generating access token.
I generated access and refresh token using below parameters in Postman:
GET https://login.microsoftonline.com/TenantId/oauth2/v2.0/token
client_id:ClientID
client_secret:ClientSecret
scope:https://graph.microsoft.com/.default offline_access
grant_type:authorization_code
redirect_uri:RedirectUri
code:code
To get this in your code you can include the below line:
refreshToken = result.RefreshToken
To refresh the access token, I used the parameters like below:
https://login.microsoftonline.com/TenantID/oauth2/v2.0/token
client_id:ClientId
grant_type:refresh_token
refresh_token:refreshtoken
client_secret:ClientSecret
Sample Code:
AzureADApp.AcquireTokenByRefreshToken(RefreshToken, scope) .ExecuteAsync();
var refreshedAccessToken = result.AccessToken;

Related

How to set custom claims to aad token using C# code

I have a webapi which generates aad token and I have written token generation logic in Get() method in webapi.
I'm able generate aad jwt token from webapi get() method but, now I want to include some custom claims into the token.
How can I set custom claims to aad token using c#.
I have used below code for generating aad token.
var authenticationContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext("https://login.windows.net/" + ConfigurationManager.AppSettings["TenantID"].ToString());
var credential = new ClientCredential(clientId: ConfigurationManager.AppSettings["ClientID"].ToString(), clientSecret: secret);
var result = await authenticationContext.AcquireTokenAsync(
ConfigurationManager.AppSettings["Resource"].ToString(),
credential
).ConfigureAwait(false);
Kindly share any sample c# code to set custom claims to aad token generated from above code .
Note: I want to set a new custom claim for aad token where custom claim value obtained from external logic.
Update 1:
Looks like below post may be useful.
https://www.rahulpnath.com/blog/azure-ad-custom-attributes-and-optional-claims-from-an-asp-dot-net-application/
I tried below following above post.
Generated jwt token to call Graph API. But I got blocked at below code.
var dictionary = new Dictionary<string, object>();
dictionary.Add(employeeCodePropertyName, employee.Code);
//Here I can't use graphApiClient.Users because, I don't have any user info on my jwt token. It will be just Access token which as details related to aad application.I want to update extension attribute which is present in OptionalClaims -> Access Token of AAD Application Manifest.
await graphApiClient.Users[employee.EmailAddress]
.Request()
.UpdateAsync(new User()
{
AdditionalData = dictionary
});
How to update extension claim attribute present in access token of optional claims . I want to update through c# code.
How to do that. Kindly suggest.
Update 2:
I want to use code similar to below for updating custom extension claim attribute present in optional claims of azure ad app but UpdateAsync is not working.
await graphApiClient.Application[clientid]
.Request()
.UpdateAsync(new Application()
{
AdditionalData = dictionary
});
At UpdateAsync(), I'm getting issue as below
Specified HTTP method is not allowed for the request
Kindly let me know the solution to add custom user defined claim to azure ad access token.
Note: Since, I want to update access token ,there will be not be any user info on access token. So, graphApiClient.Users[employee.EmailAddress] won't work, as access token will not have any user info like EmailAddress
I have created extension claim attribute in azure ad ap manifest as below
I want to update extension claim attribute extension_clientid_moviename value dynamically with value obtained from external source through code. How to do that. Kindly suggest.
Update 3:
I have tried below code to update extension claim attribute present in Optional claims ID Token.
await graphApiServiceClient.Users["abcd#hotmail.com"]
.Request()
.UpdateAsync(new User()
{
AdditionalData = dictionary
});
I am getting error as below
Code: Request_ResourceNotFound\r\nMessage: Resource '' does not exist or one of its queried reference-property objects are not present.
That is because you are using OAuth 2.0 client credentials flow to get access token :
https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow
That flow is commonly used for server-to-server interactions without immediate interaction with a user. So you can't find user information in access token .
The document you provided is adding User's extension property , update that value via Microsoft Graph :
await graphApiClient.Users[employee.EmailAddress]
.Request()
.UpdateAsync(new User()
{
AdditionalData = dictionary
});
That email is not from access token , you should manually provide the user's email who the api wants to update the properties value .
But since the property is a User's extension property , you can get the value from claims in ID token when user login with Azure AD in your client app . That claim won't include in access token which issued using client credential flow .
Regarding the issue in Update 3, we can not use the guest user email here. We should use ObjectId instead. That's why you got Request_ResourceNotFound error.
await graphApiServiceClient.Users["ObjectId"]
.Request()
.UpdateAsync(new User()
{
AdditionalData = dictionary
});

How to get the oauth refresh token?

I have a web app which utlizes Oauth and is unable to reuse the authToken due to the error below.
{"AADSTS70002: Error validating credentials. AADSTS54005: OAuth2 Authorization
code was already redeemed, please retry with a new valid code or use an
existing refresh token.\r\nTrace ID: 30c342a7-f16a-4a05-a4a8-
c7ee2c722300\r\nCorrelation ID: 3a5c99d1-ca1c-4cd7-bd36-
cce721bf05b6\r\nTimestamp: 2018-11-21 00:26:18Z"}
I'm told this is a know issue/update here and here.
...okay, fine so now I'm trying to get the refresh token so I can regenerate my access token but I'm having trouble getting something to work.
I have tried the ones below:
https://learn.microsoft.com/en-us/bingads/shopping-content/code-example-authentication-oauth - this one does not seem to work and throws an exception when I try to get the accesstoken or refresh token. stating that one or more errors have occured.
https://auth0.com/docs/api/authentication#authorization-code-pkce- - but does not return the refresh token. Could this be because I don't have the code_verifier? If so, how would I get that?
Authorization Code (PKCE) Image
Below is a code sample which I am using - problem here is that I can only use this once and once It has been redemed I cannot retrive it silently as it no longer exists in the cache.
ClientCredential clientcred = new ClientCredential(Constants.ClientId, Constants.AppKey);
TokenCache TC = new TokenCache();
AuthenticationContext AC = new AuthenticationContext(Constants.Authority, TC);
//Set token from authentication result
AuthenticationResult authenticationResult = await AC.AcquireTokenByAuthorizationCodeAsync(
Constants.Code,
new Uri(Constants.postLogoutRedirectUri + "Index"), clientcred);
return authenticationResult.AccessToken;
You need to call OAuth2 authorize endpoint with offline_access scope to get refresh token.
You should call AcquireTokenByAuthorizationCodeAsync only once when you receive authorization code and should not use the result. azure ad sample
You need to call AcquireTokenSilently when you want to get access token. azure ad sample
This azure ad sample use a TokenCache implementation by user id.
Authorize request
Token request
Good luck!

How to acquire graph token without using sessions?

I have an application that is utilizing Azure AD authentication. I also need to access the Microsoft Graph API for user data. Every example I have found that makes requests to the Graph API is utilizing a cached session token, but since I am using JWT obviously I have no need for storing session state. How can I get a JWT with the proper audience using a JWT with my app as the audience?
For example, here is a request to retrieve a token from the Microsoft Graph AspNetCore Sample:
_userTokenCache = new SessionTokenCache(userId, _memoryCache).GetCacheInstance();
var cca = new ConfidentialClientApplication(
_appId,
_redirectUri,
_credential,
_userTokenCache,
null);
var result = await cca.AcquireTokenSilentAsync(_scopes, cca.Users.First());
return result.AccessToken;
Which utilizes the memory cache to pull the token from a Challenge() redirect sign-in with OpenId Connect cookie. However, since I am using JWT, I already have a bearer token, but with the wrong authority. What do I need to do to acquire a new token that I can use to access the Graph API? I still want the tokens to be authorized for my application id, so I would want a new token that allows me to access the API with server-side rest requests.
Edit: Incorrectly tagged as Azure AD Graph, retagged to Microsoft Graph.
Edit Edit: To clarify, each of the samples I've seen so far is using Session cookies as so:
services.AddAuthentication(sharedOptions => {
sharedOptions.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddAzureAd(options => Configuration.Bind("AzureAd", options))
.AddCookie();
However, I am using JWT so I don't have a token cached:
app.UseJwtBearerAuthentication(new JwtBearerOptions {
Authority = $"{instance}{tenant}",
Audience = audience,
SaveToken = true
});
The JWT that I get from requests to login.microsoftonline.com have my application as the audience, whereas the JWT generated by these samples have https://graph.microsoft.com as the audience. So I need to get (I presume at least) a token for this audience using only the token I got from my standard authentication request.
Don't confuse how you manage your token (i.e. token cache) with the tokens themselves. The reason you cache a token is simply so you can request a refreshed token as needed (refresh_token). The refresh token is only provided for certain sceanios (i.e. when using the authorization_code flow and you've requested the offline_access scope).
If you're using a flow without a refresh token (i.e implicit or client_credentials) then you may not need to cache your token. You generally should still cache them since there is an overhead cost to fetching a token from AAD and caching allows you to only retrieve a new token when the existing one expires.
Using DelegateAuthenticationProvider with an existing Token
All that said, it sounds like you've already got a token in hand. Since the entire point of MSAL (which is where ConfidentialClientApplication comes from) it to retrieve and manage tokens for you, I'm not exactly sure why you'd want to do this. I would simply skip MSAL entirely and just use your existing token.
If you're using the Microsoft Graph .NET Client Library you can drop MSAL entirely and simply use your existing token (access_token) via the DelegateAuthenticationProvider:
var graphServiceClient = new GraphServiceClient(
new DelegateAuthenticationProvider((requestMessage) => {
requestMessage.Headers.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", token.access_token);
return Task.FromResult(0);
})
);
As for the "proper audience", I'm not sure I understand the context. Your token will need to include scopes for Microsoft Graph but how you define them depends a bit on how you are getting your token.
v1 Endpoint
If you're using the older Azure AD OAUTH endpoint (aka the v1 Endpoint) then you need to configure your Application permissions via the Azure Portal. In order to switch between different APIs (called "Resources") you need to request offline_access and user the refresh_token. Switching involves requesting a refreshed token while passing in a new resource. The resulting token will then work with that resource.
For example, if my default resource is a SharePoint Online instance (https://tenant.sharepoint.com) then I would normally refresh my token with something like this:
private async Task<string> RequestTokenAsync() {
var data = new Dictionary<string, string>();
data.Add("grant_type", "refresh_token");
data.Add("client_id", _clientId);
data.Add("client_secret", _clientSecret);
data.Add("resource", "https://tenant.sharepoint.com");
data.Add("redirect_uri", RedirectUri);
data.Add("refresh_token ", refresh_token);
HttpClient httpClient = new HttpClient();
var response = await httpClient.PostAsync(_tokenUri, new FormUrlEncodedContent(data));
response.EnsureSuccessStatusCode();
var result = await result.Content.ReadAsStringAsync();
}
Now if I want to make a call to Microsoft Graph I will first need to get a token for the https://graph.microsoft.com resource:
private async Task<string> RequestTokenAsync() {
var data = new Dictionary<string, string>();
data.Add("grant_type", "refresh_token");
data.Add("client_id", _clientId);
data.Add("client_secret", _clientSecret);
data.Add("resource", "https://graph.microsoft.com");
data.Add("redirect_uri", RedirectUri);
data.Add("refresh_token ", refresh_token);
HttpClient httpClient = new HttpClient();
var response = await httpClient.PostAsync(_tokenUri, new FormUrlEncodedContent(data));
response.EnsureSuccessStatusCode();
var result = await result.Content.ReadAsStringAsync();
}
Now I have two tokens, one for SharePoint and one for Microsoft Graph. I can switch between resources by simply refreshing the token for the proper resource. I do have to make sure I refresh properly however since if my refresh_token expires before I can replace it, I've lost my credentials entirely.
If this sounds complicated, it is. Generally you need to build some mechanisms to manage which tokens are live, which tokens need to be replaced, etc. This is what that token cache is all about since MSAL/ADAL handle this for you.
v2 Endpoint
The newer v2 Endpoint is far easier to work with. Rather than resources it uses scopes. These scopes include the resource identifier and can be dynamically assigned as needed.
So while in v1 we might assign user.read from Microsoft Graph and user.read from Outlook Rest API, we can now assign both at once in a single token by requesting https://graph.microsoft.com/user.read and https://outlook.office.com/user.read at the same time. This means we get a single token that can be used with either API without getting into the "refresh to switch resource" business from above.
The downside of v2 is that only a limited number of APIs support it at the moment. If you need to work across a number of APIs, you may still be better off using v1 for this reason.
Hope this helps a little.

Cant authenticate user silently with ADAL for Office 365 REST API on ASP.NET MVC

So I'm trying to implement persistent tokens for our office authentication so that the user does not have to sign into office each time they are in a new session. The code I currently have to authenticating the user is as below.
string authority = "https://login.microsoftonline.com/common";
var tokenCache = new ADALTokenCache(User.Identity.GetUserId());
AuthenticationContext authContext = new AuthenticationContext(authority, tokenCache );
var token = authContext.AcquireTokenSilentAsync(scopes, clientId, new UserIdentifier(userId, UserIdentifierType.RequiredDisplayableId));
But everything I've tried so far gives me the error below
The Exception is: "Failed to acquire token silently. Call method AcquireToken"
The method Im using to aquire the token in the first place is as below
string authority = "https://login.microsoftonline.com/common";
var fileCache = new ADALTokenCache(User.Identity.GetUserId());
AuthenticationContext authContext = new AuthenticationContext(authority, fileCache);
var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
authCode, redirectUri, credential, scopes);
And the token cache im using is a db implementation which I made from a tutorial which I cannnot find again, if I watch the db I can see that new tokens are being inserted into the db when AcquireTokenByAuthorizationCodeAsync is called.
Update:
This is my result from authResult when calling AcquireTokenByAuthorizationCodeAsync
I have marked Virbonet's answer as the solution but I have not fixed it but he did explain to me where I was going wrong
AcquireTokenSilent cannot work if you are passing /common in the authority. Using "common" is equivalent to declaring that you don' know what tenant is the user from, hence ADAL cannot return a cached token form a specific tenant - user interaction is required to determine which tenant should be used.
If you want to call AcquireTokenSilent you need to initialize the authority with the exact tenant of the incoming user, as in "https://login.microsoftonline.com/"+tenantID here tenantID is the tenantID from the current ClaimsPrincipal.
This is the function call you need to use: AcquireTokenByAuthorizationCode() but not AcquireTokenSilent().
Hope this helps.

c# - how to get user access token without login from facebook?

I want to get user access token(Graph API Explorer) from facebook without login
I tried with app access token but I am unable to get comments for the posts
Code is for app access token:
string appId = "APP_Id";
string appSecret = "APP_Secret";
var fb = new FacebookClient();
dynamic result = fb.Get("oauth/access_token", new
{
client_id = appId,
client_secret = appSecret,
grant_type = "client_credentials"
});
fb.AccessToken = result.access_token;
var accessToken = fb.AccessToken;
Any ideas? Thanks in advance.
You have to create a new instance of the FacebookClient with the Users AccessToken to get info about the User!
I think here is no way you get the Token without calling the FB.Login
From the API Documentation:
User Access Token – The user token is the most commonly used type of token. This kind of access token is needed any time the app calls
an API to read, modify or write a specific person's Facebook data on
their behalf. User access tokens are generally obtained via a login
dialog and require a person to permit your app to obtain one.

Categories

Resources