AspNetCore认证授权代码怎么写

发布时间:2022-01-05 15:03:44 作者:柒染
阅读:175
开发者专用服务器限时活动,0元免费领! 查看>>

AspNetCore认证授权代码怎么写

在现代Web应用程序中,认证(Authentication)和授权(Authorization)是确保系统安全性的关键部分。AspNetCore提供了强大的内置机制来实现认证和授权功能。本文将详细介绍如何在AspNetCore中编写认证和授权代码,涵盖从基本概念到实际代码实现的各个方面。

1. 认证与授权的基本概念

1.1 认证(Authentication)

认证是确认用户身份的过程。常见的认证方式包括: - Cookie认证:使用Cookie来存储用户身份信息。 - JWT(JSON Web Token)认证:使用JWT来传递用户身份信息。 - OAuth2.0:使用第三方服务进行认证。

1.2 授权(Authorization)

授权是确认用户是否有权限访问特定资源的过程。常见的授权方式包括: - 基于角色的授权:根据用户的角色来决定其权限。 - 基于声明的授权:根据用户的声明(Claims)来决定其权限。 - 基于策略的授权:使用自定义策略来决定用户的权限。

2. 配置认证与授权

2.1 安装必要的NuGet包

在AspNetCore项目中,首先需要安装以下NuGet包: - Microsoft.AspNetCore.Authentication.Cookies:用于Cookie认证。 - Microsoft.AspNetCore.Authentication.JwtBearer:用于JWT认证。 - Microsoft.AspNetCore.Authorization:用于授权。

可以通过NuGet包管理器或命令行安装:

dotnet add package Microsoft.AspNetCore.Authentication.Cookies
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
dotnet add package Microsoft.AspNetCore.Authorization

2.2 配置认证服务

Startup.cs文件中,配置认证服务。以下是一个使用Cookie认证的示例:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
            options.LoginPath = "/Account/Login"; // 登录页面路径
            options.AccessDeniedPath = "/Account/AccessDenied"; // 拒绝访问页面路径
        });

    services.AddControllersWithViews();
}

2.3 配置授权服务

Startup.cs文件中,配置授权服务。以下是一个基于角色的授权示例:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthorization(options =>
    {
        options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin"));
        options.AddPolicy("UserOnly", policy => policy.RequireRole("User"));
    });

    services.AddControllersWithViews();
}

2.4 启用认证与授权中间件

Startup.cs文件的Configure方法中,启用认证与授权中间件:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthentication(); // 启用认证中间件
    app.UseAuthorization(); // 启用授权中间件

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

3. 实现认证

3.1 登录与登出

AccountController中实现登录与登出功能:

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

    [HttpPost]
    public async Task<IActionResult> Login(string username, string password)
    {
        // 验证用户名和密码
        if (username == "admin" && password == "password")
        {
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, username),
                new Claim(ClaimTypes.Role, "Admin")
            };

            var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var principal = new ClaimsPrincipal(identity);

            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

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

        ModelState.AddModelError(string.Empty, "Invalid login attempt.");
        return View();
    }

    [HttpPost]
    public async Task<IActionResult> Logout()
    {
        await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        return RedirectToAction("Index", "Home");
    }
}

3.2 使用JWT认证

如果需要使用JWT认证,可以在Startup.cs中配置JWT认证服务:

public void ConfigureServices(IServiceCollection services)
{
    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key"));
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = "your_issuer",
                ValidAudience = "your_audience",
                IssuerSigningKey = key
            };
        });

    services.AddControllersWithViews();
}

在登录时生成JWT:

[HttpPost]
public IActionResult Login(string username, string password)
{
    if (username == "admin" && password == "password")
    {
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, username),
            new Claim(ClaimTypes.Role, "Admin")
        };

        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key"));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        var token = new JwtSecurityToken(
            issuer: "your_issuer",
            audience: "your_audience",
            claims: claims,
            expires: DateTime.Now.AddMinutes(30),
            signingCredentials: creds);

        return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
    }

    return Unauthorized();
}

4. 实现授权

4.1 基于角色的授权

在控制器或Action上使用[Authorize]特性来实现基于角色的授权:

[Authorize(Roles = "Admin")]
public class AdminController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

4.2 基于策略的授权

Startup.cs中定义策略:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthorization(options =>
    {
        options.AddPolicy("MinimumAge", policy =>
            policy.RequireClaim("DateOfBirth", DateTime.Now.AddYears(-18).ToString()));
    });

    services.AddControllersWithViews();
}

在控制器或Action上使用策略:

[Authorize(Policy = "MinimumAge")]
public class AdultController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

5. 总结

本文详细介绍了如何在AspNetCore中实现认证与授权功能。通过配置认证服务、实现登录与登出、使用JWT认证、以及基于角色和策略的授权,您可以构建一个安全可靠的Web应用程序。希望本文对您在AspNetCore项目中实现认证与授权有所帮助。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:
  1. Spring security的认证和授权
  2. 如何实现SpringSecurity的认证和授权

开发者交流群:

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

原文链接:https://my.oschina.net/u/3772973/blog/4567636

aspnetcore

上一篇:Java基础框架面试题有哪些

下一篇:QT如何实现定时关闭消息提示框

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》
开发者交流群×