Как настроить приложение MVC 5 с федеративной аутентификацией Cognito - PullRequest
0 голосов
/ 01 ноября 2018

Я пытаюсь получить аутентификацию приложения MVC 5 с настроенным провайдером SAML в Amazon Cognito через промежуточное ПО OWIN.

В моем классе Startup у меня есть:

app.Use(typeof(AuthenticationMiddleware));
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
        OnValidateIdentity = MyCustomValidateIdentity
    },
    SlidingExpiration = true,
    ExpireTimeSpan = TimeSpan.FromMinutes(timespan)
});

var config = ConfigHelper.CognitoConfigSection;
var signingCert = new X509Certificate2(Encoding.ASCII.GetBytes(config.cert));
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
    AuthenticationType = "Cognito",
    AuthenticationMode = AuthenticationMode.Passive,
    Authority = $"https://cognito-idp.{config.Region}.amazonaws.com/{config.UserPoolId}",
    ResponseType = "code",
    ClientId = config.UserpoolClientId,
    ClientSecret = config.UserpoolClientSecret,
    Scope = String.Join(" ", "openid", "profile", "email"),
    MetadataAddress = $"https://cognito-idp.{config.Region}.amazonaws.com/{config.UserPoolId}/.well-known/openid-configuration",
    RedirectUri = "http://localhost:12345",
    TokenValidationParameters = new TokenValidationParameters
    {
        SaveSigninToken = true,
        RequireSignedTokens = true,
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new X509SecurityKey(signingCert),
        ValidateLifetime = true,
        ValidateAudience = false,
        ValidateIssuer = false,
        ValidIssuer = $"https://cognito-idp.{config.Region}.amazonaws.com/{config.UserPoolId}",
        ClockSkew = TimeSpan.FromMinutes(0)
    },
    SignInAsAuthenticationType = "Cookies",
    Notifications = new OpenIdConnectAuthenticationNotifications
    {
        // Defined all of these with break points to see what hit and what didn't
        RedirectToIdentityProvider = (ctx) =>
        {
            // This break point hits when auth challenge is initiated
            return Task.FromResult(0);
        },
        MessageReceived = (ctx) =>
        {
            // This break point and all the rest never hit.
            return Task.FromResult(0);
        },
        AuthorizationCodeReceived = (ctx) =>
        {
            return Task.FromResult(0);
        },
        AuthenticationFailed = (ctx) =>
        {
            return Task.FromResult(0);
        },
        SecurityTokenReceived = (ctx) =>
        {
            return Task.FromResult(0);
        },
        SecurityTokenValidated = (ctx) =>
        {
            var identity = ctx.AuthenticationTicket.Identity;
            return Task.FromResult(0);
        }
    }
});

В виде логина моего AccountController у меня есть ссылка

<a href="@Url.Action("Login", "Account", new { returnUrl = ViewBag.ReturnUrl, authType = "Cognito" })">Corporate Login</a>

И в действии контроллера для представления входа в систему у меня есть этот фрагмент:

HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = returnUrl }, authType);

При такой полной настройке, как я есть, я могу щелкнуть ссылку, инициировать проверку подлинности, точки прерывания уведомления RedirectToIdentityProvider (я возобновляю), я перенаправлен в Cognito UserPool, который затем перенаправляет на настроенный SAML Страница входа провайдера идентификации, я аутентифицируюсь (успешно с действительными учетными данными), перенаправляет обратно в приложение с кодом аутентификации в URL, и все. Ни одна из других точек останова оповещения не достигнута, и пользователь все еще не аутентифицирован.

...