core身份认证

Leo_wlCnBlogs Leo_wlCnBlogs     2022-08-11     703

关键词:

Core中实现一个基础的身份认证

注:本文提到的代码示例下载地址> How to achieve a basic authorization in ASP.NET Core

如何在ASP.NET Core中实现一个基础的身份认证

ASP.NET终于可以跨平台了,但是不是我们常用的ASP.NET, 而是叫一个ASP.NET Core的新平台,他可以跨Windows, Linux, OS X等平台来部署你的web应用程序,你可以理解为,这个框架就是ASP.NET的下一个版本,相对于传统ASP.NET程序,它还是有一些不同的地方的,比如很多类库在这两个平台之间是不通用的。

 

今天首先我们在ASP.NET Core中来实现一个基础的身份认证,既登陆功能。

 

前期准备:

1.推荐使用 VS 2015 Update3 作为你的IDE,下载地址:www.visualstudio.com

2.你需要安装.NET Core的运行环境以及开发工具,这里提供VS版:www.microsoft.com/net/core

 

创建项目:

在VS中新建项目,项目类型选择ASP.NET Core Web Application (.NET Core), 输入项目名称为TestBasicAuthor。

接下来选择 Web Application, 右侧身份认证选择:No Authentication

 

打开Startup.cs

在ConfigureServices方法中加入如下代码:

services.AddAuthorization(); 

在Configure方法中加入如下代码:

复制代码
app.UseCookieAuthentication(new CookieAuthenticationOptions 
{ 
    AuthenticationScheme = "Cookie", 
    LoginPath = new PathString("/Account/Login"), 
    AccessDeniedPath = new PathString("/Account/Forbidden"), 
    AutomaticAuthenticate = true, 
    AutomaticChallenge = true 
}); 
复制代码

完整的代码应该是这样:

复制代码
public void ConfigureServices(IServiceCollection services) 
{ 
    services.AddMvc(); 
 
    services.AddAuthorization(); 
} 
 
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
{ 
    app.UseCookieAuthentication(new CookieAuthenticationOptions 
    { 
        AuthenticationScheme = "Cookie", 
        LoginPath = new PathString("/Account/Login"), 
        AccessDeniedPath = new PathString("/Account/Forbidden"), 
        AutomaticAuthenticate = true, 
        AutomaticChallenge = true 
    }); 
 
    app.UseMvc(routes => 
    { 
        routes.MapRoute( 
             name: "default", 
             template: "{controller=Home}/{action=Index}/{id?}"); 
    }); 
}
复制代码

你或许会发现贴进去的代码是报错的,这是因为还没有引入对应的包,进入报错的这一行,点击灯泡,加载对应的包就可以了。

在项目下创建一个文件夹命名为Model,并向里面添加一个类User.cs

代码应该是这样

public class User
{
    public string UserName { get; set; }
    public string Password { get; set; }
}

 

创建一个控制器,取名为:AccountController.cs

在类中贴入如下代码:

复制代码
[HttpGet] 
public IActionResult Login() 
{ 
    return View(); 
} 
 
[HttpPost] 
public async Task<IActionResult> Login(User userFromFore) 
{ 
    var userFromStorage = TestUserStorage.UserList 
        .FirstOrDefault(m => m.UserName == userFromFore.UserName && m.Password == userFromFore.Password); 
 
    if (userFromStorage != null) 
    { 
        //you can add all of ClaimTypes in this collection 
        var claims = new List<Claim>() 
        { 
            new Claim(ClaimTypes.Name,userFromStorage.UserName) 
            //,new Claim(ClaimTypes.Email,"emailaccount@microsoft.com")  
        }; 
 
        //init the identity instances 
        var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "SuperSecureLogin")); 
 
        //signin 
        await HttpContext.Authentication.SignInAsync("Cookie", userPrincipal, new AuthenticationProperties 
        { 
            ExpiresUtc = DateTime.UtcNow.AddMinutes(20), 
            IsPersistent = false, 
            AllowRefresh = false 
        }); 
 
        return RedirectToAction("Index", "Home"); 
    } 
    else 
    { 
        ViewBag.ErrMsg = "UserName or Password is invalid"; 
 
        return View(); 
    } 
} 
 
