adding authorization and validation to injected objects and middleware in the startup class
1. Injecting an object in the Configureservices method
Validation injection services. Addauthentication (opts=>opts. Defaultscheme= Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme). Addcookie (Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme, opt = > {opt. Loginpath = new Microsoft.AspNetCore.Http.PathString ("/login"); opt. Accessdeniedpath= new Microsoft.AspNetCore.Http.PathString ("/home/error"); opt. Logoutpath= new Microsoft.AspNetCore.Http.PathString ("/login"); opt. Cookie.path = "/";} );
2. Adding middleware in the Configure method
Open the Verification middleware app. Useauthentication ();
Authorizing controller and action under special effects
[Authorize (Roles = "admin")]//allow those roles to access [allowanonymous]//allow everyone to access
Login method
[HttpGet ("Login")] [allowanonymous]//allows everyone to access public Iactionresult Login (string returnUrl) {//Failed to verify if (! HttpContext.User.Identity.IsAuthenticated) {viewbag.returnurl = RETURNURL; } return View (); }
Login Implementation Function method
[httppost ("login")][allowanonymous]//allow everyone to access Public iactionresult login (String net_user, string password ,string returnurl) {if (NET_ user == "123" && PassWord == "123") {var claims = New system.security.claims.claim[] {new system.security.claims.claim ( System.Security.Claims.ClaimTypes.Role, "admin"),//user.identity.namenew system.security.claims.claim ( System.Security.Claims.ClaimTypes.Name, "Name"),}; Httpcontext.signinasync ( microsoft.aspnetcore.authentication.cookies.cookieauthenticationdefaults.authenticationscheme,new System.Security.Claims.ClaimsPrincipal (New system.security.claims.claimsidentity (Claims)));return New redirectresult (String. IsNullOrEmpty (RETURNURL) ? "/home/index": RETURNURL);} else {ViewBag.error = "User name or password error"; Return view ();}}
front page
<form method= "POST" action= "Login" class= "Am-form" > <label for= "Email" > Email/username/Phone Number: </label><input type= "text" name= "Net_user" Value= "" ><br><label for= "password" > Login password: </label><input type= "password" Name= "PassWord" value= "" ><input type= "hidden" name= "ReturnUrl" value= "@ Viewbag.returnurl "><br><span style=" color:red "> @ViewBag .error</span><br>< Label for= "Remember-me" ><input id= "Remember-me" type= "checkbox" > Remember password </label>< br /><div class= "AM-CF" ><input type= "Submit" name= " value=" Login Record " class= "AM-BTN&NBSP;AM-BTN-PRIMARY&NBSP;AM-BTN-SM&NBSP;AM-FL" ><input type= "Submit" name= " " value=" Forgot password ^_^? " class=" AM-BTN&NBSP;AM-BTN-DEFAULT&NBSP;AM-BTN-SM&NBSP;AM-FR "></ Div></form>
. NET Core Permissions Authentication