当前位置:网站首页>asp. Core is compatible with both JWT authentication and cookies authentication
asp. Core is compatible with both JWT authentication and cookies authentication
2022-07-04 12:29:00 【Illusory private school】
Python Wechat ordering applet course video
https://edu.csdn.net/course/detail/36074
Python Actual quantitative transaction financial management system
https://edu.csdn.net/course/detail/35475
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
| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 | varuid = Request.Form[``"code"``] +""``;``varpwd = Request.Form[``"pwd"``] +""``; varinfo = _mysql.users.Where(m => m.user_code == uid&&m.delflag==0).FirstOrDefault();``if(info ==null``)``{``returnnewJsonResult(``new``{``success =false``,``msg =" The user doesn't exist "``});``}``if(info.pwd != pwd)``{``returnnewJsonResult(``new``{``success =false``,``msg =" Incorrect user password "``});``} // Create an authentication ``varclaims =newList() {``newClaim(ClaimTypes.Sid,info.id),// user ID``newClaim(ClaimTypes.Name,info.user_code)// User name ``};``varclaimsIdentity =newClaimsIdentity(``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(); varauthProperties =newAuthenticationProperties``{``//AllowRefresh = ,``// 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 = ,``// The time at which the authentication ticket was issued. //RedirectUri =// The full path or absolute URI to be used as an http// redirect response value.``}; await HttpContext.SignInAsync(``CookieAuthenticationDefaults.AuthenticationScheme,``newClaimsPrincipal(claimsIdentity),``authProperties); |
Controler Controller part , Login code :
| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 | [HttpPost(``"Login"``)]``publicasync Task Login(getdata \_getdata)``{``varuserName = _getdata.username;``varpassWord = _getdata.password;``varinfo = _mysql.users.Where(m => m.user_code == userName && m.delflag == 0).FirstOrDefault();``if(info ==null``)``{``returnnewJsonResult(``new``{``state =false``,``code = -1,``data =""``,``msg =" The username does not exist !"``});``}``if(CommonOp.MD5Hash(info.pwd).ToLower() != passWord)``{``returnnewJsonResult(``new``{``state =false``,``code = -2,``data =""``,``msg =" Incorrect user password !"``});``} #region Identity authentication processing ``varsecrityKey =newSymmetricSecurityKey(Encoding.UTF8.GetBytes(_config[``"SecurityKey"``]));``List claims =newList();``claims.Add(``newClaim(``"user_code"``, info.user_code));``claims.Add(``newClaim(``"id"``, info.id)); varcreds =newSigningCredentials(secrityKey, SecurityAlgorithms.HmacSha256);``vartoken =newJwtSecurityToken(``issuer: _config[``"JWTDomain"``],``audience: _config[``"JWTDomain"``],``claims: claims,``expires: DateTime.Now.AddMinutes(120),``signingCredentials: creds); returnnewJsonResult(``new``{``state =true``,``code = 0,``data =newJwtSecurityTokenHandler().WriteToken(token),``msg =" obtain token success " });``#endregion``} |
Be careful , Authenticated controller part , Add the following attribute header , It will take effect .
| 12345 | **[Authorize(AuthenticationSchemes =**"Bearer,Cookies"``)]``publicclassControllerCommonBase : ControllerBase``{ } |
Such a Controler controller , It can be compatible with two modes .
边栏推荐
- (August 10, 2021) web crawler learning - Chinese University ranking directed crawler
- Exness: positive I win, negative you lose
- Iframe to only show a certain part of the page
- Review of week 278 of leetcode II
- Possible to restore a backup of SQL Server 2014 on SQL Server 2012?
- Method of setting default items in C # ComboBox control code
- Googgle guava ImmutableCollections
- Clion configuration of opencv
- Here, the DDS tutorial you want | first experience of fastdds - source code compilation & Installation & Testing
- 03_ Armv8 instruction set introduction load and store instructions
猜你喜欢

Using terminal connection in different modes of virtual machine
![[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 24](/img/2e/b1f348ee6abaef24b439944acf36d8.jpg)
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 24
![[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 18](/img/1a/94ef8be5c06c2d1c52fc8ce7f03ea7.jpg)
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 18

What if the chat record is gone? How to restore wechat chat records on Apple Mobile

Function parameters (positional parameters, default value parameters, variable parameters, named keyword parameters, keyword parameters)

01. Basics - MySQL overview
![[the way of programmer training] - 2 Perfect number calculation](/img/fd/4bb8560f601daddaa8895f20215be4.jpg)
[the way of programmer training] - 2 Perfect number calculation

Properties and methods of OS Library
![[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 23](/img/72/a80ee7ee7b967b0afa6018070d03c9.jpg)
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 23

MySQL performance optimization index
随机推荐
Exceptions and exception handling
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 23
R语言--readr包读写数据
Dos and path
Bottom Logic -- Mind Map
Review of week 278 of leetcode II
'using an alias column in the where clause in PostgreSQL' - using an alias column in the where clause in PostgreSQL
Games101 Lesson 8 shading 2 Notes
MYCAT middleware installation and use
Pat 1059 prime factors (25 points) prime table
PKCs 5: password based cryptography specification version 2.1 Chinese Translation
MySQL advanced (Advanced) SQL statement
TCP slicing and PSH understanding
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 17
Xshell's ssh server rejected the password, failed to skip publickey authentication, and did not register with the server
13、 C window form technology and basic controls (3)
Exness: positive I win, negative you lose
First knowledge of spark - 7000 words +15 diagrams, and learn the basic knowledge of spark
DDS-YYDS
Method of setting default items in C # ComboBox control code