Asp .Net Core 2.0 登录授权以及前后台多用户登录

摘要:
用户登录是一种非常常见的应用场景。netcore 2.0的登录模式略有改变。这应该是一个良性的变化,变得更方便,更容易扩展=null){user.AuthenticationType=CookieAuthenticationDefaults.AuthentitationScheme;varidentity=newClaimsIdentity;identity.AddClaim;awaitHttpContext.SignInAsync;if{returnRedirectToAction;}returnRedirect;}ViewBag。ErrorMessage=“登录失败,用户名和密码不正确”;returnView();}请注意,AuthenticationType设置的Scheme必须与之前的配置相同,以便相应的登录授权生效。两个用户都可以登录,这将很容易实现。netcore 2.0.多用户登录添加登录方案CookieAuthenticationDefaults AuthentiationScheme是系统定义的默认登录方案,它添加了一个新方案以实现不同的身份登录。

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

配置

打开项目中的Startup.cs文件,找到ConfigureServices方法,我们通常在这个方法里面做依赖注入的相关配置。添加如下代码:

复制代码
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的方式,配置登录页面和没有权限时的跳转页面。

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

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

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

登录

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

用户提交用户名和密码,登录代码大致如下:

复制代码
[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一定要与前面的配置一样,这样对应的登录授权才会生效。

使用登录身份

登录的目录,就是希望有些页面或者资源只有登录以后才可访问。使用AuthorizeAttribute来做限制。在需要做限制的Controller上加上[Authorize]特性来做限制。

[Authorize]
public class ThemeController
{
}

这样这个Controller下的所有的Action都必需要登录后才可访问。如果希望其中某些Action可以不用登录也可访问,可以添加例外:

[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了。

Asp .Net Core 2.0 登录授权以及前后台多用户登录第11张

如何获取对应方案的登录用户呢?使用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

免责声明:文章转载自《Asp .Net Core 2.0 登录授权以及前后台多用户登录》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇C# 通过ServiceStack 操作Redis——ZSet类型的使用及示例MarkDown基本操作下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

随便看看

MySQL的安装、配置文件和初始化

MySQL基于源代码的安装本文以MySQL5.1.73+Centos6.5作为安装演示,其他版本安装方法大同小异。首先下载MySQL5.1.73的源代码包。比如MySQL5.1.73,安装在目录/usr/local/myql-5.1.73,然后做一个软连接/usr/local/mysql指向真正的版本路径。进行到此,MySQL库以及可执行程序已经编译出来,可...

微信分享回调

在我们的项目中,我曾经判断用户是否通过微信分享了文章或内容。在确认用户通过微信分享了文章或内容后,我向用户添加了相应的分数。...

com.aliyun.openservices.shade.com.alibaba.fastjson.JSONException: exepct '[', but {, pos 1, line 1, column 2

错误报告的原因:您放置了一个非List对象,但希望从packagetest中取出List对象;导入java.text。SimpleDateFormat;导入java.util。阵列列表;导入java.util。日期导入java.util。列表importcom.alibaba.fastjson。JSON;导入com.alibaba.fastj...

css动画延迟好像有点怪

项目需要使用动画Css。自定义时,会发现设置动画延迟和动画持续时间的总时间不正确,这将导致动画丢失。例如,bounceInLeft动画从左侧出现,然后抖动。当初始动画延迟为0时,动画持续时间为1s,动画已完成,但如果设置该值,动画延迟为1s且动画持续时间是2s,则动画未完成。具体的动画是从左侧出现,然后在1s延迟后直接到达终点,但没有抖动。然后我用w3c写了...

一起学习Avalonia(十二)

可以使用数据模板自定义和显示数据模板模板。文档中介绍了Avalonia的基本数据模板。PublicstringFirstName{get;set;}publicstringLastName{get;set;}扩展使用文档最后介绍了扩展使用,包括2个模型。Student和Teacher。在MainWindowViewModel中创建属性Content。此属性是...

electron用默认浏览器打开链接的3种实现方式

在使用Electron开发桌面程序的过程中,我们可能经常需要使Electron程序中包含的链接在单击后直接调用系统的默认浏览器打开。仔细阅读文档后,我们都知道它的核心原理是调用系统的默认浏览器,通过Electron shell模块中的openExternal方法打开链接。然而,它的实现有不同的方法,彻底接管和选择性接管。介绍第3章中的有效方法。以上三种方法都...