You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

101 lines
3.1 KiB

using System;
2 years ago
using System.ComponentModel.DataAnnotations;
using System.Net.Http;
using System.Threading.Tasks;
using IdentityModel.Client;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
2 years ago
using Volo.Abp.Application.Services;
namespace Win_in.Sfs.Auth.Tokens;
[Route($"api/token")]
public class TokenService : ApplicationService
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger<TokenService> _logger;
2 years ago
private readonly IConfiguration _configuration;
2 years ago
public TokenService(IHttpClientFactory httpClientFactory, IConfiguration configuration, ILogger<TokenService> logger)
2 years ago
{
this._httpClientFactory = httpClientFactory;
this._configuration = configuration;
this._logger = logger;
2 years ago
}
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> CreateAsync(LoginModel model)
2 years ago
{
var address = _configuration["AuthServer:Authority"];
var request = new DiscoveryDocumentRequest
{
Address = address,
Policy = new DiscoveryPolicy { RequireHttps = false }
};
var discovery = await _httpClientFactory.CreateClient().GetDiscoveryDocumentAsync(request).ConfigureAwait(false);
2 years ago
var clientId = _configuration["AuthServer:ClientId"];
var clientSecret = _configuration["AuthServer:ClientSecret"];
this._logger.LogInformation($"address:{address},TokenEndpoint:{discovery.TokenEndpoint},clientId:{clientId},clientSecret:{clientSecret}");
2 years ago
var result = await _httpClientFactory.CreateClient().RequestPasswordTokenAsync(new PasswordTokenRequest
{
Address = $"{address.TrimEnd('/')}/connect/token",
2 years ago
GrantType = "password",
ClientId = clientId,
ClientSecret = clientSecret,
UserName = model.UserName,
Password = model.Password
}).ConfigureAwait(false);
Console.WriteLine($"Result:${(result.IsError ? result.ErrorDescription : result.AccessToken)}");
//if (result.RefreshToken == null)
//{
// throw new UserFriendlyException("用户名或密码错误");
//}
return new JsonResult(new
{
result.TokenType,
result.AccessToken,
result.ExpiresIn,
result.RefreshToken,
result.Scope,
result.HttpStatusCode,
result.Error,
result.HttpErrorReason,
result.ErrorDescription,
result.ErrorType,
result.Exception?.Message,
Exception = result.Exception?.ToString()
});
2 years ago
}
2 years ago
[HttpGet("[action]")]
[AllowAnonymous]
public string Test()
{
return "Test";
}
[HttpGet("/token/test")]
[AllowAnonymous]
public string Test1()
{
return "Test";
}
2 years ago
}
[Display]
public class LoginModel
{
[Display]
[Required]
public string UserName { get; set; }
[Display]
[Required]
public string Password { get; set; }
}