First, add a permission code to the startup Configureservices method
Services. Addauthentication (x=> { x.defaultauthenticatescheme = Cookieauthenticationdefaults.authenticationscheme; X.defaultchallengescheme = cookieauthenticationdefaults.authenticationscheme; X.defaultsigninscheme = cookieauthenticationdefaults.authenticationscheme; }). Addcookie (cookieauthenticationdefaults.authenticationscheme, x + = { //login address X.loginpath = "/ Home/login ";//sid x.cookie.name =" MyCookie "; x.cookie.path ="/"; x.cookie.httponly = True; X.cooki E.expiration = new TimeSpan (0, 0, +); X.expiretimespan = new TimeSpan (0, 0, +);});
Sort the directory here.
There is a HomeController, the index page of the homepage add [authorize], need permission to enter
There's a login action, login page
Add Login Method Signin
Public async task<iactionresult> SignIn (Loginviewmodel model) { if (modelstate.isvalid) { var claims = new list<claim>(); Claims. ADD (New Claim (Claimtypes.name, model. UserName)); var identity = new Claimsidentity (claims, "login"); var principal = new ClaimsPrincipal (identity); await Httpcontext.signinasync ( Cookieauthenticationdefaults.authenticationscheme, principal); If (principal. identity.isauthenticated) return redirecttoaction ("Index");} return View ();}
Add Login Page
@{ viewdata["Title"] = "Login";} User name <input type= "text" Name= " Username "/> password <input type=" password "name=" password "/> <button type=" Submit "class=" BTN " > Login </button></form>
Because it is configured in startup to enter the login page when there is no permission
X.loginpath = "/home/login";
Run the program at this time, will jump to the login page
Enter the user name password login, login verification success can jump to index.
Add an Exit again
Public Async Task<iactionresult> signout () { if ( HttpContext.User.Identity.IsAuthenticated) await Httpcontext.signoutasync ( Cookieauthenticationdefaults.authenticationscheme); return Redirecttoaction ("Login");
On the page, you can use this code to determine whether to log in
Context.User.Identity.IsAuthenticated
. NET Core 2.0 login permission Verification