.net core 2.0 登陆权限验证

首先在Startup的ConfigureServices方法添加一段权限代码

services.AddAuthentication(x=> {
                x.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                x.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            }).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, x =>
                    {
                        //登录地址
                        x.LoginPath = "/Home/Login";
                        //sid
                        x.Cookie.Name = "mycookie";
                        x.Cookie.Path = "/";
                        x.Cookie.HttpOnly = true;
                        x.Cookie.Expiration = new TimeSpan(0, 0, 30);
                        x.ExpireTimeSpan = new TimeSpan(0, 0, 30);
                    });

这里整理下目录。

有个HomeController,首页的Index页面添加[Authorize],需要权限进入

有个Login的action,登录页

添加登录方法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();
        }

添加登录页面

@{
    ViewData["Title"] = "Login";
}

<h2>Login</h2>

<form method="post" action="/home/SignIn">
    用户名<input type="text" name="username" />
    密码<input type="password" name="password" />
    <button type="submit" class="btn">登录</button>
</form>

因为在Startup里面配置了当没权限时进入登录页面  

                        x.LoginPath = "/Home/Login";

此时运行程序,会跳转到登录页面

输入用户名密码登陆,登录验证成功后就可以跳转到Index了。

再添加个退出

public async Task<IActionResult> SignOut()
        {
            if (HttpContext.User.Identity.IsAuthenticated)
                await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

            return RedirectToAction("Login");
        } 

在页面上可以通过这段代码判断是否登录

Context.User.Identity.IsAuthenticated

 

posted @ 2017-09-04 10:13  小胖脸  阅读(1662)  评论(0编辑  收藏  举报