public async Task<IActionResult> Logout() 
{ 
    await HttpContext.Authentication.SignOutAsync("Cookie"); 
 
    return RedirectToAction("Index", "Home"); 
} 
复制代码

相同的文件里让我们来添加一个模拟用户存储的类

复制代码
//for simple, I'm not using the database to store the user data, just using a static class to replace it.
public static class TestUserStorage
{
    public static List<User> UserList { get; set; } = new List<User>() {
        new User { UserName = "User1",Password = "112233"}
    };
}
复制代码

接下来修复好各种引用错误。

完整的代码应该是这样

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using TestBasicAuthor.Model;
using System.Security.Claims;
using Microsoft.AspNetCore.Http.Authentication;

// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace TestBasicAuthor.Controllers
{
    public class AccountController : Controller
    {
        [HttpGet]
        public IActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Login(User userFromFore)
        {
            var userFromStorage = TestUserStorage.UserList
                .FirstOrDefault(m => m.UserName == userFromFore.UserName && m.Password == userFromFore.Password);

            if (userFromStorage != null)
            {
                //you can add all of ClaimTypes in this collection 
                var claims = new List<Claim>()
                {
                    new Claim(ClaimTypes.Name,userFromStorage.UserName) 
                    //,new Claim(ClaimTypes.Email,"emailaccount@microsoft.com")  
                };

                //init the identity instances 
                var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "SuperSecureLogin"));

                //signin 
                await HttpContext.Authentication.SignInAsync("Cookie", userPrincipal, new AuthenticationProperties
                {
                    ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
                    IsPersistent = false,
                    AllowRefresh = false
                });

                return RedirectToAction("Index", "Home");
            }
            else
            {
                ViewBag.ErrMsg = "UserName or Password is invalid";

                return View();
            }
        }

        public async Task<IActionResult> Logout()
        {
            await HttpContext.Authentication.SignOutAsync("Cookie");

            return RedirectToAction("Index", "Home");
        }
    }

    //for simple, I'm not using the database to store the user data, just using a static class to replace it.
    public static class TestUserStorage
    {
        public static List<User> UserList { get; set; } = new List<User>() {
        new User { UserName = "User1",Password = "112233"}
    };
    }
}
复制代码

在Views文件夹中创建一个Account文件夹,在Account文件夹中创建一个名位index.cshtml的View文件。

贴入如下代码:

复制代码
@model TestBasicAuthor.Model.User


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    @using (Html.BeginForm())
    {
        <table>
            <tr>
                <td></td>
                <td>@ViewBag.ErrMsg</td>
            </tr>
            <tr>
                <td>UserName</td>
                <td>@Html.TextBoxFor(m => m.UserName)</td>
            </tr>
            <tr>
                <td>Password</td>
                <td>@Html.PasswordFor(m => m.Password)</td>
            </tr>
            <tr>
                <td></td>
                <td><button>Login</button></td>
            </tr>
        </table>
    }
</body>
</html>
复制代码

打开HomeController.cs

添加一个Action, AuthPage.

复制代码
[Authorize]
[HttpGet]
public IActionResult AuthPage()
{
    return View();
}
复制代码

在Views/Home下添加一个视图,名为AuthPage.cshtml

复制代码
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <h1>Auth page</h1>

    <p>if you are not authorized, you can't visit this page.</p>
</body>
</html>
复制代码

到此,一个基础的身份认证就完成了,核心登陆方法如下:

复制代码
await HttpContext.Authentication.SignInAsync("Cookie", userPrincipal, new AuthenticationProperties
{
    ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
    IsPersistent = false,
    AllowRefresh = false
});
复制代码

