Files
jinko.yikatong/Src/Dlhis.Sys/Identity/Controllers/OAuth2Controller.cs
2024-06-28 11:58:37 +08:00

38 lines
1.4 KiB
C#

using System.Text;
using Dlhis.Sys.Identity.Request;
using Kurisu.AspNetCore.Authentication.Options;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;
namespace Dlhis.Sys.Identity.Controllers;
/// <summary>
/// OAuth2认证
/// </summary>
[Route("api/[controller]")]
[ApiController]
public class OAuth2Controller : ControllerBase
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly IOptions<IdentityServerOptions> _identityServerOption;
public OAuth2Controller(IHttpClientFactory httpClientFactory, IOptions<IdentityServerOptions> identityServerOption)
{
_httpClientFactory = httpClientFactory;
_identityServerOption = identityServerOption;
}
[HttpPost("clientgrant")]
public async Task<object> ClientGrant(ClientGrantRequest request)
{
var authority = _identityServerOption.Value.Authority;
var httpClient = _httpClientFactory.CreateClient();
var content = new StringContent($"grant_type=client_credentials&client_id={request.ClientId}&client_secret={request.ClientSecret}&scope={request.Scope}", Encoding.UTF8, "application/x-www-form-urlencoded");
var response = await httpClient.PostAsync($"{authority}/connect/token", content);
var result = await response.Content.ReadAsStringAsync();
return JObject.Parse(result);
}
}