Asp.Net Core 实现登录验证身份的功能

步骤如下:

1.打开VS2019,新建ASP.NET Core Web应用程序,选择Web应用程序(模型视图控制器)

 

 

不用勾选右侧的身份认证,因为演示的是比较简单的,而勾选之后模板内容较为复杂

 

2、在Controller文件夹下AccountController,代码如下:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Security.Claims;

using System.Threading.Tasks;

using Microsoft.AspNetCore.Authentication;

using Microsoft.AspNetCore.Authentication.Cookies;

using Microsoft.AspNetCore.Authorization;

using Microsoft.AspNetCore.Mvc;



namespace Server.Controllers

{

public class AccountController: Controller

{

/// <summary>

/// 登录页面

/// </summary>

/// <returns></returns>

public IActionResult Login()

{

return View();

}



/// <summary>

/// post 登录请求

/// </summary>

/// <returns></returns>

[HttpPost]

public async Task<IActionResult> Login(string userName, string password)

{

if (userName.Equals("admin") && password.Equals("123456"))

{

var claims = new List<Claim>(){

new Claim(ClaimTypes.Name,userName),new Claim("password",password)

};

var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Customer"));

await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, new AuthenticationProperties

{

ExpiresUtc = DateTime.UtcNow.AddMinutes(20),

IsPersistent = false,

AllowRefresh = false

});

return Redirect("/Home/Index");

}

return Json(new { result = false, msg = "用户名密码错误!" });

}



/// <summary>

/// 退出登录

/// </summary>

/// <returns></returns>

public async Task<IActionResult> Logout()

{

await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

return Redirect("/Login");

}

}

}

 

3.在Views文件夹下新建一个Account的文件夹,并在文件夹中新建Login.cshtml,实现登录页面的html视图

内容如下:


@{

ViewData["Title"] = "登录";

}



<h2 style="text-align:center">登录管理系统</h2>



<hr />

<div>

<form asp-controller="Account" asp-action="Login" method="post">

<div>

<label class="control-label">用户名</label>

<input class="form-control" type="text" name="username"/>

</div>

<div>

<label class="control-label">密码</label>

<input class="form-control" type="password" name="password" />

</div>

<div class="form-group">

<input type="submit" value="登录" class="btn btn-primary" />

</div>

</form>

</div>





@section Scripts {

@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}

}

 

 

4.修改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("/Home/Privacy");

});

public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IHostingEnvironment env) 方法中加入:

app.UseAuthentication();//认证//身份验证中间件

注意这句话要放在app.UseMvc的前面

 

 

 

5.F5运行项目,然后在浏览器中输入:

https://localhost:5000/Account/Login,访问登录界面

 

输入账号密码后,点击登录,则会进入AccountController的post Login方法,进行验证,若验证成功,则会调用HttpContext.SignInAsync 方法给浏览器发送一个cookie的认证信息

这样用户就可以在其他页面中使用该认证信息进行访问了

 

6.如何控制呢?

通过注解[Authorize] ,在所有需要用户登录的Controller上方加上[Authorize]注解,那么由于在startup中注册过的原因,若发现用户没有认证信息,则会跳转到Account/Login 登录页面要求登录

 

由于已经在Controller上方加过[Authorize],因此这个Controller中所有的方法都会要求验证,如果在该Controller中又有一个get api,我们想让其不需要验证就可以访问,那么可以在该方法上方加上[AllowAnonymous],如:

[AllowAnonymous]

[HttpGet]

[Route("/info")]

public ActionResult<string> Get()

{

return serviceImpl.getDataAll();

}

 

同理[AllowAnonymous]也可以加在Controller上方

 

这样就实现了.netCore 简单的身份验证以及登录功能

  • 10
    点赞
  • 45
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
ASP.NET Core Authorization是一个集成在ASP.NET Core中的授权框架,可以用来实现身份验证和授权。下面介绍如何使用ASP.NET Core Authorization来实现身份验证和授权。 1. 配置身份验证 在Startup.cs文件中的ConfigureServices方法中添加以下代码来配置身份验证: ``` services.AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Configuration["Jwt:Issuer"], ValidAudience = Configuration["Jwt:Audience"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])) }; }); ``` 这段代码使用JWT来进行身份验证,需要提供一个密钥作为签名,可以在appsettings.json中配置。 2. 在控制器中添加授权 在需要授权的控制器或方法上添加Authorize特性来限制访问: ``` [Authorize(Roles = "admin")] public class AdminController : Controller { // ... } ``` 这段代码限制只有拥有admin角色的用户才能访问AdminController。 3. 配置授权策略 通过配置授权策略,可以更细粒度地控制访问权限。在Startup.cs文件的ConfigureServices方法中添加以下代码: ``` services.AddAuthorization(options => { options.AddPolicy("RequireAdminRole", policy => policy.RequireRole("admin")); }); ``` 这段代码配置了一个名为RequireAdminRole的策略,要求用户必须拥有admin角色才能访问。 在控制器或方法上使用Authorize特性指定授权策略: ``` [Authorize(Policy = "RequireAdminRole")] public class AdminController : Controller { // ... } ``` 这段代码限制只有拥有admin角色的用户才能访问AdminController。 以上就是使用ASP.NET Core Authorization来实现身份验证和授权的基本步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值