|
|
|
using System;
|
|
|
|
using System.ComponentModel.DataAnnotations;
|
|
|
|
using System.Net.Http;
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
using IdentityModel.Client;
|
|
|
|
using IdentityServer4.Models;
|
|
|
|
using Microsoft.AspNetCore.Authorization;
|
|
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
using Microsoft.Extensions.Configuration;
|
|
|
|
using Volo.Abp;
|
|
|
|
using Volo.Abp.Application.Services;
|
|
|
|
|
|
|
|
namespace Win_in.Sfs.Auth.Tokens;
|
|
|
|
|
|
|
|
[Route($"api/token")]
|
|
|
|
public class TokenService : ApplicationService
|
|
|
|
{
|
|
|
|
private readonly IHttpClientFactory _httpClientFactory;
|
|
|
|
private readonly IConfiguration _configuration;
|
|
|
|
|
|
|
|
public TokenService(IHttpClientFactory httpClientFactory, IConfiguration configuration)
|
|
|
|
{
|
|
|
|
this._httpClientFactory = httpClientFactory;
|
|
|
|
this._configuration = configuration;
|
|
|
|
}
|
|
|
|
|
|
|
|
[HttpPost]
|
|
|
|
[AllowAnonymous]
|
|
|
|
public async Task<IActionResult> CreateAsync(LoginModel model)
|
|
|
|
{
|
|
|
|
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);
|
|
|
|
var clientId = _configuration["AuthServer:ClientId"];
|
|
|
|
var clientSecret = _configuration["AuthServer:ClientSecret"];
|
|
|
|
Console.WriteLine($"address:{address},TokenEndpoint:{discovery.TokenEndpoint},clientId:{clientId},clientSecret:{clientSecret}");
|
|
|
|
var result = await _httpClientFactory.CreateClient().RequestPasswordTokenAsync(new PasswordTokenRequest
|
|
|
|
{
|
|
|
|
Address = discovery.TokenEndpoint,
|
|
|
|
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 });
|
|
|
|
}
|
|
|
|
|
|
|
|
[HttpGet("[action]")]
|
|
|
|
[AllowAnonymous]
|
|
|
|
public string Test()
|
|
|
|
{
|
|
|
|
return "Test";
|
|
|
|
}
|
|
|
|
|
|
|
|
[HttpGet("/token/test")]
|
|
|
|
[AllowAnonymous]
|
|
|
|
public string Test1()
|
|
|
|
{
|
|
|
|
return "Test";
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
[Display]
|
|
|
|
public class LoginModel
|
|
|
|
{
|
|
|
|
[Display]
|
|
|
|
[Required]
|
|
|
|
public string UserName { get; set; }
|
|
|
|
|
|
|
|
[Display]
|
|
|
|
[Required]
|
|
|
|
public string Password { get; set; }
|
|
|
|
}
|