Getting Exception when trying to get User Authentication EMailMethods

JS Arya 46 Reputation points
2022-09-02T09:47:10.277+00:00

I am trying to update User EmailAuthenticationMethod in AD. While calling the Get method, It gives exception. I have highlighted the line on which it is throwing exception. If I deploy and run it for the first time, it runs. After that is starts to throw this exception

Exception I am getting :

022-09-02 09:23:28.678 +00:00 [Information] Call Entry: ## LOG IN EXCEPTION {"error":{"code":"accessDenied","message":"Request Authorization failed","target":null,"details":null,"innerError":{"code":null,"message":"Request Authorization failed","target":null,"details":null,"innerError":null,"throwSite":null,"clientRequestId":null,"additionalData":{"date":{"valueKind":3},"request-id":{"valueKind":3},"client-request-id":{"valueKind":3}},"throwSite":null,"clientRequestId":"a5481f0c-0695-4b06-bbee-a58f668878e8","additionalData":null},"responseHeaders":[{"key":"Transfer-Encoding","value":["chunked"]},{"key":"Vary","value":["Accept-Encoding"]},{"key":"Strict-Transport-Security","value":["max-age=31536000"]},{"key":"request-id","value":["a5481f0c-0695-4b06-bbee-a58f668878e8"]},{"key":"client-request-id","value":["a5481f0c-0695-4b06-bbee-a58f668878e8"]},{"key":"x-ms-ags-diagnostic","value":["{\"ServerInfo\":{\"DataCenter\":\"East US\",\"Slice\":\"E\",\"Ring\":\"5\",\"ScaleUnit\":\"001\",\"RoleInstance\":\"MN1PEPF00002F1E\"}}"]},{"key":"Date","value":["Fri, 02 Sep 2022 09:23:28 GMT"]}],"statusCode":403,"rawResponseBody":"{\"error\":{\"code\":\"accessDenied\",\"message\":\"Request Authorization failed\",\"innerError\":{\"message\":\"Request Authorization failed\",\"date\":\"2022-09-02T09:23:28\",\"request-id\":\"a5481f0c-0695-4b06-bbee-a58f668878e8\",\"client-request-id\":\"a5481f0c-0695-4b06-bbee-a58f668878e8\"}}","stackTrace":" at Microsoft.Graph.HttpProvider.SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)\n at Microsoft.Graph.BaseRequest.SendRequestAsync(Object serializableObject, CancellationToken cancellationToken, HttpCompletionOption completionOption)\n at Microsoft.Graph.BaseRequest.SendAsync[T](Object serializableObject, CancellationToken cancellationToken, HttpCompletionOption completionOption)\n at Microsoft.Graph.AuthenticationEmailMethodsCollectionRequest.GetAsync(CancellationToken cancellationToken)\n at Auth.Services.AzureADB2CGraphService.UpdateEmailAuthenticationMethod(Guid tenantId, UserEmailAuthenticationPostRequest postRequest, ILoggerService loggerService, IConfiguration _configuration) in /src/AuthService/Services/AzureADB2CGraphService.cs:line 762","message":"Code: accessDenied\nMessage: Request Authorization failed\nInner error:\n\tMessage: Request Authorization failed\nAdditionalData:\n\tdate: 2022-09-02T09:23:28\n\trequest-id: a5481f0c-0695-4b06-bbee-a58f668878e8\n\tclient-request-id: a5481f0c-0695-4b06-bbee-a58f668878e8\nClientRequestId: a5481f0c-0695-4b06-bbee-a58f668878e8\n","data":{},"innerException":null,"helpLink":null,"source":"Microsoft.Graph.Core","hResult":-2146233088}

try  
            {                 
               var scopes = new[] { "Directory.AccessAsUser.All", "UserAuthenticationMethod.ReadWrite.All" };  

               B2cCredentials b2cCredentials = BlobHelper.GetB2CCredentialsFromBlob(_configuration, tenantId);  

               var userName = $"%$$%$%$";  
               var password = "$%$%$$";  

               var options = new TokenCredentialOptions  
               {  
                   AuthorityHost = AzureAuthorityHosts.AzurePublicCloud                     
               };  

               var userNamePasswordCredential = new UsernamePasswordCredential(  
                                                       userName,  
                                                       password,  
                                                       b2cCredentials.B2cTenantId.ToString(),  
                                                       b2cCredentials.ClientId.ToString(),  
                                                       options);  


                var _graphClient = new GraphServiceClient(userNamePasswordCredential, scopes);  


               if (_graphClient != null)  
               {                
                    **var m = await _graphClient.Users[postRequest.UserId.ToString()]  
                    .Authentication.EmailMethods.Request().GetAsync();**  

                    if(m.Count > 0)  
                    {  
                        await _graphClient.Users[postRequest.UserId.ToString()]  
                        .Authentication.EmailMethods["0"]  
                        .Request()  
                        .PutAsync(new Microsoft.Graph.EmailAuthenticationMethod  
                        {  
                            EmailAddress = postRequest.Email  
                        });  
                    }  
                    else  
                    {  
                        await  _graphClient.Users[postRequest.UserId.ToString()]  
                        .Authentication.EmailMethods  
                        .Request()  
                        .AddAsync(new Microsoft.Graph.EmailAuthenticationMethod  
                        {  
                            EmailAddress = postRequest.Email  
                        });  
                    }  

               }                                  
            }      
            catch(Exception ex)  
            {           
               return ex.Message;  
            }     
Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
10,521 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Zehui Yao_MSFT 5,826 Reputation points
    2022-09-05T05:50:42.573+00:00

    Hi @JS Arya , According to the documentation, in addition to the corresponding permissions, this endpoint also requires your user to be a specific role, you can try to set the role for the user in AD.portal and retry this endpoint. Hope can help you, I wish you all the best.

    237703-untitled.png


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    2 people found this answer helpful.