Skip to content

Commit

Permalink
chore: from main
Browse files Browse the repository at this point in the history
  • Loading branch information
wzh425 committed Sep 13, 2024
2 parents df740d4 + dfc0406 commit e3258bc
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Copyright (c) MASA Stack All rights reserved.
// Licensed under the Apache License. See LICENSE.txt in the project root for license information.

namespace Masa.Mc.Contracts.Admin.Infrastructure;

public class TokenGenerater : ITokenGenerater
{
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly HttpClient _httpClient;
private readonly IMasaStackConfig _masaStackConfig;
private const string SCHEME = "Bearer ";

public TokenGenerater(IHttpContextAccessor httpContextAccessor, HttpClient httpClient, IMasaStackConfig masaStackConfig)
{
_httpContextAccessor = httpContextAccessor;
_httpClient = httpClient;
_masaStackConfig = masaStackConfig;
}

public TokenProvider Generater()
{
StringValues authenticationHeaderValue;

if (_httpContextAccessor.HttpContext?.Request.Headers.TryGetValue("Authorization", out authenticationHeaderValue) == true)
{
var accessToken = authenticationHeaderValue.ToString();

if (!string.IsNullOrEmpty(accessToken) && accessToken.StartsWith(SCHEME, StringComparison.OrdinalIgnoreCase))
{
accessToken = accessToken.Substring(SCHEME.Length).Trim();
}

return new TokenProvider { AccessToken = accessToken };
}

if (_httpContextAccessor.HttpContext == null)
{
var request = new ClientCredentialsTokenRequest
{
Address = _masaStackConfig.GetSsoDomain() + "/connect/token",
GrantType = BuildingBlocks.Authentication.OpenIdConnect.Models.Constans.GrantType.CLIENT_CREDENTIALS,
ClientId = _masaStackConfig.GetWebId(MasaStackProject.MC),
Scope = "MasaStack"
};
var tokenResponse = _httpClient.RequestClientCredentialsTokenAsync(request).Result;
return new TokenProvider { AccessToken = tokenResponse.AccessToken };
}

return new TokenProvider();
}
}
1 change: 1 addition & 0 deletions src/Web/Masa.Mc.Web.Admin.Server/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
mcBaseAddress = masaStackConfig.GetMcServiceDomain();
}

builder.Services.AddScoped<ITokenGenerater, TokenGenerater>();
await builder.Services.AddMasaStackComponentsAsync(MasaStackProject.MC, "wwwroot/i18n", authBaseAddress);

builder.Services.AddHttpContextAccessor();
Expand Down

0 comments on commit e3258bc

Please sign in to comment.