【问题标题】:asp.net authorize by default (without [Authorize])asp.net 默认授权(不带 [Authorize])
【发布时间】:2021-09-16 20:11:44
【问题描述】:

我有一个 asp.netcore .net 5 应用程序。

我已获得使用控制器端点上方的[Authorize] 属性的授权。

如何让它使用授权而不使用[Authorize] 属性?以下是我设置授权的方式:

我有这个在ConfigureServices:

public void ConfigureServices(IServiceCollection services)
{...
        FirebaseApp.Create(new AppOptions()
        {
            Credential = GoogleCredential.FromFile("firebase_admin_sdk.json"),
        });

        services
        .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.Authority = "https://securetoken.google.com/vepo-xxx";
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidIssuer = "https://securetoken.google.com/vepo-xxx",
                ValidateAudience = true,
                ValidAudience = "vepo-xxx",
                ValidateLifetime = true
            };
        });
...}

在我Configure 有:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, VepoContext context, ISearchIndexService searchIndexService)
{...
    app.UseAuthentication();
    app.UseAuthorization();
...}

【问题讨论】:

    标签: asp.net asp.net-core .net-5 asp.net-authorization asp.net5


    【解决方案1】:

    请参阅Require authenticated users 的文档。您可以将RequireAuthenticatedUser() 添加到所有控制器:

    public void ConfigureServices(IServiceCollection services)
    {
    
        ...
    
        services.AddControllers(config =>
        {
            // using Microsoft.AspNetCore.Mvc.Authorization;
            // using Microsoft.AspNetCore.Authorization;
            var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
            config.Filters.Add(new AuthorizeFilter(policy));
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-20
      • 2016-09-25
      • 2019-02-04
      • 1970-01-01
      • 1970-01-01
      • 2018-01-24
      • 2017-08-07
      • 2017-07-15
      相关资源
      最近更新 更多