Ма c с использованием asp. net .core 3.1 с использованием бритвенных страниц - Один арендатор (не распространен)
NuGet - Microsoft.AspNetCore.Authentication (2.2.0) - Microsoft.AspNetCore .Authentication.JwtBearer (3.1.3) - Microsoft.AspNetCore.Authentication.OpenIdConnect (3.1.3) - Microsoft.Graph (3.3.0) - Microsoft.Identity.Client (4.11.0) (
public GraphAuthProvider(IConfiguration configuration)
{
var azureOptions = new AzureAdOptions();
configuration.Bind("AzureAd", azureOptions);
// More info about MSAL Client Applications: https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/Client-Applications
_app = ConfidentialClientApplicationBuilder.Create(azureOptions.ClientId)
// J.Vogel - Removes "common" issue .WithAuthority(AzureCloudInstance.AzurePublic, AadAuthorityAudience.AzureAdAndPersonalMicrosoftAccount)
// J.Vogel
.WithAuthority(azureOptions.Instance + azureOptions.TenantId + "/")
.WithRedirectUri(azureOptions.BaseUrl + azureOptions.CallbackPath)
.WithClientSecret(azureOptions.ClientSecret)
.Build();
Authority = _app.Authority;
_scopes = azureOptions.GraphScopes.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
}
// Gets an access token. First tries to get the access token from the token cache.
// Using password (secret) to authenticate. Production apps should use a certificate.
public async Task<string> 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."
});
}
}
public async Task<AuthenticationResult> GetUserAccessTokenByAuthorizationCode(string authorizationCode)
{
return await _app.AcquireTokenByAuthorizationCode(_scopes, authorizationCode).ExecuteAsync();
}
}
Я наконец получил это на работу (после недели борьбы). Я могу подтвердить подлинность и увидеть свой профиль, наконец .
var user = await graphClient.Users[email].Request().GetAsync();
Однако , оба из них вызовут исключение с «HttpStatusCode = Forbidden». Вздох, я просто пытаюсь получить список моих команд Microsoft.
var joinedTeams = await graphClient.Users[email].JoinedTeams.Request().GetAsync();
var joinedTeams = await graphClient.Me.JoinedTeams.Request().GetAsync();
Вот мои настройки приложения. json
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "mycompany.onmicrosoft.com", <= mycompany is replaced with my actual company
"CallbackPath": "/signin-oidc",
"BaseUrl": "https://localhost:5001",
"TenantId": "b56591e5-6490-456e-b21d-40500f93e44c",
"ClientId": "932e2b08-99df-471f-9e5d-8d55945c9679",
"ClientSecret": "xxxx", <= Removed from my post
"GraphResourceId": "https://graph.microsoft.com/",
"GraphScopes": "User.Read User.ReadBasic.All Mail.Send Team.ReadBasic.All"
}
Однако «graphClient.Me.JoinedTeams» отлично работает через Microsoft Graph Explorer (https://developer.microsoft.com/en-us/graph/graph-explorer/preview).
Чего мне здесь не хватает ?
Спасибо, Джейсон