Home > Software engineering >  How to authenticate microsoft graph api?
How to authenticate microsoft graph api?

Time:10-29

Am trying to configure the graphseviceclient to get the outlook calendar events of other user in the same organization.Here am using the below code in program.cs,

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Identity.Web;
using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"))
        .EnableTokenAcquisitionToCallDownstreamApi()
            .AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"))
            .AddInMemoryTokenCaches();

builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo
    {
        Title = "OutlookEvents",
        Version = "v1"
    });

    c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
    {
        Type = SecuritySchemeType.OAuth2,
        Flows = new OpenApiOAuthFlows()
        {
            Implicit = new OpenApiOAuthFlow()
            {
                AuthorizationUrl = new Uri("xxx"),
                TokenUrl = new Uri("xxx"),
                Scopes = new Dictionary<string, string>
            {
               {
                  "api://xxx/xxx",
                  "xxx"
               }
             
            }
            }
    }
    });

    c.AddSecurityRequirement(new OpenApiSecurityRequirement() {
    {
        new OpenApiSecurityScheme
        {
            Reference = new OpenApiReference
            {
                    Type = ReferenceType.SecurityScheme,
                        Id = "oauth2"
            },
                Scheme = "oauth2",
                Name = "oauth2",
                In = ParameterLocation.Header
        },
        new List < string > ()
    }});

});

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "OutlookEvents v1");

        c.OAuthClientId("xxx");
        c.OAuthClientSecret("xxx");

        c.OAuthUseBasicAuthenticationWithAccessCodeGrant();
    });
}

app.UseHttpsRedirection();

app.UseAuthentication();

app.UseAuthorization();

app.MapControllers();

app.Run();

and my appssettings.json looks like this,

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "xxx.com",
    "TenantId": "xxx",
    "ClientId": "xxx",
    "Scopes": "access_as_user",
    "CallbackPath": "/signin-oidc",
    "ClientSecret": "Client secret from app-registration. Check user secrets/azure portal.",
    "ClientCertificates": []
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "MicrosoftGraph": {
    "BaseUrl": "https://graph.microsoft.com/v1.0",
    "Scopes": [
      "user.read",
      "Calendars.Read",
      "Calendars.ReadWrite",
      "User.Read.All",
      "User.ReadWrite.All",
      "Application.Read.All",
      "Profile"
    ]
  }
}


But still am not getting the other user details,may be there is a problem with generation of token.

I need to get valid token with proper scopes.

CodePudding user response:

this is the enter image description here

enter image description here

Then use this code in your controller:

using Microsoft.Graph;
using Azure.Identity;

var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "tenant_name.onmicrosoft.com";
var clientId = "aad_app_id";
var clientSecret = "client_secret";
var clientSecretCredential = new ClientSecretCredential(
                tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var events = await graphClient.Users["[email protected]"].Calendar.Events.Request().GetAsync();
  • Related