Аутентификация OKTA с ASP.Net Core выдает необработанное исключение, когда пользователь не назначен клиентскому приложению - PullRequest
0 голосов
/ 01 июня 2019

Я интегрировал OKTA в свое приложение ASP.Net Core из следующего учебного пособия: https://developer.okta.com/quickstart/#/okta-sign-in-page/dotnet/aspnetcore

Это прекрасно работает, если пользователь назначен моему приложению OKTA, но если нет, я получаю необработанное исключениев обратном вызове авторизации:

OpenIdConnectProtocolException: сообщение содержит ошибку: «access_denied», error_description: «Пользователь не назначен клиентскому приложению.», error_uri: «error_uri is null».

Я хотел бы поймать это исключение и обработать его изящно.

С OpenId вы можете создать событие OnRemoteFailure, чтобы справиться с этим, но я не могу понять, как это сделатьбиблиотека Okta.AspNetCore.

1 Ответ

1 голос
/ 03 июня 2019

Схема Okta.AspNetCore по умолчанию: OpenIdConnectDefaults.AuthenticationScheme:

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;

namespace Okta.AspNetCore
{
    public static class OktaDefaults
    {
        public const string MvcAuthenticationScheme = OpenIdConnectDefaults.AuthenticationScheme;

        public const string ApiAuthenticationScheme = JwtBearerDefaults.AuthenticationScheme;

        public const string CallbackPath = "/authorization-code/callback";

        public const string SignOutCallbackPath = "/signout/callback";

        public static readonly string[] Scope = new string[] { "openid", "profile" };
    }
}

Таким образом, вы можете настроить OpenIdConnectOptions, используя имена схем из приведенных выше, включая доступ к OpenIdConnectEvents:

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = OktaDefaults.MvcAuthenticationScheme;
})
.AddCookie()
.AddOktaMvc(new OktaMvcOptions
{
    // Replace these values with your Okta configuration
    OktaDomain = Configuration.GetValue<string>("Okta:OktaDomain"),
    ClientId = Configuration.GetValue<string>("Okta:ClientId"),
    ClientSecret = Configuration.GetValue<string>("Okta:ClientSecret"),
});
services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
    options.Events = new OpenIdConnectEvents
    {
        OnRedirectToIdentityProvider = async ctxt =>
        {
            // Invoked before redirecting to the identity provider to authenticate. This can be used to set ProtocolMessage.State
            // that will be persisted through the authentication process. The ProtocolMessage can also be used to add or customize
            // parameters sent to the identity provider.
            await Task.Yield();
        },
        OnMessageReceived = async ctxt =>
        {
            // Invoked when a protocol message is first received.
            await Task.Yield();
        },
        OnTicketReceived = async ctxt =>
        {
            // Invoked after the remote ticket has been received.
            // Can be used to modify the Principal before it is passed to the Cookie scheme for sign-in.
            // This example removes all 'groups' claims from the Principal (assuming the AAD app has been configured
            // with "groupMembershipClaims": "SecurityGroup"). Group memberships can be checked here and turned into
            // roles, to be persisted in the cookie.

            await Task.Yield();
        },
        OnRemoteFailure = context =>
        {

            ..........
            context.HandleResponse();
            context.Response.Redirect("AccessDenied?error=" + context.Failure.Message);

            return Task.FromResult(0);
        },
    };
});
...