[英]How to enable multiple authentication in ASP.NET Core 3.1?
在我的 aspnet core 3.1 项目中,我使用 jwt 进行身份验证。 问题是我也在使用 azure 客户端来获取 vm 大小名称列表,它也使用承载令牌。 现在测试我使用 azure 中的 AllowAnonymous 和 Bearer 一切正常,但我需要双重身份验证,一个是经过身份验证的用户的默认设置,一个是 azure 的默认设置。
我的 azure 助手 class 看起来像:
public static async Task<List<string>> GetAzureVmSizeList(string clientId, string clientSecret, string tenantId, string subscriptionId, string location)
{
var instanceIds = new List<string>();
var vmSizes = await VirtualMachineSizes(clientId, clientSecret, tenantId, subscriptionId, location);
foreach (var vmSize in vmSizes.Where(x => x.NumberOfCores >= 2 && x.MemoryInMB >= 2048)) {
instanceIds.Add(vmSize.Name);
}
return instanceIds;
}
private static async Task<IEnumerable<VirtualMachineSize>> VirtualMachineSizes(string clientId, string clientSecret, string tenantId,
string subscriptionId, string location)
{
AzureCredentials credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(
clientId,
clientSecret,
tenantId,
AzureEnvironment.AzureGlobalCloud);
RestClient restClient = RestClient.Configure()
.WithEnvironment(AzureEnvironment.AzureGlobalCloud)
.WithCredentials(credentials)
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Build();
ComputeManagementClient client = new ComputeManagementClient(restClient.Credentials)
{
SubscriptionId = subscriptionId
};
var vmSizes = await client.VirtualMachineSizes.ListAsync(location);
return vmSizes;
}
// GET Azure token 如果可能的话我需要在里面使用这个 token get azure vm size list
public static async Task<string> GetToken(string azureUrl, string clientId, string
clientSecret)
{
var url = $"https://login.microsoftonline.com/{azureUrl}/oauth2/v2.0/token";
var credentials = new Dictionary<string, string>
{
{"client_id", clientId},
{"client_secret", clientSecret},
{"scope", "https://management.azure.com/.default"},
{"grant_type", "client_credentials"}
};
var client = new HttpClient();
var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = new
FormUrlEncodedContent(credentials) };
var res = await client.SendAsync(req);
var result = res.Content.ReadAsStringAsync().Result;
var tokenObject = JObject.Parse(result);
var token = tokenObject["access_token"];
return token.ToString();
}
// 我的 controller 我正在使用这个助手:
[AllowAnonymous] // it should be [Authorize]
[HttpGet("azurevm/{projectName}")]
public async Task<IActionResult> GetAzureList(string projectName)
{
var credentials = await _context.Projects
.Join(_context.CloudCredentials, project => project.CloudCredentialId, cloud
=> cloud.Id,
(project, cloud) => new {project, cloud})
.Where(@t => @t.cloud.IsAzure
&& @t.project.Name == projectName).Select(x =>
new
{
azureLocation = x.cloud.AzureLocation,
azureClientId = x.cloud.AzureClientId,
azureClientSecret = x.cloud.AzureClientSecret,
azureSubscriptionId = x.cloud.AzureSubscriptionId,
azureTenantId = x.cloud.AzureTenantId,
azureUrl = x.cloud.AzureUrl
}).FirstOrDefaultAsync();
if (credentials == null)
{
return BadRequest($"{projectName} is not Azure based");
}
var result = await AzureHelper.GetAzureVmSizeList(credentials.azureClientId,
credentials.azureClientSecret,
credentials.azureTenantId,
credentials.azureSubscriptionId,
credentials.azureLocation);
if (result == null)
{
return BadRequest($"{projectName} is not Azure based");
}
return Ok(result);
}
// 我的启动 class jwt 配置(也许可以扩展它并添加多个jwt)
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey =
new SymmetricSecurityKey(
Encoding.ASCII.GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
ValidateIssuer = false,
ValidateAudience = false
};
});
要管理虚拟机,您不应代表用户使用授权。 因此,在那之后,您应该为您的用户获得一项全局授权,并为您的应用程序获得 Azure 门户的一项授权。 我建议您使用 Microsoft.Azure.Management.ResourceManager package 来获取虚拟机。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.