using System.Text; using Dlhis.Middle.Request; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json.Linq; namespace Dlhis.Middle.Controllers; /// /// OAuth2认证 /// [Route("api/user/[controller]")] [ApiController] public class OAuth2Controller : ControllerBase { private readonly IHttpClientFactory _httpClientFactory; private readonly IConfiguration _configuration; public OAuth2Controller(IHttpClientFactory httpClientFactory, IConfiguration configuration) { _httpClientFactory = httpClientFactory; _configuration = configuration; } [HttpPost("clientgrant")] public async Task ClientGrant(ClientGrantRequest request) { var authority = _configuration.GetSection("Authority").Value; var httpClient = _httpClientFactory.CreateClient(); try { 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}/oauth2/connect/token", content); var result = await response.Content.ReadAsStringAsync(); return JObject.Parse(result); } catch (Exception e) { return new { access_token = "123", expires_in = 36000, token_type = "Bearer", scope = "yikatong" }; } } }