Model view controller 使用令牌WebAPI验证MVC应用程序

Model view controller 使用令牌WebAPI验证MVC应用程序,model-view-controller,jwt,webapi,Model View Controller,Jwt,Webapi,我已经编写了一个使用Jwt令牌进行身份验证的基本WebAPI。当我使用Postman进行测试API调用时,我成功地获得了一个令牌。但是,我一直在让我的MVC应用程序使用令牌进行身份验证 这是API的控制器- [HttpPost] [Route("login")] public async Task<IActionResult> Login([FromBody] LoginModel model) { var user = await userM

我已经编写了一个使用Jwt令牌进行身份验证的基本WebAPI。当我使用Postman进行测试API调用时,我成功地获得了一个令牌。但是,我一直在让我的MVC应用程序使用令牌进行身份验证

这是API的控制器-

[HttpPost]
    [Route("login")]
    public async Task<IActionResult> Login([FromBody] LoginModel model)
    {
        var user = await userManager.FindByNameAsync(model.Username);
        if (user != null && await userManager.CheckPasswordAsync(user, model.Password))
        {

            var authClaims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };

            var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YVBy0OLlMQG6VVVp1OH7Xzyr7gHuw1qvUC5dcGt3SBM="));

            var token = new JwtSecurityToken(
                issuer: "https://localhost:44350",
                audience: "https://localhost:44350",
                expires: DateTime.Now.AddHours(3),
                claims: authClaims,
                signingCredentials: new Microsoft.IdentityModel.Tokens.SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)
                );

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

您应该在
startup.cs
中添加身份验证服务并使用身份验证中间件:

services.AddAuthentication(option =>
{
    option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(option =>
    {
        option.RequireHttpsMetadata = false;
        option.SaveToken = true;
        option.TokenValidationParameters = new TokenValidationParameters
        {
            RequireExpirationTime = true,
            ValidateLifetime = true,
            ValidIssuer = "Some Issuer",
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidAudience = "Some Audience",
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Security Key")),
            ValidateIssuerSigningKey = true,
        };
});

同时添加
app.UseAuthentication()
startup.cs中的
Configure
方法,这是在WebAPI项目中还是在MVC项目中?它已经存在于WebAPI中,我已经将上述内容添加到MVC中(更改了颁发者、受众和安全密钥以匹配WebAPI one)。HttpContext.User.Identity仍然为null。我觉得错误在MVC登录控制器中,它没有设置HttpContext.User.Identity…@dynmatt它是一个WebAPI2项目,但通常没有区别。请提供有关发送jwt令牌、
startup.cs
以及检查令牌验证的位置的更多详细信息。我已将WebAPI和MVC应用程序的startup.cs添加到原始帖子中。这就是我真正拥有的所有代码,登录API生成令牌,MVC Actionresult调用API并成功获取令牌。只是MVC应用程序似乎没有真正登录到身份?
[HttpPost]
    public async Task<ActionResult> Index(LoginModel login)
    {
        string url = BaseUrl + "api/authenticate/login";

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(url);

            var postTask = client.PostAsJsonAsync<LoginModel>("login", login);
            postTask.Wait();

            var result = postTask.Result;
            if (result.IsSuccessStatusCode)
            {
                var user = HttpContext.User.Identity as ClaimsIdentity;

                var tokenDetails = JsonConvert.DeserializeObject<Dictionary<string, string>>(result.Content.ReadAsStringAsync().Result);

                var claims = new Claim[]
                {
                    new Claim(JwtRegisteredClaimNames.Sub, login.Username, "string"),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim(JwtRegisteredClaimNames.Iat, DateTime.Now.Ticks.ToString(), ClaimValueTypes.Integer64)
                };

                user.AddClaims(claims);

                return RedirectToAction("Index", "Home", null);
            }
        }

        ModelState.AddModelError(string.Empty, "Server error");

        return View(login);
    }
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
    }

    // 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();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthorization();



        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}
services.AddAuthentication(option =>
{
    option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(option =>
    {
        option.RequireHttpsMetadata = false;
        option.SaveToken = true;
        option.TokenValidationParameters = new TokenValidationParameters
        {
            RequireExpirationTime = true,
            ValidateLifetime = true,
            ValidIssuer = "Some Issuer",
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidAudience = "Some Audience",
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Security Key")),
            ValidateIssuerSigningKey = true,
        };
});