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 .

asp.core Compatible with JWT Authentication and Cookies More articles about two authentication modes

  1. In the third quarter :Windows Platform deployment Asp.Net Core application ( be based on IIS and Windows There are two modes of service )

    One . brief introduction Two . The file system is published to IIS 3、 ... and . Web Deploy publish to IIS Four . FTP Release to IIS 5、 ... and . Windows Publish in the form of service ! do         person : Yaopengfei( Yao Pengfei ) Blog address ...

  2. asp.net in TextBox There are only two simplest ways to enter numbers

    as follows TextBox <asp:textboxonkeypress="isnum()"id="TextBox1"runat="server&quo ...

  3. Validation of an integer Double turn int Two ways of writing

    Double  turn int 1) I've been using force transfer before Double num = Double.parseDouble(object.toString());   int n = (int)num;   i ...

  4. ASP.NET Core Use JWT Build a distributed stateless authentication system

    Why use Jwt lately , Mobile development is gaining momentum , All kinds of school competitions need mobile phones APP Let's make it , therefore , As a write back end , It's necessary to improve on the previous one based on Session It's a new way of identity authentication , For the following reasons : Mobile terminal ...

  5. ASP.NET Core series :JWT Identity Authentication

    1. JWT summary JSON Web Token(JWT) It is a popular cross domain authentication solution . JWT Official website :https://jwt.io JWT The implementation of is to store user information on the client , The server does not save . ...

  6. ASP.NET Core WebApi be based on JWT Implement interface authorization verification

    One .ASP.Net Core WebApi JWT Course Introduction We know ,http Protocol itself is a stateless protocol , This means that if the user provides a user name and password to our application for user authentication , So the next time you ask , Users have to ...

  7. ASP.NET Core 2.1 JWT token ( One ) - Simple books

    original text :ASP.NET Core 2.1 JWT token ( One ) - Simple books JwtBearer Certification is a standard , General purpose , Stateless , Language independent authentication .Bearer Validation belongs to HTTP Protocol standard verification . Such as ...

  8. How to use the ASP.NET Core In the integration JWT authentication ?

    Antecedents feed :ASP.NET Core Use JWT Build a distributed stateless authentication system Article super long warning (1 More than ten thousand words ), Students who don't want to see the whole implementation process can jump to the end to view the results or install the related software with one click nuget package From last month ...

  9. ASP.NET Core 2.1 JWT Token Use ( Two ) - Simple books

    original text :ASP.NET Core 2.1 JWT Token Use ( Two ) - Simple books Continued above ,https://www.jianshu.com/p/c5f9ea3b4b65 ASP.NET Core 2. ...

  10. .Net Core Official JWT Authorization verification

    What is? JWT? JSON Web token (JWT) It's an open standard (RFC 7519), It defines a compact and self-contained way , Used to securely transmit information between parties as JSON object . Because this information is digitally signed , So it can be tested ...

Random recommendation

  1. Spring The first one to learn hello world Program

    Spring It's an open source framework ,Spring Is in the 2003 A lightweight that emerged in 1997 Java Development framework , from Rod Johnson His works are in Expert One-On-One J2EE Development a ...

  2. oracle Roll forward and roll back

    Roll forward (Rollforward): When the database is shut down , A lot of submitted data is not written to disk , Data recovery , Replay log content on file , Restore the file to the state when the database was closed . Roll back (Rollback): When the database is shut down , ...

  3. php,blade grammar

    Print array <?php print_r($agreement);die?> <?= ?><?php echo ?><?php printf();die;?> ...

  4. Talking about Bootstrap—— The navigation bar starts

    Not much to say , Go straight to the code . <div class="navbar navbar-default"> <div class="container"&g ...

  5. solve HttpClient simulation http Of get After the request , appear 403 error

    resolvent : URI uri = builder.build(); // establish http GET request HttpGet httpGet = new HttpGet(uri); httpGet.setHead ...

  6. Wechat public platform development 5 .net

    Every time we interact on wechat , All need to be used. access_token, But this value is limited by time , however access_token, It will be often used in the advanced functions in the future , So I have to explain what I have explained access_token ...

  7. C# Import file date format (dd/MM/yyyy)

      Recently, the data import date of the project has become like this This is because it is converted to American time American time format :MM/dd/yyyy British time format :dd/MM/yyyy     To avoid this problem in import, you need to set excel Document cell style settings ...

  8. C The use and writing of language header file

    C In language .h Documents and I have known each other for a long time , Its use is not very complicated , But it was after months of “ Don't understand, ” period , Years of “ Have a superficial knowledge of ” It was only in this period that I gradually realized his true colors . The reason , One of the reasons is that I am slow and eager to learn without understanding , But another ...

  9. 【Centos7】Delete virtual bridge

    Previously,Stop service which controls virtual bridges. sudo systemctl stop libvirtd.service #System ...

  10. Big data processing framework Strom:Flume+Kafka+Storm Integrate

    Environmental Science virtual machine :VMware 10 Linux edition :CentOS-6.5-x86_64 client :Xshell4 FTP:Xftp4 jdk1.8 storm-0.9 apache-flume-1.6.0 ...