2

这是图像明显的问题。

我在 api 中的登录功能

        public async Task<object> Login([FromBody] LoginDto model)
        {
            var user = _context.Users.FirstOrDefault(x => x.Email == model.Email || x.UserName == model.Email);
            var result = await _signInManager.PasswordSignInAsync(user.UserName, model.Password, model.RememberMe, false);
            var IsAuthenticate = User.Identity.IsAuthenticated;
            await _signInManager.SignInAsync(user, model.RememberMe);
            if (result.Succeeded)
            {
                var appUser = _userManager.Users.SingleOrDefault(r => r.Email == model.Email);
                return await GenerateJwtToken(model.Email, appUser);
            }

            return BadRequest("INVALID_LOGIN_ATTEMPT");
        }

我在 mvc 中使用使用 api _client.LoginAsync() 的登录函数是使用 api 进行登录的静态函数

    public async Task<IActionResult> Login(LoginDto model, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;
        if (ModelState.IsValid)
        {
            try
            {
                await _client.LoginAsync<LoginDto>(new Uri(_appSettings.WebApiBaseUrl + "Account/Login"), model);
                ApplicationManager.SetMessageToUser("تم تسجيل الدخول بمجاح");
                await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, false);
                return Redirect("/" + returnUrl);
            }
            catch
            {

            }
        }
        ApplicationManager.SetMessageToUser("تأكد من اسم المستخدم وكلمة المرور");

        // If we got this far, something failed, redisplay form
        return View(model);
    }

_client.LoginAsync() 是使用 api 进行登录的函数

public async Task<string> LoginAsync<T>(Uri requestUrl, T content)
        {
            addHeaders();
            var response = await _httpClient.PostAsync(requestUrl.ToString(), CreateHttpContent<T>(content));
            string st = response.Content.ReadAsStringAsync().Result;

            response.EnsureSuccessStatusCode();
            var data = await response.Content.ReadAsStringAsync();
            return (string)data;
        }

我的服务配置

public void ConfigureServices(IServiceCollection services)
{
    services.AddSession(options => {
        options.IdleTimeout = TimeSpan.FromMinutes(60);
    });
    services.Configure<AppSettings>(Configuration.GetSection("AppSettings")); 
    services.AddDbContext<ApplicationDbContext>(opt =>
       opt.UseSqlServer("Data Source=.;Initial Catalog=ECommerceWebDb;Integrated Security=True"));

    services.AddIdentity<IdentityUser, IdentityRole>(options =>
    {
        options.Password.RequireNonAlphanumeric = false;
        options.Password.RequiredLength = 8;
        options.User.RequireUniqueEmail = true;
    })
       .AddEntityFrameworkStores<ApplicationDbContext>()
       .AddDefaultTokenProviders();

    services.AddControllers();
    services.AddCors();
    services.AddMvc();
    services.AddControllersWithViews();
    services.AddRazorPages();
    var appSettingsSection = Configuration.GetSection("AppSettings");
    services.Configure<AppSettings>(appSettingsSection);

    // configure jwt authentication
    var appSettings = appSettingsSection.Get<AppSettings>();
    var key = Encoding.ASCII.GetBytes(appSettings.Secret);
    services.AddAuthentication(x =>
    {
        x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

    })
    .AddJwtBearer(x =>
    {
        x.RequireHttpsMetadata = false;
        x.SaveToken = true;

        x.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(key),
            ValidateIssuer = false,
            ValidateAudience = false
        };
    });
}

// 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.UseCors();


    app.UseAuthentication();

    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
         name: "default",
         pattern: "{controller=Home}/{action=Index}/{id?}");

        endpoints.MapAreaControllerRoute(
         name: "areas", "areas",
         pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
        endpoints.MapRazorPages();
    });
}

我对这个错误真的很复杂我认为这一切如果你想帮助我更多请告诉我。

4

2 回答 2

1

SignIn 为将来的请求保留给定的信息,它不会HttpContext.User在当前 的请求上设置。因此User.Identity.IsAuthenticated在后续请求中将是 true

参考

https://github.com/aspnet/Security/issues/1318

https://docs.microsoft.com/en-us/archive/msdn-magazine/2017/september/cutting-edge-cookies-claims-and-authentication-in-asp-net-core#foundation-of-aspnet-验证

在 ASP.NET 中,用户身份验证涉及到 cookie 的使用。如果用户没有携带有效的身份验证 cookie,则任何尝试访问私人页面的用户都会被重定向到登录页面。登录页面在验证提供的凭据后,会发出 cookie,然后该 cookie 会与来自该用户的任何后续请求一起通过同一浏览器传送,直到过期。这与您可能从过去的 ASP.NET 版本中了解的基本工作流相同。在 ASP.NET Core 中,只是因为中间件不同,运行环境配置不同,所以看起来不同。

于 2020-01-01T08:27:37.817 回答
0

我找到了解决办法

如果你遇到同样的问题,JWT 不支持 cookie 和 token,所以你必须删除

x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

services.AddAuthentication

    services.AddAuthentication(x =>
    {

    })
    .AddJwtBearer(x =>
    {
        x.RequireHttpsMetadata = false;
        x.SaveToken = true;

        x.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(key),
            ValidateIssuer = false,
            ValidateAudience = false
        };
    });

当您需要通过令牌授权任何操作时,您可以使用此属性

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

任何动作。

当您需要通过 cookie 授权任何操作时,您需要添加

[Authorize]
于 2020-01-05T03:47:33.737 回答