【问题标题】:exclude error razor page from OpenIdConnect authentication从 OpenIdConnect 身份验证中排除错误剃刀页面
【发布时间】:2021-11-02 19:01:15
【问题描述】:

我在 blazor 项目中遇到了 OpenIdConnect 身份验证问题。如果登录失败或在登录过程中启动应用程序时发生任何异常,则应用程序将控制重定向到 error.razor 页面,因为用户未通过身份验证应用程序再次尝试从错误页面登录,而不是显示错误消息(身份验证之间的无限循环启动和error.razor)。我想从身份验证页面中排除错误页面。我做了很多搜索,但没有找到我的问题的解决方案

public void ConfigureServices(IServiceCollection services)
        {
            var config = new ConfigurationBuilder()
                .AddEnvironmentVariables()
                .Build();

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

            services.AddRazorPages();
            services.AddServerSideBlazor();
            
            services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
                .AddAzureAD(options => Configuration.Bind("AzureAd", options));


            services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    // Instead of using the default validation (validating against a single issuer value, as we do in
                    // line of business apps), we inject our own multitenant validation logic
                    ValidateIssuer = false


                    // If the app is meant to be accessed by entire organizations, add your issuer validation logic here.
                    //IssuerValidator = (issuer, securityToken, validationParameters) => {
                    //    if (myIssuerValidationLogic(issuer)) return issuer;
                    //}
                };

                options.Events = ConfigureOpenIdConnectEvents(services);
            });
        }
private OpenIdConnectEvents ConfigureOpenIdConnectEvents(IServiceCollection services)
        {
            return new OpenIdConnectEvents
            {
                OnTicketReceived = context => Task.CompletedTask,
                OnAuthenticationFailed = context =>
                {
                    if (CurrentEnvironment.IsDevelopment()) return Task.CompletedTask;

                    context.Response.Redirect("/Error");

                    context.HandleResponse(); // Suppress the exception

                    return Task.CompletedTask;
                },
                // If your application needs to authenticate single users, add your user validation below.
                OnTokenValidated = context =>
                {
                    var client = Client;
                    var claims = new List<Claim>
                    {
                        new Claim("ClientId", client.Id.ToString()),
                    };
                    var appIdentity = new ClaimsIdentity(claims);
                    context.Principal.AddIdentity(appIdentity);
                    return Task.CompletedTask;
                }
            };
        }

Error.Razor 页面

@page "/error"
<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>
<h3>Development Mode</h3>
<p>
    Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
</p>
<p>
    <strong>The Development environment shouldn't be enabled for deployed applications.</strong>
    It can result in displaying sensitive information from exceptions to end users.
    For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
    and restarting the app.
</p>

【问题讨论】:

    标签: c# asp.net-core blazor openid-connect blazor-server-side


    【解决方案1】:

    您是否尝试在错误页面中添加授权标签?

    类似:

    <AuthorizeView>
        <Authorized>
            <H2> error message authorized</H2>
        </Authorized>
        <NotAuthorized>
             <H2> error message not authorized</H2>
        </NotAuthorized>
    </AuthorizeView>
    

    另一种方法应该是评估您来自的页面。
    比如:

    var endpoint = context.GetEndpoint() as RouteEndpoint;
    var routeNameMetadata = endpoint?.Metadata.OfType<RouteNameMetadata>().SingleOrDefault();
    var routeName = routeNameMetadata?.RouteName;
    
    if (routeName.StartsWith("error")) return Task.CompletedTask;
    

    我没试过。
    原始解决方案来自这个答案:
    How can I get the current route name with ASP.NET Core?

    解决方案 2

    从 .net 5 开始,我们可以使用 IAllowAnonymous 接口的新实现。

    尝试添加:

    @attribute [Microsoft.AspNetCore.Authorization.AllowAnonymous]
    

    【讨论】:

    • 嗨@Nicola,感谢您的回复。是的,我厌倦了您提到的上述代码,但仍然重定向登录
    • 您是否在导入中添加了@authorize?那么每个页面都会在授权下自动运行?
    • 没有。请指导如何添加。谢谢
    • 如果您将@attribute [Authorize] 添加到您的Imports.razor 中,每个页面(在_Imports.razor 的同一项目内)都将位于授权.
    猜你喜欢
    • 2020-05-22
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 2021-06-11
    • 2020-02-01
    • 2020-07-13
    相关资源
    最近更新 更多