亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

asp.core?同時(shí)兼容JWT身份驗(yàn)證和Cookies?身份驗(yàn)證兩種模式(示例詳解)

 更新時(shí)間:2022年02月14日 08:17:01   作者:至道中和  
這篇文章主要介紹了asp.core?同時(shí)兼容JWT身份驗(yàn)證和Cookies?身份驗(yàn)證兩種模式,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

在實(shí)際使用中,可能會遇到,aspi接口驗(yàn)證和view頁面的登錄驗(yàn)證情況。asp.core 同樣支持兩種兼容。

首先在startup.cs 啟用身份驗(yàn)證。

var secrityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["SecurityKey"]));
            services.AddSingleton(secrityKey);
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(option =>    //cookies 方式
                {
                    option.LoginPath = "/Login"; 
                })
            .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>   //jwt 方式
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,//是否驗(yàn)證Issuer
                    ValidateAudience = true,//是否驗(yàn)證Audience
                    ValidateLifetime = true,//是否驗(yàn)證失效時(shí)間
                    ClockSkew = TimeSpan.FromSeconds(30),
                    ValidateIssuerSigningKey = true,//是否驗(yàn)證SecurityKey
                    ValidAudience = Configuration["JWTDomain"],//Audience
                    ValidIssuer = Configuration["JWTDomain"],//Issuer
                    IssuerSigningKey = secrityKey//拿到SecurityKey
                };
            });

Configure 方法中須加入

app.UseAuthentication(); //授權(quán)
  app.UseAuthorization(); //認(rèn)證 認(rèn)證方式有用戶名密碼認(rèn)證

            app.MapWhen(context =>
            {
                var excludeUrl = new string[] { "/api/login/getinfo", "/api/login/login", "/api/login/modifypwd" };  //注意小寫
                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;
                });
            });

在login頁面,后臺代碼

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 = "用戶不存在"
    });
}
if (info.pwd != pwd)
        msg = "用戶密碼不正確"
//創(chuàng)建一個(gè)身份認(rèn)證
var claims = new List<Claim>() {
            new Claim(ClaimTypes.Sid,info.id), //用戶ID
            new Claim(ClaimTypes.Name,info.user_code)  //用戶名稱
        };
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控制器部分,登錄代碼:

[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 = "用戶名不存在!"
                });
            }
            if (CommonOp.MD5Hash(info.pwd).ToLower() != passWord)
                    code = -2,
                    msg = "用戶密碼不正確!"
 
            #region 身份認(rèn)證處理
            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 = "獲取token成功"
            });
            #endregion
        }

注意, 受身份驗(yàn)證的控制器部分,要加入如下屬性頭,才可以生效。

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

這樣一個(gè)Controler 控制器,能夠兼容兩種模式啦。

到此這篇關(guān)于asp.core 同時(shí)兼容JWT身份驗(yàn)證和Cookies 身份驗(yàn)證兩種模式的文章就介紹到這了,更多相關(guān)asp.core 身份驗(yàn)證內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • ASP.NET Core利用Jaeger實(shí)現(xiàn)分布式追蹤詳解

    ASP.NET Core利用Jaeger實(shí)現(xiàn)分布式追蹤詳解

    這篇文章主要給大家介紹了關(guān)于ASP.NET Core利用Jaeger實(shí)現(xiàn)分布式追蹤的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用ASP.NET Core具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04
  • 詳解ASP.NET Core 中的多語言支持(Localization)

    詳解ASP.NET Core 中的多語言支持(Localization)

    本篇文章主要介紹了ASP.NET Core 中的多語言支持(Localization) ,具有一定的參考價(jià)值,有興趣的可以了解一下
    2017-08-08
  • 使用Aspose.Cells實(shí)現(xiàn)導(dǎo)入導(dǎo)出

    使用Aspose.Cells實(shí)現(xiàn)導(dǎo)入導(dǎo)出

    這篇文章主要為大家詳細(xì)介紹了如何使用Aspose.Cells實(shí)現(xiàn)導(dǎo)入導(dǎo)出,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-12-12
  • .Net中的集合排序可以這么玩你知道嗎

    .Net中的集合排序可以這么玩你知道嗎

    集合為處理大量數(shù)據(jù)時(shí)所用到一種容器類。簡單講就是數(shù)據(jù)結(jié)構(gòu)算法的具體平臺上的實(shí)現(xiàn)。下面這篇文章主要給大家介紹了關(guān)于.Net中集合排序的一些你可能不知道的用法,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下。
    2018-04-04
  • ASP.NET之Response.Cookies.Remove 無法刪除COOKIE的原因

    ASP.NET之Response.Cookies.Remove 無法刪除COOKIE的原因

    在web開發(fā)中Cookie是必不可少的,.NET自然也有一個(gè)強(qiáng)大的Cookie操作類,我們用起來也非常方便,不過在使用中我們會發(fā)現(xiàn)一個(gè)坑爹的事情Response.Cookies.Remove刪除不了Cookie。
    2013-06-06
  • java 單例模式(餓漢模式與懶漢模式)

    java 單例模式(餓漢模式與懶漢模式)

    這篇文章主要介紹了java 單例模式(餓漢模式與懶漢模式)的相關(guān)資料,希望通過本文大家能掌握這部分內(nèi)容,需要的朋友可以參考下
    2017-09-09
  • Bin 和 App_Code 文件夾介紹

    Bin 和 App_Code 文件夾介紹

    Bin 和 App_Code 文件夾介紹...
    2007-04-04
  • 微軟發(fā)布的Data Access Application Block的使用代碼

    微軟發(fā)布的Data Access Application Block的使用代碼

    微軟發(fā)布的Data Access Application Block的使用代碼...
    2007-04-04
  • .NET Core使用FluentEmail發(fā)送郵件的示例代碼

    .NET Core使用FluentEmail發(fā)送郵件的示例代碼

    這篇文章主要介紹了.NET Core使用FluentEmail發(fā)送郵件的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-10-10
  • ASP.NETCore6開啟文件服務(wù)允許通過url訪問附件的操作方法

    ASP.NETCore6開啟文件服務(wù)允許通過url訪問附件的操作方法

    最近在做一個(gè)工作臺的文件上傳下載功能,主要想實(shí)現(xiàn)上傳圖片之后,可以通過url直接訪問,由于url直接訪問文件不安全,所以需要手動開啟文件服務(wù),這篇文章主要介紹了ASP.NETCore6開啟文件服務(wù)允許通過url訪問附件,需要的朋友可以參考下
    2023-11-11

最新評論