Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在ASP.NET Core 3.1中启用多重身份验证?_C#_Azure_Asp.net Core_Jwt - Fatal编程技术网

C# 如何在ASP.NET Core 3.1中启用多重身份验证?

C# 如何在ASP.NET Core 3.1中启用多重身份验证?,c#,azure,asp.net-core,jwt,C#,Azure,Asp.net Core,Jwt,在我的ASPNETCore3.1项目中,我使用jwt进行身份验证。问题是我还使用azure客户端来获取vm大小的名称列表,并且它还使用了承载令牌。就目前的测试而言,我使用来自azure的AllowAnonymous和Bear,一切正常,但我需要双重身份验证,一个是默认的身份验证用户,一个是azure 我的azure helper类看起来像: public static async Task<List<string>> GetAzureVmSizeList

在我的ASPNETCore3.1项目中,我使用jwt进行身份验证。问题是我还使用azure客户端来获取vm大小的名称列表,并且它还使用了承载令牌。就目前的测试而言,我使用来自azure的AllowAnonymous和Bear,一切正常,但我需要双重身份验证,一个是默认的身份验证用户,一个是azure

我的azure helper类看起来像:

        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;
        }

要管理虚拟机,您不应该代表用户使用授权。因此,在此之后,您应该为您的用户拥有一个全局授权,为您的应用程序拥有一个Azure门户授权。我建议您使用Microsoft.Azure.Management.ResourceManager包来获取虚拟机

实际上我已经在使用**Microsoft.Azure.Management.ResourceManager.Fluent;Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;Microsoft.Azure.Management.ResourceManager.Fluent.Core**所以不要使用JWT令牌。准备以下凭据:var credentials=new AzureCredentialsFactory.fromServicePrincipalServicePrincipalCredentials.ClientId、ServicePrincipalCredentials.ClientSecret、ServicePrincipalCredentials.TenantId、,AzureEnvironment.AzureGlobalCloud;然后将其传递给身份验证方法Azure.Configure.AuthenticateCcredentials Azure的凭据可以存储在应用程序设置中。我建议您在Azure应用程序服务中使用密钥库或应用程序设置。不要直接将机密存储在appsettings.json中。
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();                                                                                    
}                    
        [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);
        }      
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
                    };
                });