SoFunction
Updated on 2025-03-07

Compatible with both JWT authentication and Cookies authentication modes (example details)

In actual use, you may encounter login verification of the aspi interface and view page. Both compatibility is supported.

First enable authentication.

var secrityKey = new SymmetricSecurityKey(Encoding.(Configuration["SecurityKey"]));
            (secrityKey);
            ()
                .AddCookie(option =>    //cookies method                {
                     = "/Login"; 
                })
            .AddJwtBearer(, options =>   //jwt method            {
                 = new TokenValidationParameters
                {
                    ValidateIssuer = true,//Whether to verify Issuer                    ValidateAudience = true,// Whether to verify Audience                    ValidateLifetime = true,//Whether to verify the expiration time                    ClockSkew = (30),
                    ValidateIssuerSigningKey = true,//Whether to verify SecurityKey                    ValidAudience = Configuration["JWTDomain"],//Audience
                    ValidIssuer = Configuration["JWTDomain"],//Issuer
                    IssuerSigningKey = secrityKey//Get SecurityKey                };
            });

Configure method must be added

(); //Authorization  (); //Authentication The authentication method is username and password authentication
            (context =>
            {
                var excludeUrl = new string[] { "/api/login/getinfo", "/api/login/login", "/api/login/modifypwd" };  //Note lowercase                return 
                && ("Login")
                && ("Authorization")
                && !((()));
            }, _app =>
            {
                _app.Use(async (context, next) =>
                {
                     = 401;
                });
            });

On the login page, background code

var uid = ["code"] + "";
var pwd = ["pwd"] + "";
 
var info = _mysql.(m => m.user_code == uid&&==0).FirstOrDefault();
if (info == null)
{
    return new JsonResult(new
    {
        success = false,
        msg = "The user does not exist"
    });
}
if ( != pwd)
        msg = "User password is incorrect"
//Create an identity authenticationvar claims = new List<Claim>() {
            new Claim(,), //User ID            new Claim(,info.user_code)  //User Name        };
var claimsIdentity = new ClaimsIdentity(
    claims, );
//var identity = new ClaimsIdentity(claims, "Login");
//var userPrincipal = new ClaimsPrincipal(identity);
//("MyCookieAuthenticationScheme", userPrincipal, new AuthenticationProperties
//{
//    ExpiresUtc = (30),
//    IsPersistent = true
//}).Wait();
var authProperties = new AuthenticationProperties
    //AllowRefresh = <bool>,
    // Refreshing the authentication session should be allowed.
    ExpiresUtc = (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 (
    ,
    new ClaimsPrincipal(claimsIdentity),
    authProperties);

Controller controller part, login code:

[HttpPost("Login")]
        public async Task<JsonResult> Login(getdata _getdata)
        {
            var userName = _getdata.username;
            var passWord = _getdata.password;
            var info = _mysql.(m => m.user_code == userName &&  == 0).FirstOrDefault();
            if (info == null)
            {
                return new JsonResult(new
                {
                    state = false,
                    code = -1,
                    data = "",
                    msg = "The username does not exist!"
                });
            }
            if (CommonOp.MD5Hash().ToLower() != passWord)
                    code = -2,
                    msg = "The user password is incorrect!"
 
            #region Identity Authentication Processing            var secrityKey = new SymmetricSecurityKey(Encoding.(_config["SecurityKey"]));
            List<Claim> claims = new List<Claim>();
            (new Claim("user_code", info.user_code));
            (new Claim("id", ));
            var creds = new SigningCredentials(secrityKey, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(
                issuer: _config["JWTDomain"],
                audience: _config["JWTDomain"],
                claims: claims,
                expires: (120),
                signingCredentials: creds);
            return new JsonResult(new
                state = true,
                code = 0,
                data = new JwtSecurityTokenHandler().WriteToken(token),
                msg = "Getting token successful"
            });
            #endregion
        }

Note that the authenticated controller part must be added with the following attribute headers before it can take effect.

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

Such a Controller controller is compatible with both modes.

This is the article about the two modes of JWT authentication and Cookies authentication. This is all about this. For more related authentication content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!