启用验证如下:

复制代码
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationScheme = "Cookie",
        LoginPath = new PathString("/Account/Login"),
        AccessDeniedPath = new PathString("/Account/Forbidden"),
        AutomaticAuthenticate = true,
        AutomaticChallenge = true
    });
}
复制代码

在某个Controller或Action添加[Author],即可配置位需要登陆验证的页面。

 

最后:如何运行这个Sample以及下载完整的代码请访问:How to achieve a basic authorization in ASP.NET Core

 

更多脚本样例, 访问微软One Code样例库:http://aka.ms/onescriptsamples 更多代码样例, 访问微软One Script样例库:http://aka.ms/onecodesamples

Dotnet Core 3 MVC 对 Core API 的身份验证

】DotnetCore3MVC对CoreAPI的身份验证【英文标题】:DotnetCore3MVCauthenticationtoCoreAPI【发布时间】:2020-02-0108:45:15【问题描述】:两个独立的项目,DotNetCore3:API和WebMVC。MVC和移动应用都只与API对话。MVC需要通过API对用户进行身份验证(... 查看详情

Asp.Net Core 正确配置身份认证中间件

】Asp.NetCore正确配置身份认证中间件【英文标题】:Asp.NetCoreconfigureIdentityauthenticationmiddlewareproperly【发布时间】:2021-07-2020:18:13【问题描述】:要求是我在项目中有MVC和WebAPI。MVC视图将在初始时交付渲染如登录、功能的基本视图... 查看详情

没有 ASP.NET 身份的 .NET Core 外部身份验证

】没有ASP.NET身份的.NETCore外部身份验证【英文标题】:.NETCoreExternalAuthenticationwithoutASP.NETIdentity【发布时间】:2018-06-1516:09:59【问题描述】:我使用自己的JWT令牌身份验证,而不是默认模板免费提供的asp.net身份。我到处寻找一些... 查看详情

Asp Net Core 身份验证问题

】AspNetCore身份验证问题【英文标题】:AspNetCoreauthenticationtroubles【发布时间】:2020-04-0911:09:21【问题描述】:我已经用Angular制作了aspnetcoreweb应用程序。它使用基于cookie的身份验证,使用标准的网络核心身份验证机制。一切正常... 查看详情

ASP .NET Core 身份登录管理器

】ASP.NETCore身份登录管理器【英文标题】:ASP.NETCoreIdentitySignInManager【发布时间】:2018-03-3009:19:22【问题描述】:美好的一天。ASP.NET-Core项目没有身份验证。因此,我尝试为此添加内置身份。数据库中的表已成功创建,新用户已... 查看详情

Cookie 身份验证 ASP.NET Core

】Cookie身份验证ASP.NETCore【英文标题】:CookieAuthenticationASP.NETCore【发布时间】:2017-03-3012:57:27【问题描述】:我可以在ITicketStore中使用MemoryCache来存储AuthenticationTicket吗?背景:我的网络应用正在使用Cookie身份验证:app.UseCookieAuth... 查看详情

.Net Core 2 OpenID Connect 身份验证和多个身份

】.NetCore2OpenIDConnect身份验证和多个身份【英文标题】:.NetCore2OpenIDConnectAuthenticationandmultipleIdentities【发布时间】:2019-03-1414:14:12【问题描述】:我仍在学习身份框架,并且在尝试在我的.NetCore2MVC应用程序中设置身份验证时迷失... 查看详情

.NET Core Identity Server 4 身份验证 VS 身份验证

】.NETCoreIdentityServer4身份验证VS身份验证【英文标题】:.NETCoreIdentityServer4AuthenticationVSIdentityAuthentication【发布时间】:2017-06-2614:04:23【问题描述】:我试图了解在ASP.NETCore中进行身份验证的正确方法。我查看了几个资源(其中大... 查看详情

.Net Core HttpClient 摘要式身份验证

】.NetCoreHttpClient摘要式身份验证【英文标题】:.NetCoreHttpClientDigestAuthentication【发布时间】:2020-01-2721:44:56【问题描述】:在.NetCore3.1应用程序中使用MongoAtlasAPI,但我无法让HttpClient处理来自摘要身份验证的挑战。代码发送第一个... 查看详情

.NET Core 2.0 身份和 jwt?

】.NETCore2.0身份和jwt?【英文标题】:.NETCore2.0IdentityANDjwt?【发布时间】:2018-12-2108:30:31【问题描述】:我一直在四处寻找并尝试对.NETCoreIdentity(https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-2.1&tabs= 查看详情

ASP.NET Core 使用多种身份验证方法

】ASP.NETCore使用多种身份验证方法【英文标题】:ASP.NETCoreUsingMultipleAuthenticationMethods【发布时间】:2019-07-1004:17:11【问题描述】:同时使用Cookie身份验证中间件和JWT身份验证中间件。当我登录用户时,我创建自定义声明并将它们... 查看详情

Asp net core 和 Firebase 身份验证

】Aspnetcore和Firebase身份验证【英文标题】:AspnetcoreandFirebaseAuthentication【发布时间】:2021-06-1515:44:32【问题描述】:在我的aspnetcore5(api)中,我已将firebase身份验证与此中间件集成:publicvoidConfigureServices(IServiceCollectionservices)services.... 查看详情

Dotnet core 2.0 身份验证多模式身份 cookie 和 jwt

】Dotnetcore2.0身份验证多模式身份cookie和jwt【英文标题】:Dotnetcore2.0authenticationmultipleschemasidentitycookiesandjwt【发布时间】:2018-01-2810:34:31【问题描述】:在dotnetcore1.1asp中,我能够通过执行以下操作来配置和使用身份中间件和jwt中... 查看详情

.NET Core - 使用具有专用身份验证 API 的多个身份验证方案 [关闭]

】.NETCore-使用具有专用身份验证API的多个身份验证方案[关闭]【英文标题】:.NETCore-UsingmultipleauthenticationschemeswithadedicatedAuthenticationAPI[closed]【发布时间】:2021-03-0107:54:58【问题描述】:我正在尝试创建一个专用的身份验证API,我... 查看详情

没有身份的 ASP.NET Core 2.0 承载身份验证

】没有身份的ASP.NETCore2.0承载身份验证【英文标题】:ASP.NETCore2.0BearerAuthwithoutIdentity【发布时间】:2018-01-2416:55:17【问题描述】:当我一天前开始在.NETcore2.0上实现一个独立的承载身份验证webapi时,我以为我有一个非常简单的目... 查看详情

ASP.NET Core 中的 Jwt 令牌身份验证

】ASP.NETCore中的Jwt令牌身份验证【英文标题】:JwttokenauthenticationinASP.NETCore【发布时间】:2021-12-1711:55:34【问题描述】:我正在构建一个ASP.NETCoreWeb应用程序和Angular,我想使用基于令牌的身份验证来保护它。我对身份验证机制相... 查看详情

.Net Core WebAPI CORS 与 Windows 身份验证

】.NetCoreWebAPICORS与Windows身份验证【英文标题】:.NetCoreWebAPICORSwithWindowsAuthentication【发布时间】:2018-01-0704:43:42【问题描述】:我有一个.NetCoreWebAPI服务,我为它启用了CORS(使用下面的代码),在项目的属性中我禁用了匿名身份... 查看详情

在 .NET Core 应用程序中添加 Windows 身份验证

】在.NETCore应用程序中添加Windows身份验证【英文标题】:AddWindowsauthenticationin.NETCoreapplication【发布时间】:2022-01-1906:07:51【问题描述】:我是.NET(Core)5的新手,我正在尝试像在web.config文件中的先前版本一样添加Windows身份验证:&l... 查看详情