当前位置:网站首页>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 | 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() {``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 = ,``// 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,``new
ClaimsPrincipal(claimsIdentity),``authProperties);
|
Controler Controller part , Login code :
| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 | [HttpPost(``"Login"``)]``public
async Task 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 claims =
new
List();``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 .
| 12345 | **[Authorize(AuthenticationSchemes =**
"Bearer,Cookies"``)]``public
class
ControllerCommonBase : ControllerBase``{
}
|
Such a Controler controller , It can be compatible with two modes .
边栏推荐
- Unity performance optimization reading notes - explore performance issues -profiler (2.1)
- 'using an alias column in the where clause in PostgreSQL' - using an alias column in the where clause in PostgreSQL
- vim 出现 Another program may be editing the same file. If this is the case 的解决方法
- Ml and NLP are still developing rapidly in 2021. Deepmind scientists recently summarized 15 bright research directions in the past year. Come and see which direction is suitable for your new pit
- os. Path built-in module
- Snowflake won the 2021 annual database
- [Chongqing Guangdong education] National Open University spring 2019 2727 tax basis reference questions
- [ES6] template string: `string`, a new symbol in es2015
- 8.8.1-PointersOnC-20220214
- TCP slicing and PSH understanding
猜你喜欢
Data communication and network: ch13 Ethernet
2020 Summary - Magic year, magic me
Summary of Shanghai Jiaotong University postgraduate entrance examination module firewall technology
JD home programmers delete databases and run away. Talk about binlog, the killer of MySQL data backup
Detailed explanation of NPM installation and caching mechanism
LVS load balancing cluster deployment - Dr direct routing mode
Star leap plan | new projects are continuously being recruited! MSR Asia MSR Redmond joint research program invites you to apply!
Btrace tells you how to debug online without restarting the JVM
Summary of Shanghai Jiaotong University postgraduate entrance examination module -- cryptography
Ml and NLP are still developing rapidly in 2021. Deepmind scientists recently summarized 15 bright research directions in the past year. Come and see which direction is suitable for your new pit
随机推荐
Properties and methods of OS Library
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 15
[the way of programmer training] - 2 Perfect number calculation
2021-08-09
French Data Protection Agency: using Google Analytics or violating gdpr
CSDN documentation specification
IO stream ----- open
Reptile learning 4 winter vacation series (3)
Complementary knowledge of auto encoder
Awk getting started to proficient series - awk quick start
Login operation (for user name and password)
Review of week 278 of leetcode II
How to use the mongodb ID array to get multiple documents- How to get multiple document using array of MongoDb id?
Reptile learning winter vacation series (2)
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 8
Introduction of network security research direction of Shanghai Jiaotong University
The frost peel off the purple dragon scale, and the xiariba people will talk about database SQL optimization and the principle of indexing (primary / secondary / clustered / non clustered)
Tableau makes data summary after linking the database, and summary exceptions occasionally occur.
Interview question MySQL transaction (TCL) isolation (four characteristics)
It's hard to hear C language? Why don't you take a look at this (V) pointer