ZetCode

ASP.NET AllowAnonymous

最后修改于 2025 年 4 月 3 日

在本文中,我们将探讨 ASP.NET 8 中的 AllowAnonymous 属性。此属性可以绕过特定控制器操作的授权要求。

ASP.NET 提供了强大的身份验证和授权功能。当您需要使某些端点在无需身份验证的情况下可访问时,可以使用 AllowAnonymous。

基本定义

ASP.NET 中的 AllowAnonymous 属性表示控制器或操作方法应跳过授权检查。它会覆盖任何授权策略。

当应用于控制器或操作时,即使控制器或应用程序需要身份验证,它也允许匿名访问。这对于登录页面等公共端点很有用。

AllowAnonymous 是 ASP.NET 授权系统的一部分。它适用于 .NET 8 应用程序中的传统和基于属性的授权方法。

ASP.NET AllowAnonymous 示例

以下示例演示了在 Web API 控制器中使用 AllowAnonymous。

Program.cs
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = builder.Configuration["Jwt:Issuer"],
            ValidAudience = builder.Configuration["Jwt:Audience"],
            IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
        };
    });

builder.Services.AddControllers();

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();
app.Run();

这会为应用程序设置 JWT bearer 身份验证。身份验证中间件在授权之前添加,以确保请求得到正确处理。

Controllers/AuthController.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;

[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
    private readonly IConfiguration _config;

    public AuthController(IConfiguration config)
    {
        _config = config;
    }

    [AllowAnonymous]
    [HttpPost("login")]
    public IActionResult Login([FromBody] LoginModel login)
    {
        // In a real app, validate credentials against database
        if (login.Username != "admin" || login.Password != "password")
            return Unauthorized();
            
        var token = GenerateJwtToken(login.Username);
        return Ok(new { Token = token });
    }

    [Authorize]
    [HttpGet("profile")]
    public IActionResult GetProfile()
    {
        var username = User.Identity.Name;
        return Ok(new { Username = username, Message = "Secure data" });
    }

    private string GenerateJwtToken(string username)
    {
        var claims = new[]
        {
            new Claim(ClaimTypes.Name, username),
            new Claim(ClaimTypes.Role, "User")
        };

        var key = new SymmetricSecurityKey(
            Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
            
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        var token = new JwtSecurityToken(
            issuer: _config["Jwt:Issuer"],
            audience: _config["Jwt:Audience"],
            claims: claims,
            expires: DateTime.Now.AddMinutes(30),
            signingCredentials: creds);

        return new JwtSecurityTokenHandler().WriteToken(token);
    }
}

public record LoginModel(string Username, string Password);

此控制器显示两个端点:一个公共登录端点和一个安全的配置文件端点。登录端点标记有 AllowAnonymous,以允许未经身份验证的访问。

Login 操作在验证凭据后生成 JWT 令牌。GetProfile 操作需要身份验证,如 Authorize 属性所示。

该示例演示了如何将 AllowAnonymous 与同一控制器中的 Authorize 一起使用。这种模式对于与身份验证相关的端点很常见。

来源

Microsoft ASP.NET 授权文档

在本文中,我们探讨了 ASP.NET 8 中的 AllowAnonymous 属性。此重要功能可在 Web 应用程序中实现灵活的授权配置。

作者

我的名字是 Jan Bodnar,我是一名充满热情的程序员,拥有丰富的编程经验。我自 2007 年以来一直在撰写编程文章。迄今为止,我已撰写了 1400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出所有 ASP.NET 教程