无法从控制台应用程序在 Dot Net Core API 中发送令牌

Unable to send Token in Dot Net Core API from Console App

我是 .Net Core 应用程序的新手,我创建了 .Net Core API 并从控制台应用程序调用这些 APIs,我也能够登录并获取令牌。

现在,当我想为下一次调用传递此令牌时,出现未授权错误。

public void GetEmployeesByToken()
    {
        try
        {
            string str = string.Empty;

            string url = baseUrl + "api/Employees/GetEmployees";

            using (HttpClient webRequest = new HttpClient())
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "Get";
                request.ContentType = "application/json";
                //request.Headers["Authorization"] = "Bearer " + BearerToken;
                webRequest.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",  BearerToken);
                //webRequest.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", BearerToken);
                HttpResponseMessage response = webRequest.GetAsync(url).Result;
                //webRequest.GetAsync().Result;
                
                if (response != null)
                {
                    //str = JsonConvert.DeserializeObject<string>(response);
                }
            }
        }
        catch (Exception ex)
        {
            throw;
        }
    }

我尝试了多种方法,但仍然是同样的问题。

下面是我的控制器

[Authorize(Roles = UserRoles.Admin)]
[Route("api/[controller]")]
[ApiController]
public class EmployeesController : ControllerBase
{
    [HttpGet]
    [Route("GetEmployees")]
    public List<string>GetEmployees()
    {
        return new List<string>() {"Employee01", "Employee02", "Employee03", "Employee04", "Employee05"};
    }

BearerToken 我正在设置响应登录请求。

以下 Startup.cs class 中的代码用于 dot net core API

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddControllers();

        //For Entity Framework
        services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnectionStr")));

        //For Identity
        services.AddIdentity<ApplicationUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();

        //Adding Authentication
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        })

        //Addding Jwt Bearer
        .AddJwtBearer(options =>
        {
            options.SaveToken = true;
            options.RequireHttpsMetadata = false;
            options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidAudience = Configuration["JWT:ValidAudience"],
                ValidIssuer = Configuration["JWT:ValidIssuer"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Secret"]))
            };
        });

        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebAPI_First", Version = "v1" });
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("./v1/swagger.json", "WebAPI_First v1"); //originally "./swagger/v1/swagger.json"
            });
            //app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebAPI_First v1"));
        }

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }

当我能够调用并获取 JWT 令牌时的登录方法

    [HttpPost]
    [Route("Login")]
    public async Task<IActionResult> Login(LoginModel model)
    {
        var user = await _userManager.FindByNameAsync(model.UserName);
        if(user != null && await _userManager.CheckPasswordAsync(user, model.Password))
        {
            var userRoles = await _userManager.GetRolesAsync(user);

            var AuthClaims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            };

            foreach (var userRole in userRoles)
            {
                AuthClaims.Add(new Claim(ClaimTypes.Role, userRole));
            }

            var authSignKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_Configarion["JWT:Secret"]));

            var token = new JwtSecurityToken(
                issuer: _Configarion["JWT:ValidIssuer"],
                audience: _Configarion["JWT:ValidAudience"],
                expires: DateTime.Now.AddHours(3),
                claims: AuthClaims,
                signingCredentials : new SigningCredentials(authSignKey, SecurityAlgorithms.HmacSha256)
                );

            return Ok(new
            {
                token = new JwtSecurityTokenHandler().WriteToken(token),
                expiration = token.ValidTo,
                user = user.UserName
            }); ;
        }

        return Unauthorized();
    }

提前致谢。

试试这个

public async Task<List<string>> GetEmployeesByToken(string token)
{
......
    using HttpClient client = new HttpClient { BaseAddress = new Uri(baseUrl) };
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
    client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
    string uri = "api/Employees/GetEmployees";

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
    
   var response = await client.GetAsync(uri);
    
    if (response.IsSuccessStatusCode)
    {
        var stringData = await response.Content.ReadAsStringAsync();
        var result = JsonConvert.DeserializeObject<List<string>>(stringData);
     return result;
        
    }
return null;
}

如果它仍然不起作用,那么您将必须 post 启动文件和您用来创建令牌的代码。

更新:

尝试在 UseAuthorization

之前添加 app.UseAuthentication()
 app.UseAuthentication();
 app.UseAuthorization();