我正在使用cookie身份验证为我的MVC应用程序和MVC web api应用程序设置身份验证 . 这是我的Mvc应用程序的startup.cs代码 .

public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
    {
        var secretKey = "esssecret_secretkey!@#$";
        var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));

        var tokenValidationParameters = new TokenValidationParameters
        {
            // The signing key must match!
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = signingKey,

            // Validate the JWT Issuer (iss) claim
            ValidateIssuer = true,
            ValidIssuer = "essIssue",

            // Validate the JWT Audience (aud) claim
            ValidateAudience = true,
            ValidAudience = "essAudi",

            // Validate the token expiry
            ValidateLifetime = true,

            // If you want to allow a certain amount of clock drift, set that here:
            ClockSkew = TimeSpan.Zero
        };

        loadServerLink();

        app.UseCookieAuthentication(options =>
        {

            options.AutomaticAuthenticate = true;
            options.AutomaticChallenge = true;
            options.AuthenticationScheme = "CookieAuthHRMS";              

            options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
            options.SlidingExpiration = true;

            options.LoginPath = new Microsoft.AspNet.Http.PathString("/Account/Login");
            options.LogoutPath = new Microsoft.AspNet.Http.PathString("/Account/Logout");
            options.AccessDeniedPath = new Microsoft.AspNet.Http.PathString("/Account/AccessDenied");

        });

        app.UseIISPlatformHandler();

        app.UseMvc(ConfigureRoutes);

        app.UseStaticFiles();

        app.Run(async (context) =>
        {
            await context.Response.WriteAsync("Hello World -----!");
        });            
    }

这是我在控制器中的登录代码 . 那真是太好了 .

private async Task SignInAsync(ApplicationUser user,bool isPersistent){await HttpContext.Authentication.SignOutAsync(“CookieAuthHRMS”);

var Cidentity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, user.UserName), }, DefaultAuthenticationTypes.ApplicationCookie, ClaimTypes.Name, ClaimTypes.Role);

        List<Claim> userClaims = new List<Claim>
        {               
            new Claim("userId",user.UserId.ToString()),
            new Claim("EmployeeId",user.EmployeeID),
            new Claim(ClaimTypes.Name, user.UserName),                
        };

        ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(userClaims,DefaultAuthenticationTypes.ApplicationCookie));


        await HttpContext.Authentication.SignInAsync("CookieAuthHRMS", principal);

    }

在app.UseCookieAuthentication()中添加两行代码后 . 我的登录名不会重定向到主页/索引 .

options.CookieName = "access_token";
  options.TicketDataFormat = new CustomJwtDataFormat(SecurityAlgorithms.HMAC_SHA256, tokenValidationParameters);

这是我的控制器代码:

[HttpPost]
    [AllowAnonymous]
    public async Task<IActionResult> Login(LoginViewModel lgvm)
    {
        if (ModelState.IsValid)
        {
            var user = await _userManager.FindAsync(lgvm.UserName, lgvm.Password);
            string result;
            if(user!= null)
            {                    
                await SignInAsync(user, lgvm.RememberMe); //Just stop here and not continue to next line
                return RedirectToAction("Index", "Home");
            }
        }

        return RedirectToAction("AccessDenied","Account");
    }

好的,我的错误是等待“等待SignInAsync(user,lgvm.RememberMe);”而不是继续“返回RedirectToAction(”索引“,”主页“);” .

这是制作自定义jwt数据格式的参考链接:https://stormpath.com/blog/token-authentication-asp-net-core

最好的Rgds,青蛙