Comments (12)
Hi @deepika537,
that's absolutely fine that this line returns null
. It means there is no valid token cached in the TokenCache (eg. you are trying to authenticate after you restarted the application).
This line should get you the token from AD:
from aspnetcore-connect-sample.
Thank you for your quick reply.
The below function also returns "null" because we are passing "account" as a parameter which is null.
var result = await _app.AcquireTokenSilent(_scopes, account).ExecuteAsync();
from aspnetcore-connect-sample.
Sorry, wrong line linked - my bad.
It will be called after the user authentication against AAD is successful:
from aspnetcore-connect-sample.
My application got stuck in the function GetUserAccessTokenAsync() and it never entered the function GetUserAccessTokenByAuthorizationCode() because we call GetUserAccessTokenAsync() function from GraphSDKHelper.cs file at line 33.
Please find my code in GraphSDKHelper.cs file
// Get an authenticated Microsoft Graph Service client.
public GraphServiceClient GetAuthenticatedClient(ClaimsIdentity userIdentity)
{
_graphClient = new GraphServiceClient(new DelegateAuthenticationProvider(
async requestMessage =>
{
// Get user's id for token cache.
//userIdentity.FindFirst(ClaimTypes.NameIdentifier).Value;
var identifier = userIdentity.FindFirst(Startup.ObjectIdentifierType)?.Value + "." + userIdentity.FindFirst(Startup.TenantIdType)?.Value;
// Passing tenant ID to the sample auth provider to use as a cache key
var accessToken = await _authProvider.GetUserAccessTokenAsync(identifier);
// Append the access token to the request
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
// This header identifies the sample in the Microsoft Graph service. If extracting this code for your project please remove.
requestMessage.Headers.Add("SampleID", "aspnetcore-connect-sample");
}));
return _graphClient;
}
GraphAuthprovider.cs
public async Task GetUserAccessTokenAsync(string userId)
{
var account = await _app.GetAccountAsync(userId);
if (account == null) throw new ServiceException(new Error
{
Code = "TokenNotFound",
Message = "User not found in token cache. Maybe the server was restarted."
});
try
{
var result = await _app.AcquireTokenSilent(_scopes, account).ExecuteAsync();
return result.AccessToken;
}
// Unable to retrieve the access token silently.
catch (Exception)
{
throw new ServiceException(new Error
{
Code = GraphErrorCode.AuthenticationFailure.ToString(),
Message = "Caller needs to authenticate. Unable to retrieve the access token silently."
});
}
}
Whats wrong with my code?
from aspnetcore-connect-sample.
- You press the login button.
- You are redirected to AAD to log in.
- After logging in you are redirected back to the app and
OnAuthorizationCodeReceived
is called. - It will get the access token by the authorization code received:
GetUserAccessTokenAsync()
won't work for the first time, because it checks the existence of a token in the token cache and if it does not found anything, throws an error.
GetUserAccessTokenAsync()
should not be called before authenticating the user first. You can see this here:
from aspnetcore-connect-sample.
In My application, After clicking on login button, the value of "User.Identity.IsAuthenticated" is true and it entered in to the if loop and called the function (_graphSdkHelper.GetAuthenticatedClient((ClaimsIdentity)User.Identity); ) and the function throws an error.
After few secs final results says that we could not signIn, Please try again. I only replaced below line with email = email ?? User.Identity.Name;
Old Code: email = email ?? User.FindFirst("preferred_username")?.Value;
New Code: email = email ?? User.FindFirst("preferred_username")?.Value;
from aspnetcore-connect-sample.
New code: email = email ?? User.Identity.Name
from aspnetcore-connect-sample.
Wait a sec. You are telling that you click the login button and you are not redirected to AD and authenticated correctly, but User.Identity.IsAuthenticated
is true?
from aspnetcore-connect-sample.
I entered my credentials and clicked on login button. After successful login I should be able to see my profile and photo instead of that it gave me an error because the applications do not have access token to get my details.
While debugging I came to know that the value of "User.Identity.IsAuthenticated" is true but the value of var account = await _app.GetAccountAsync(userId); is null.
I was successfully authenticated with AAD (because I can see home page without my profile data) but I could not connect to Microsoft Graph.
Please look at the screenshot below.
from aspnetcore-connect-sample.
I can see home page without profile details if I use below line in HomeController.cs
email = email ?? User.FindFirst("preferred_username")?.Value;
But If I replace the above line with below line then I can not see home page instead I see below page.
email = email ?? User.Identity.Name
from aspnetcore-connect-sample.
Hello,
Did you understand my problem?
Can you help me?
from aspnetcore-connect-sample.
Have you tried opening it in an incognito window? Maybe something with the cookies is corrupted.
from aspnetcore-connect-sample.
Related Issues (20)
- Configuring for single tenant HOT 2
- Access denied when trying to get mail messages HOT 2
- ConfidentialClientApplication.AcquireTokenForClientAsync(IEnumerable<string>)' is obsolete HOT 2
- Authentication success, but after redirect to site Getting the error page - Azure app service HOT 2
- The profile picture is not loading and getting access denied error. HOT 1
- User not found in token cache HOT 6
- Supported account types issue HOT 1
- Needs updating to MSAL v4.0
- Application using http vs https HOT 3
- Transient creation of GraphServiceClient HOT 2
- build failed HOT 1
- Restart IIS in production returns error if user is logged in HOT 3
- After signin in to AAD - Exception: Correlation failed. HOT 2
- Code is not usable in a deployed web app. HOT 6
- Release version for production env HOT 3
- Single tenant - Guest Account login error - Null Token HOT 2
- Retrieve user groups in Startup.cs HOT 1
- Error when running application (single-tenant vs multi-tenant) HOT 3
- This repo is missing important files
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from aspnetcore-connect-sample.