Files
jinko.yikatong/Src/Dlhis.User/Identity/Controllers/OAuth2Controller.cs

39 lines
1.6 KiB
C#

using System.Text;
using Dlhis.User.Identity.Request;
using Kurisu.AspNetCore.Authentication.Options;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;
namespace Dlhis.User.Identity.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class OAuth2Controller : ControllerBase
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly IOptions<IdentityServerOptions> _identityServerOption;
private readonly IServiceProvider _serviceProvider;
public OAuth2Controller(IHttpClientFactory httpClientFactory, IOptions<IdentityServerOptions> identityServerOption, IServiceProvider serviceProvider)
{
_httpClientFactory = httpClientFactory;
_identityServerOption = identityServerOption;
_serviceProvider = serviceProvider;
}
[HttpPost("clientgrant")]
public async Task<object> ClientGrant(ClientGrantRequest request)
{
var authority = _identityServerOption.Value.Authority;
var httpClient = _httpClientFactory.CreateClient("oauth2");
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);
}
}
}