当前位置:网站首页>asp. Core is compatible with both JWT authentication and cookies authentication

asp. Core is compatible with both JWT authentication and cookies authentication

2022-07-06 03:56:00 To Dao Zhonghe

In practical use , May come across ,aspi Interface verification and view Login verification of the page .asp.core It also supports two compatible . 

First, in the startup.cs Enable Authentication .

 var secrityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["SecurityKey"]));
            services.AddSingleton(secrityKey);
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(option =>    //cookies  The way  { option.LoginPath = "/Login"; }) .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => //jwt  The way  { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true,// Whether the validation Issuer ValidateAudience = true,// Whether the validation Audience ValidateLifetime = true,// Is the failure time verified  ClockSkew = TimeSpan.FromSeconds(30), ValidateIssuerSigningKey = true,// Whether the validation SecurityKey ValidAudience = Configuration["JWTDomain"],//Audience ValidIssuer = Configuration["JWTDomain"],//Issuer IssuerSigningKey = secrityKey// Get SecurityKey  }; });

Configure Method must be added

  app.UseAuthentication(); // to grant authorization 
  app.UseAuthorization(); // authentication   Authentication methods include user name and password authentication 

            app.MapWhen(context => { var excludeUrl = new string[] { "/api/login/getinfo", "/api/login/login", "/api/login/modifypwd" }; // Pay attention to lowercase  return context.Request.Path.HasValue && context.Request.Path.Value.Contains("Login") && context.Request.Headers.ContainsKey("Authorization") && !(excludeUrl.Contains(context.Request.Path.Value.ToLower())); }, _app => { _app.Use(async (context, next) => { context.Response.StatusCode = 401; }); });

 

stay login page , Background code

            var uid = Request.Form["code"] + "";
            var pwd = Request.Form["pwd"] + "";

            var info = _mysql.users.Where(m => m.user_code == uid&&m.delflag==0).FirstOrDefault();
            if (info == null)
            {
                return new JsonResult(new
                {
                    success = false,
                    msg = " The user doesn't exist "
                });
            }
            if (info.pwd != pwd)
            {
                return new JsonResult(new
                {
                    success = false,
                    msg = " Incorrect user password "
                });
            }

            // Create an authentication 
            var claims = new List<Claim>() {
                        new Claim(ClaimTypes.Sid,info.id), // user ID
                        new Claim(ClaimTypes.Name,info.user_code)  // User name 
                    };
            var claimsIdentity = new ClaimsIdentity(
                claims, CookieAuthenticationDefaults.AuthenticationScheme);
            //var identity = new ClaimsIdentity(claims, "Login");
            //var userPrincipal = new ClaimsPrincipal(identity);
            //HttpContext.SignInAsync("MyCookieAuthenticationScheme", userPrincipal, new AuthenticationProperties
            //{
            //    ExpiresUtc = DateTime.UtcNow.AddMinutes(30),
            //    IsPersistent = true
            //}).Wait();

            var authProperties = new AuthenticationProperties
            {
                //AllowRefresh = <bool>,
                // Refreshing the authentication session should be allowed.
                ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(60),
                // The time at which the authentication ticket expires. A 
                // value set here overrides the ExpireTimeSpan option of 
                // CookieAuthenticationOptions set with AddCookie.
                IsPersistent = true,
                // Whether the authentication session is persisted across 
                // multiple requests. When used with cookies, controls
                // whether the cookie's lifetime is absolute (matching the
                // lifetime of the authentication ticket) or session-based.

                //IssuedUtc = <DateTimeOffset>,
                // The time at which the authentication ticket was issued.

                //RedirectUri = <string>
                // The full path or absolute URI to be used as an http 
                // redirect response value.
            };

            await HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(claimsIdentity),
                authProperties);

 Controler Controller part , Login code :

[HttpPost("Login")]
        public async Task<JsonResult> Login(getdata _getdata)
        {
            var userName = _getdata.username;
            var passWord = _getdata.password;
            var info = _mysql.users.Where(m => m.user_code == userName && m.delflag == 0).FirstOrDefault();
            if (info == null)
            {
                return new JsonResult(new
                {
                    state = false,
                    code = -1,
                    data = "",
                    msg = " The username does not exist !"
                });
            }
            if (CommonOp.MD5Hash(info.pwd).ToLower() != passWord)
            {
                return new JsonResult(new
                {
                    state = false,
                    code = -2,
                    data = "",
                    msg = " Incorrect user password !"
                });
            }

            #region  Identity authentication processing 
            var secrityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["SecurityKey"]));
            List<Claim> claims = new List<Claim>();
            claims.Add(new Claim("user_code", info.user_code));
            claims.Add(new Claim("id", info.id));

            var creds = new SigningCredentials(secrityKey, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(
                issuer: _config["JWTDomain"],
                audience: _config["JWTDomain"],
                claims: claims,
                expires: DateTime.Now.AddMinutes(120),
                signingCredentials: creds);

            return new JsonResult(new
            {
                state = true,
                code = 0,
                data = new JwtSecurityTokenHandler().WriteToken(token),
                msg = " obtain token success "

            });
            #endregion
        }

Be careful , Authenticated controller part , Add the following attribute header , It will take effect . 

    [Authorize(AuthenticationSchemes = "Bearer,Cookies")]
    public class ControllerCommonBase : ControllerBase
    {
    
     }    

 

Such a Controler controller , It can be compatible with two modes .

原网站

版权声明
本文为[To Dao Zhonghe]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202132257200666.html