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.
 
 
 
 
 
 

67 lines
2.4 KiB

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
namespace Win_in.Sfs.Wms.DataExchange.Authenticaitons;
public class TokenService : ITokenService
{
private readonly IConfiguration _configuration;
private readonly AuthenticationOptions _options;
public TokenService(IConfiguration configuration, IOptions<AuthenticationOptions> options)
{
_configuration = configuration;
_options = options.Value;
}
public async Task<BaererToken> GetTokenAsync(string baseUrl)
{
var options = _options;
var token = await GetTokenAsync(baseUrl, options).ConfigureAwait(false);
return token;
}
public async Task<BaererToken> GetTokenAsync(string baseUrl, string username, string password)
{
var options = new AuthenticationOptions()
{
client_id = _options.client_id,
client_secret = _options.client_secret,
grant_type = "password",
username = username,
password = password
};
var token = await GetTokenAsync(baseUrl, options).ConfigureAwait(false);
return token;
}
private static async Task<BaererToken> GetTokenAsync(string baseUrl, AuthenticationOptions options)
{
const string routeString = "connect/token";
var client = new HttpClient();
client.BaseAddress = new Uri(baseUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("client_id",options.client_id),
new KeyValuePair<string, string>("client_secret",options.client_secret),
new KeyValuePair<string, string>("grant_type",options.grant_type),
new KeyValuePair<string, string>("username",options.username),
new KeyValuePair<string, string>("password",options.password),
});
var response = await client.PostAsync(routeString, content).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
var dto = await response.Content.ReadFromJsonAsync<BaererToken>().ConfigureAwait(false);
return dto;
}
}