zoukankan      html  css  js  c++  java
  • .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
  • 相关阅读:
    yum命令速查
    5分钟理解编译系统
    Nginx(一)安装及启停
    Linux时间命令
    常用七种排序的python实现
    python迭代器、生成器、装饰器
    LeetCode【第217题】Contains Duplicate
    LeetCode【第1题】Two Sum
    python【第二十篇】Django表的多对多、Ajax
    不要问我DO在哪里?
  • 原文地址:https://www.cnblogs.com/xiaoquangege/p/7472346.html
Copyright © 2011-2022 走看看