Use Authorization middleware instead of AuthorizationAttribute ASPNET Core

Callum Linington

I have a dedicated IdServer running that has the login page that other applications will boot unauthenticated users to.

My current pipeline is:

app.UseCookieAuthentication
app.UseOpenIdConnectAuthentication
app.UseDefaultFiles // because it is a SPA app
app.UseStaticFiles // the SPA app

So all tutorials say to use [Authorize] on your controllers...

However, I want middle to authorize all of my controllers, and static files.

So how do I write a middleware to handle that.

My current setup is:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IOptions<IdentityServerAppOptions> identityServerAppOptions)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    var serverAppOptions = identityServerAppOptions.Value;

    loggerFactory.CreateLogger("Configure").LogDebug("Identity Server Authority Configured: {0}", serverAppOptions.Authority);

    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationScheme = "Cookies"
    });
    app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
    {
        AuthenticationScheme = "oidc",
        SignInScheme = "Cookies",

        Authority = serverAppOptions.Authority,
        RequireHttpsMetadata = false,

        ClientId = "Video",
        SaveTokens = true
    });

    app.Use(async (context, next) =>
    {
        var authService = context.RequestServices.GetRequiredService<IAuthorizationService>();


        if (!await authService.AuthorizeAsync(context.User, context, "Api"))
        {
            // This is as far as I have got, here we should boot them to IdServer
        }
    });

    app.UseDefaultFiles(new DefaultFilesOptions
    {
        DefaultFileNames = new List<string> { "index.html" },
        RequestPath = new PathString("")
    });
    app.UseStaticFiles(new StaticFileOptions
    {
        OnPrepareResponse = ctx =>
        {
            ctx.Context.Response.Headers.Append("Cache-Control", "no-cache");
        }
    });
    app.UseMvc();
}
Callum Linington

Just needed to add the AuthenticationManager Challenge:

app.Use(async (context, next) =>
{
    var authService = context.RequestServices.GetRequiredService<IAuthorizationService>();


    if (!await authService.AuthorizeAsync(context.User, context, "Api"))
    {
        await context.Authentication.ChallengeAsync("oidc");
    }
    else
    {
        await next();
    }
});

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

NLog AspNet Core 5.0

分類Dev

AuthorizationAttribute ASPNETCoreの代わりにAuthorizationミドルウェアを使用する

分類Dev

AspNet Core CookieAuthentication with injected SessionStore

分類Dev

Http Query Parameters in UTC in AspNet Core

分類Dev

Model binding not working in aspnet core web api

分類Dev

AspNet Core3ID構成

分類Dev

Use carrierwave with Bearer token Authorization

分類Dev

Dynamic User Group Authorization in .NET Core

分類Dev

Use TypeScript lib.core.d.ts instead of lib.d.ts

分類Dev

ASP.NET Core 2.0 authentication middleware

分類Dev

Middleware in .net core not working, letting me step into it

分類Dev

AspNet Core using in memory repo for data protection when running in IIS

分類Dev

AspNet Core using in memory repo for data protection when running in IIS

分類Dev

AspNet Core using in memory repo for data protection when running in IIS

分類Dev

AspNet Core DI:TryAddとAddの使用法

分類Dev

How to validate user agains policy in code in aspnet core?

分類Dev

Swashbuckle aspnet core 2.0 Swaggerconfig.cs not created

分類Dev

Using Google OAuth to secure web services in aspnet core

分類Dev

aspnet core 2.2 web app environment variables not changing in docker

分類Dev

AspNet Core - input/output JSON serialization settings at Controller Level

分類Dev

Dotnet Core Aspnet 1.1用のSimple(st)Dockerfile

分類Dev

IdentityServer4 Authorization returns 403 forbidden instead of 401

分類Dev

Use same authorization policies for client and server in Blazor

分類Dev

how to use declartive_Authorization in rails engine

分類Dev

How to use 'OR' middleware for route laravel 5

分類Dev

How to use a route specific middleware of express in Nestjs?

分類Dev

Authorization in ASP.NET Core 2.0 via openid provider

分類Dev

How to implement permission based authorization in ASP.net core Identity?

分類Dev

Get a 403 when using dual authorization (Bearer & Basic) in .net core

Related 関連記事

  1. 1

    NLog AspNet Core 5.0

  2. 2

    AuthorizationAttribute ASPNETCoreの代わりにAuthorizationミドルウェアを使用する

  3. 3

    AspNet Core CookieAuthentication with injected SessionStore

  4. 4

    Http Query Parameters in UTC in AspNet Core

  5. 5

    Model binding not working in aspnet core web api

  6. 6

    AspNet Core3ID構成

  7. 7

    Use carrierwave with Bearer token Authorization

  8. 8

    Dynamic User Group Authorization in .NET Core

  9. 9

    Use TypeScript lib.core.d.ts instead of lib.d.ts

  10. 10

    ASP.NET Core 2.0 authentication middleware

  11. 11

    Middleware in .net core not working, letting me step into it

  12. 12

    AspNet Core using in memory repo for data protection when running in IIS

  13. 13

    AspNet Core using in memory repo for data protection when running in IIS

  14. 14

    AspNet Core using in memory repo for data protection when running in IIS

  15. 15

    AspNet Core DI:TryAddとAddの使用法

  16. 16

    How to validate user agains policy in code in aspnet core?

  17. 17

    Swashbuckle aspnet core 2.0 Swaggerconfig.cs not created

  18. 18

    Using Google OAuth to secure web services in aspnet core

  19. 19

    aspnet core 2.2 web app environment variables not changing in docker

  20. 20

    AspNet Core - input/output JSON serialization settings at Controller Level

  21. 21

    Dotnet Core Aspnet 1.1用のSimple(st)Dockerfile

  22. 22

    IdentityServer4 Authorization returns 403 forbidden instead of 401

  23. 23

    Use same authorization policies for client and server in Blazor

  24. 24

    how to use declartive_Authorization in rails engine

  25. 25

    How to use 'OR' middleware for route laravel 5

  26. 26

    How to use a route specific middleware of express in Nestjs?

  27. 27

    Authorization in ASP.NET Core 2.0 via openid provider

  28. 28

    How to implement permission based authorization in ASP.net core Identity?

  29. 29

    Get a 403 when using dual authorization (Bearer & Basic) in .net core

ホットタグ

アーカイブ