Code Monkey home page Code Monkey logo

Comments (12)

mark-szabo avatar mark-szabo commented on August 27, 2024

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:

return await _app.AcquireTokenByAuthorizationCode(_scopes, authorizationCode).ExecuteAsync();

from aspnetcore-connect-sample.

deepika537 avatar deepika537 commented on August 27, 2024

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.

mark-szabo avatar mark-szabo commented on August 27, 2024

Sorry, wrong line linked - my bad.

return await _app.AcquireTokenByAuthorizationCode(_scopes, authorizationCode).ExecuteAsync();

It will be called after the user authentication against AAD is successful:

var result = await _authProvider.GetUserAccessTokenByAuthorizationCode(code);

from aspnetcore-connect-sample.

deepika537 avatar deepika537 commented on August 27, 2024

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.

mark-szabo avatar mark-szabo commented on August 27, 2024
  • 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:

var result = await _authProvider.GetUserAccessTokenByAuthorizationCode(code);

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:

if (User.Identity.IsAuthenticated)
{
// Get users's email.
email = email ?? User.FindFirst("preferred_username")?.Value;
ViewData["Email"] = email;
// Initialize the GraphServiceClient.
var graphClient = _graphSdkHelper.GetAuthenticatedClient((ClaimsIdentity)User.Identity);
ViewData["Response"] = await GraphService.GetUserJson(graphClient, email, HttpContext);
ViewData["Picture"] = await GraphService.GetPictureBase64(graphClient, email, HttpContext);
}

from aspnetcore-connect-sample.

deepika537 avatar deepika537 commented on August 27, 2024

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.

deepika537 avatar deepika537 commented on August 27, 2024

New code: email = email ?? User.Identity.Name

from aspnetcore-connect-sample.

mark-szabo avatar mark-szabo commented on August 27, 2024

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.

deepika537 avatar deepika537 commented on August 27, 2024

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.

Screen Shot 2019-11-27 at 3 45 11 PM

from aspnetcore-connect-sample.

deepika537 avatar deepika537 commented on August 27, 2024

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

Screen Shot 2019-11-27 at 3 59 09 PM

from aspnetcore-connect-sample.

deepika537 avatar deepika537 commented on August 27, 2024

Hello,

Did you understand my problem?

Can you help me?

from aspnetcore-connect-sample.

mark-szabo avatar mark-szabo commented on August 27, 2024

Have you tried opening it in an incognito window? Maybe something with the cookies is corrupted.

from aspnetcore-connect-sample.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.