asp.net core 基本身份验证

1.创建项目

  • 使用visual studio创建一个空的asp.net core mvc项目
  • 在StartUp类中添加代码
//服务注册中
services.AddControllersWithViews();
//管道中
app.UseEndpoints(endpoints =>
{
    endpoints.MapDefaultControllerRoute();
});
  • 新建一个HomeController,并创建三个方法和视图
//无需验证权限的方法
public IActionResult Index()
{
    return View();
}
//需要验证权限的方法
[Authorize]
public IActionResult Secret()
{
    return View();
}
public IActionResult Authenticate()
{
    return RedirectToAction("Index");
}
  • 此时我们访问/home/index可以看到正确的页面,访问/home/secret会报一个错误:
InvalidOperationException: Endpoint Basic.Controllers.HomeController.Secret (Basic) contains authorization metadata, but a middleware was not found that supports authorization.Configure your application startup by adding app.UseAuthorization() inside the call to Configure(..) in the application startup code. The call to app.UseAuthorization() must appear between app.UseRouting() and app.UseEndpoints(...).

这个错误的原因是我们没有配置鉴权,框架不知道如何处理验证的问题

2.配置基于cookie的验证

基于以上的代码,我们做如下修改:

  • 在服务配置方法中:
services.AddAuthentication("CookieAuth")
.AddCookie("CookieAuth", config =>
{
    config.Cookie.Name = "mysite.cookie";    #生成的cookie名称
    config.LoginPath = "/Home/Authenticate";    #登录地址,如果没有配置,默认会跳转/Account/Login
});
  • 在管道配置方法中:
   
//who are you?
app.UseAuthentication();  # 认证中间件,必须位于 app.UseRouting() 和 app.UseEndpoints() 之间
//are you allowed?
app.UseAuthorization();  # 授权中间件,必须位于 app.UseRouting() 和 app.UseEndpoints() 之间,必须位于 app.UseAuthentication() 下面
  • 在认证方法 Home/Authenticate 中写入如下代码:
//在此可以进行一些数据库验证,然后取出信息放入下面
//定义一些身份信息,可以定义多个
var myClaims = new List<Claim>()
{
    new Claim(ClaimTypes.Name,"zhangsan"),
    new Claim(ClaimTypes.Email,"zhangsan@qq.com"),
    new Claim("zhangsan.hobby","shopping")
};
var otherClaims = new List<Claim>()
{
    new Claim(ClaimTypes.Name,"zhangsan"),
    new Claim(ClaimTypes.Email,"zhangsan@qq.com"),
    new Claim("zhangsan.hobby","shopping")
};
var myIdentity = new ClaimsIdentity(myClaims, "myIdentity");
var otherIdentity = new ClaimsIdentity(otherClaims, "otherIdentity");
var userPrinciple = new ClaimsPrincipal(new []{myIdentity,otherIdentity});
//调用框架登录方法
HttpContext.SignInAsync(userPrinciple);
return RedirectToAction("Index");
  • 再次运行项目,访问 /home/secret 页面,会发现浏览器的cookie已经生成,第一次会跳转到 /home/index,第二次再访问就可以看到 /home/secret 页面的内容了

3.完整代码

  • Startup.cs
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication("CookieAuth")
            .AddCookie("CookieAuth", config =>
            {
                config.Cookie.Name = "mysite.cookie";
                config.LoginPath = "/Home/Authenticate";
            });
        services.AddControllersWithViews();
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        //who are you?
        app.UseAuthentication();
        //are you allowed?
        app.UseAuthorization();
        

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapDefaultControllerRoute();
        });
    }
}
  • HomeController.cs
public class HomeController:Controller
{
    public IActionResult Index()
    {
        return View();
    }

    [Authorize]
    public IActionResult Secret()
    {
        return View();
    }

    public IActionResult Authenticate()
    {
        //在此可以进行一些数据库验证,然后取出信息放入下面
        //定义一些身份信息,可以定义多个
        var myClaims = new List<Claim>()
        {
            new Claim(ClaimTypes.Name,"zhangsan"),
            new Claim(ClaimTypes.Email,"zhangsan@qq.com"),
            new Claim("zhangsan.hobby","shopping")
        };
        var otherClaims = new List<Claim>()
        {
            new Claim(ClaimTypes.Name,"zhangsan"),
            new Claim(ClaimTypes.Email,"zhangsan@qq.com"),
            new Claim("zhangsan.hobby","shopping")
        };
        var myIdentity = new ClaimsIdentity(myClaims, "myIdentity");
        var otherIdentity = new ClaimsIdentity(otherClaims, "otherIdentity");
        var userPrinciple = new ClaimsPrincipal(new []{myIdentity,otherIdentity});
        //调用框架登录方法
        HttpContext.SignInAsync(userPrinciple);
        return RedirectToAction("Index");
    }
}
原文地址:https://www.cnblogs.com/xiaoqingtian/p/13574320.html