简体   繁体   中英

Using Open ID Connect with Server Side Blazor

I'd like to use Open ID Connect with Identity Server 4 for authorization in my server side Blazor application. I've got the same setup working in a MVC application.

With the newest .NET Core version, 3.0 Preview 6, it is possible to add the attribute ´@attribute [Authorize]´ to a site. But if I'm not authorized, I don't get redirected to the Identity Server to log in, as I am used from my MVC applications. Instead the site only shows the message "Not authorized".

In Startup.cs I've got the following setup:

        services.AddAuthentication(options =>
        {
            options.DefaultScheme = "Cookies";
            options.DefaultChallengeScheme = "oidc";
        })
        .AddCookie("Cookies")
        .AddOpenIdConnect("oidc", options =>
        {
            options.Authority = "http://localhost:5000";
            options.RequireHttpsMetadata = false;

            options.ClientId = "myClient";
            options.SaveTokens = true;
        });

and

        app.UseAuthentication();

How do I tell the application, that I want to be redirected to the Identity Server if I'm not logged in?

EDIT: Codevisions answer works as a workaround. I found pending github issues here and here , planned for .NET Core 3.0 Preview 7 that will possibly cover this issue officially.

Add to ConfigureServices code below.

services.AddMvcCore(options =>
{
    var policy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
    options.Filters.Add(new AuthorizeFilter(policy));
});

The following code-snippet demonstrates how you can annotate a data controller in your Web API with the Authorize attribute to redirect an unauthenticated user to log in (perhaps Identity Server).

[Authorize(AuthenticationSchemes = OpenIdConnectDefaults.AuthenticationScheme)] 
[Route("api/[controller]")]
    public class SampleDataController : Controller
    {
    // ..
    }

Note: Appropriate configuration is need in the Startup class

Note: If you use a Service instead of Web API, I'd advise you to discard the former and use the latter.

Note: I was not aware of the @attribute directive, but why don't you give it a try like this and tell us if it works for you...

@attribute [Authorize(AuthenticationSchemes = OpenIdConnectDefaults.AuthenticationScheme)] 

I'll try to add more info later on, but run your app and ask questions about issues you're facing...

Hope this helps...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM