Starts in:
1 DAY
18 HRS
20 MIN
26 SEC
Starts in:
1 D
18 H
20 M
26 S
Open Closed

fetch Photo of an Azure AD User when we do authentication using OpenIddic #4799


User avatar
0
oshabani created
  • ABP Framework version: 7.0.3
  • UI type: MVC
  • DB provider: EF Core
  • Tiered (MVC) or Identity Server Separated (Angular): yes
  • Exception message and stack trace:
  • Steps to reproduce the issue:"

Hi,

how could we fetch Photo of an Azure AD User when we do authentication using OpenIddic option in Auth-Server

regards,


25 Answer(s)
  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    Can you explain it in detail? I don't quite understand what you mean.

  • User Avatar
    0
    oshabani created

    well, we are using ABP as our Auth-Server , we already configure this Server to to authenticate with our Azure Active Directory service using OpenIddic , users in our Azure AD has their photos upload there ,we want to fetch this user photos and save it in our Auth-Server database in table ([AbpBlobs]) with the generate User ID once the User grant permission to Auth-Server

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    You can set it in azure to return the claim of the user's photo, and then you can get it in the OpenIdConnect event and save it.

    .AddAbpOpenIdConnect("oidc", options =>
        {
            //...
    
            options.Events.OnTokenValidated = tokenValidatedContext =>
            {
                var photoClaim = tokenValidatedContext.Principal.Claims.FirstOrDefault(x => x.Type == "photo");
    
                return Task.FromResult(Task.CompletedTask);
            };
    
    
            //...
    
        });
    

    If this doesn't work, you can request azure's api to get photo through access-token.

    await httpContext.GetTokenAsync("access_token");
    
  • User Avatar
    0
    oshabani created

    await httpContext.GetTokenAsync("access_token");

    I am trying to get access token to get photo through Graph API but it is returning null.

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    Please share your code of ConfigureAuthentication

    eg

    
     context.Services.AddAuthentication(options =>
                    {
    
                    })
                    .AddCookie("Cookies", options =>
                    //.........
    
  • User Avatar
    0
    oshabani created

    AuthServerModule.cs

        .AddOpenIdConnect("AzureOpenId", "SbgEmailAccount", options =>
            {
                options.Authority = "https://login.microsoftonline.com/" + configuration["AzureAd:TenantId"] + "/v2.0/";
                options.ClientId = configuration["AzureAd:ClientId"];
                options.ResponseType = OpenIdConnectResponseType.Code; // CodeIdToken;
                options.CallbackPath = configuration["AzureAd:CallbackPath"];
                options.ClientSecret = configuration["AzureAd:ClientSecret"];
                options.SignedOutCallbackPath = configuration["AzureAd:SignedOutCallbackPath"];
        options.RequireHttpsMetadata = false;
                options.SaveTokens = true;
                options.GetClaimsFromUserInfoEndpoint = true;
                options.Prompt = "consent";
                options.Scope.Add("profile");
                options.Scope.Add("email");
                options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "sub");
                options.Events.OnTokenValidated = async tokenValidatedContext => 
                {
                    //not working
                    //var photoClaim = tokenValidatedContext.Principal.Claims.FirstOrDefault(x => x.Type == "photo");
                    var accessToken = await tokenValidatedContext.HttpContext.GetTokenAsync("access_token");
                    //var accessToken = tokenValidatedContext.TokenEndpointResponse.AccessToken;
                    //return Task.FromResult(Task.CompletedTask);
                    var client = new RestClient("https://graph.microsoft.com/v1.0/");
                    var request = new RestRequest("me/photo/$value", Method.Get);
                    request.AddHeader("Content-Type", "application/json");
                    request.AddHeader("Authorization", "Bearer " + accessToken);
                    RestResponse response = await client.ExecuteAsync(request);
                    var aa = response.RawBytes;
                };
            }
            ```
    
  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    Please share full code of context.Services.AddAuthentication....

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    I will confirm OnTokenValidated again.

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    options.Events.OnTokenResponseReceived = async onTokenResponseReceivedContext =>
    {
        var accessToken = onTokenResponseReceivedContext.TokenEndpointResponse.AccessToken;
    
        await Task.CompletedTask;
    };
    

  • User Avatar
    0
    oshabani created

    options.Events.OnTokenValidated = async tokenValidatedContext => { //not working //var photoClaim = tokenValidatedContext.Principal.Claims.FirstOrDefault(x => x.Type == "photo"); //var accessToken = await tokenValidatedContext.HttpContext.GetTokenAsync("access_token");

    var accessToken = tokenValidatedContext.TokenEndpointResponse.AccessToken;
                //return Task.FromResult(Task.CompletedTask);
                var client = new RestClient("https://graph.microsoft.com/v1.0/");
                var request = new RestRequest("me/photo/$value", Method.Get);
                request.AddHeader("Content-Type", "application/json");
                request.AddHeader("Authorization", "Bearer " + accessToken);
                RestResponse response = await client.ExecuteAsync(request);
                var aa = response.RawBytes;
            };
    

    I have already checked this and passed to graph API as mentioned in the code above but it is not authorizing it. Once I checked the details of this access token with jwt.io that is actually a JWT token. Maybe because of this reason graph API is not authorizing.

  • User Avatar
    0
    oshabani created

    Our primary objective is to save the azure profile photo with register page of AuthServer.

    Maybe getting photo on OnTokenValidated event is not good enough. I am not sure about it. So please help us to find the resolution for this.

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    I mean you can get access_token on OnTokenResponseReceived instead of OnTokenValidated

    https://support.abp.io/QA/Questions/4799#answer-3a0a6184-5a12-c5bc-3538-2d7cba8ad485

    Can you share a simple project with me? include your AddOpenIdConnect configuration and test user & password.

    liming.ma@volosoft.com

    I will try the OnTokenResponseReceived

  • User Avatar
    0
    oshabani created

    We shared the link of the uploaded project with you at liming.ma@volosoft.com

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    Thanks, I will check it asap.

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    Hi

    Please share a test user and password, Im trying to signin.

    Thanks.

  • User Avatar
    0
    oshabani created

    Hi,

    In order to sign in to azure ad account. Please do the following steps"

    1. you can sign in with any Microsoft account that you will provide us. We will add this account to Azure AD and will send you the invitation to accept it.

    2. Replace appsettings.development in AuthServer project "AzureAd": { "Instance": "https://login.microsoftonline.com/", "TenantId": "9affbb38-3096-4eb1-bcac-4b709bedc8af", "ClientId": "b53c656e-f7eb-4474-a7bc-826bf93eed03", "Domain": "domain.onmicrosoft.com", "CallbackPath": "/signin-azuread-oidc", "SignedOutCallbackPath ": "/signout-azuread-oidc", "ClientSecret": "Amw8Q~gPtjSivovD-j1TKgI~JuNHfbl7LwKB8c6g" },

    3. Comment the validation lines related to employee, civilid and dcu/oracle in OnPostAsync (AuthServer/Pages/Account/Register.cshtml.cs) handler

      //if (Input.EmployeeNo <= 0) //{ // throw new UserFriendlyException("Invalid Employee No"); // //Alerts.Danger("Invalid Employee Number"); // //return Page(); //}

      ////civil id validation //if (!ValidateTool.ValidateCivilId(Input.CivilId.ToString())) //{ // throw new UserFriendlyException("Invalid CivilId"); //}

      #region check validation from dcu // var data = await new RestSharpFactory().ExecuteJsonAsync<bool>( // _configuration["Services:OracleEbs_V1"], // "Employees/CheckValidityRegisterEmployee", // Method.Get, // queryParams: new Dictionary<string, string> { // { "employeeNo", Input.EmployeeNo.ToString() }, // { "civilId", Input.CivilId.ToString()} // });

      // if (data.StatusCode == 200) // { // if (!data.Data) // { // throw new UserFriendlyException("Invalid Employee"); // } //}else // { // throw new UserFriendlyException("Oracle service has issue ("+data.StatusCode+" - "+(data.Messages.Count > 0 ? data.Messages.FirstOrDefault():"")+")" ); //}

    #endregion

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    You can add malimings@gmail.com to your org. I will test it with this email.

  • User Avatar
    0
    oshabani created

    malimings@gmail.com has been added to our organization

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    I can get the access token but can't get a photo, I think your app is not set properly

    https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-configure-app-access-web-apis#delegated-permission-to-microsoft-graph

  • User Avatar
    0
    oshabani created

    API permission User,Read is already there but still not able to get photo.

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    Retrieving a user's photo using the Microsoft Graph API is currently not supported in Azure AD B2C tenants.

    Are you using it?

  • User Avatar
    0
    oshabani created

    No, it is not B2C tenant.

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    I don't have too many ideas. This is not what I'm good at. : (

  • User Avatar
    0
    oshabani created

    No problem...finally I have resolved the issue.

    Just I have added the the Scope

    options.Scope.Add("User.Read");

    As a favour, if you do not include in support tickets count that will be appreciated. Thanks.

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    Great

Made with ❤️ on ABP v9.1.0-preview. Updated on November 20, 2024, 13:06