Using Open ID Connect with Server Side Blazor

爷,独闯天下 提交于 2019-12-21 05:21:40

问题


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.


回答1:


Add to ConfigureServices code below.

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



回答2:


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...



来源:https://stackoverflow.com/questions/56580654/using-open-id-connect-with-server-side-blazor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!