怎么在ASP.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>
<h2>Auth page</h2>
<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
});
}
关于怎么在ASP.NET Core中实现一个身份认证功能问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。