Большинство примеров веб-API asp.net CORE, которые я видел, используют «промежуточное программное обеспечение» аутентификации, которое добавляется в файл запуска, и кажется, что код выглядит очень элегантно.Однако я никоим образом не аутентифицирую пользователя, вместо этого я использую Azure AD App-Only для доступа к API Graph и SharePoint REST.И я не могу найти достойных примеров, показывающих, как использовать «промежуточное ПО» без входа в систему пользователя.
Единственный пример, который я смог найти, был этот , и ниже я нашел то, что мне нужно.Моя методика работает, но, кажется, немного новичок, и мне интересно, есть ли способ заставить аутентификацию App-Only работать в собственном наборе инструментов аутентификации / идентификации CORE?
public class ExclusionRequestsController : Controller
{
private readonly IConfiguration Config;
private string token;
public ExclusionRequestsController(IConfiguration config)
{
Config = config;
this.Init();
}
private async void Init()
{
string certFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Directory.GetCurrentDirectory() + Config["BIS232AppSettings:CertificatePath"]);
X509Certificate2 certificate = new X509Certificate2(certFile, Config["BIS232AppSettings:CertificatePassword"], X509KeyStorageFlags.MachineKeySet);
AuthenticationContext authenticationContext = new AuthenticationContext(String.Format("{0}{1}/oauth2/authorize",
Config["BIS232AppSettings:Instance"],
Config["BIS232AppSettings:TenantID"]), false);
ClientAssertionCertificate cac = new ClientAssertionCertificate(Config["BIS232AppSettings:ClientID"], certificate);
var authenticationResult = await authenticationContext.AcquireTokenAsync(Config["BIS232AppSettings:GraphResourceId"], cac);
this.token = authenticationResult.AccessToken;
}
// GET: api/ExclusionRequests/Get
[HttpGet]
[ActionName("Get")]
public async Task<ActionResult<dynamic>> Get()
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", this.token);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string requestUrl = Config["BIS232AppSettings:GraphResourceId"] + "v1.0/sites/" + Config["BIS232AppSettings:Hostname"] + ","
+ Config["BIS232AppSettings:SPSiteID"] + "," + Config["BIS232AppSettings:SPWebID"] + "/lists/"
+ Config["BIS232AppSettings:ERList"] + "/items?expand=Fields&$top=50";
HttpResponseMessage result = await client.GetAsync(requestUrl);
if (result.IsSuccessStatusCode)
{
string json = await result.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject(json);
}
else
return new NoContentResult();
}
}