Asp .Net Core 2.0 登陆受权以及多用户登陆

用户登陆是一个很是常见的应用场景 .net core 2.0 的登陆方式发生了点变化,应该是属因而良性的变化,变得更方便,更容易扩展。后端

配置

打开项目中的Startup.cs文件,找到ConfigureServices方法,咱们一般在这个方法里面作依赖注入的相关配置。添加以下代码:app

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>
            {
                o.LoginPath = new PathString("/Account/Login");
                o.AccessDeniedPath = new PathString("/Error/Forbidden");
            });
}

这段代码的大概意思就是,添加受权支持,并添加使用Cookie的方式,配置登陆页面和没有权限时的跳转页面。async

再找到Configure方法,添加 app.UseAuthentication(),使用受权:ide

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseAuthentication();
}

这样基本的配置就完成了。post

登陆

添加一个Controller,如AccountController,再添加一个Action,如 Login,所配置的路由,要与上面的配置对应,否则跳转登陆时会跳错页面。ui

用户提交用户名和密码,登陆代码大体以下:this

[HttpPost]
public async Task <IActionResult> Login(string userName, string password, string ReturnUrl)
{
    var user = _userService.Login(userName, password);
    if (user != null)
    {

        user.AuthenticationType = CookieAuthenticationDefaults.AuthenticationScheme;
        var identity = new ClaimsIdentity(user);
        identity.AddClaim(new Claim(ClaimTypes.Name, user.UserID));
        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));

        if (ReturnUrl.IsNullOrEmpty())
        {
            return RedirectToAction("Index", "Dashboard");
        }
        return Redirect(ReturnUrl);
    }
    ViewBag.Errormessage = "登陆失败,用户名密码不正确";
    return View();
}

这里要注意的是 AuthenticationType 所设置的Scheme必定要与前面的配置同样,这样对应的登陆受权才会生效。url

使用登陆身份

登陆的目录,就是但愿有些页面或者资源只有登陆之后才可访问。使用AuthorizeAttribute来作限制。在须要作限制的Controller上加上[Authorize]特性来作限制。.net

[Authorize]
public class ThemeController
{
}

这样这个Controller下的全部的Action都必须要登陆后才可访问。若是但愿其中某些Action能够不用登陆也可访问,能够添加例外:code

[AllowAnonymous]
public ActionResult Index()
{
    return View();
}

到这里一个最基础的登陆就完成了。

在Web项目中,一般会遇到一个问题,后端管理员和前台用户。这两个用户都是可登陆的,在 .net core 2.0,这个将很容易实现。

多用户登陆

添加一个登陆方案(Scheme)

CookieAuthenticationDefaults.AuthenticationScheme,这是系统已经定义好的一个默认的登陆方案,添加一个新的来实现一个不一样的身份登陆。代码以下:

public class CustomerAuthorizeAttribute : AuthorizeAttribute
{
    public const string CustomerAuthenticationScheme = "CustomerAuthenticationScheme";
    public CustomerAuthorizeAttribute()
    {
        this.AuthenticationSchemes = CustomerAuthenticationScheme;
    }
}

添加使用这个新的方案,在Startup.cs文件下:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>
            {
                o.LoginPath = new PathString("/Account/Login");
                o.AccessDeniedPath = new PathString("/Error/Forbidden");
            })
            .AddCookie(CustomerAuthorizeAttribute.CustomerAuthenticationScheme, option =>
            {
                option.LoginPath = new PathString("/Account/Signin");
                option.AccessDeniedPath = new PathString("/Error/Forbidden");
            });
}

添加新的登陆方案,并配置一个新的登陆页面,登陆的方法和刚才是同样,只是AuthenticationType使用了新的方案。

[HttpPost]
public async Task <IActionResult> Login(string userName, string password, string ReturnUrl)
{
    var user = _userService.Login(userName, password);
    if (user != null)
    {

        user.AuthenticationType = CustomerAuthorizeAttribute.CustomerAuthenticationScheme;
        var identity = new ClaimsIdentity(user);
        identity.AddClaim(new Claim(ClaimTypes.Name, user.UserID));
        await HttpContext.SignInAsync(CustomerAuthorizeAttribute.CustomerAuthenticationScheme, new ClaimsPrincipal(identity));

        if (ReturnUrl.IsNullOrEmpty())
        {
            return RedirectToAction("Index", "Dashboard");
        }
        return Redirect(ReturnUrl);
    }
    ViewBag.Errormessage = "登陆失败,用户名密码不正确";
    return View();
}

验证登陆状态

使用方法和以前的差很少,换成新的CustomerAuthorizeAttribute就好了:

[CustomerAuthorize]
public class CustomerController
{
}

CustomerAuthorizeAttribute这个类,不是必需的,只是为了方便使用而写,其实彻底能够只定义一个新的方案(Scheme)就好了。

谁才是HttpContext.User?

登陆了多个用户,那么谁才是HttpContext.User呢?若是你的Controller或者Action上有使用AuthorizeAttribute,那这个Attribute使用的登陆方案是哪一个,则这个HttpContext.User对应的就是那个方案的登陆用户。若是没有使用,则AddAuthentication()方法默认指它的方案(Scheme)所登陆的用户,就是这个HttpContext.User了。

如何获取对应方案的登陆用户呢?使用HttpContext.AuthenticateAsync

var auth = await HttpContext.AuthenticateAsync(CustomerAuthorizeAttribute.CustomerAuthenticationScheme);
if (auth.Succeeded)
{
    auth.Principal.Identity...
}

退出登陆

这个就简单了,指定方案退出就能够了。

public async Task Logout(string returnurl)
{
    await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
    return Redirect(returnurl ?? "~/");
}

原文地址:http://www.zkea.net/codesnippet/detail/post-60 

相关文章
相关标签/搜索