Проблемы развертывания с IdentityServer в Azure

2

В течение последних двух недель - и мне так сильно больно говорить об этом, я пытаюсь развернуть решение с IdentityServer4, API и веб-клиентом для Azure без успеха. Я столкнулся с таким количеством проблем в процессе, но решение одного из них просто приводит меня к следующему, оставляя меня с текущим, о котором я совершенно не знаю.

Прямо сейчас, если вы заходите на адрес https://breezeonline.ng, он перенаправляет вас в приложение IdentityServer для аутентификации, но когда я вхожу в систему, он переходит в какой-то цикл inifinte, пытаясь перенаправить URL-адрес обратного вызова на длинный времени и сбоев в конце.

В журналах я вижу, что он аутентифицирует пользователя, успешно выдает токен и повторяется. Ниже приведена часть журнала, которая объясняет это

Журнал

2018-09-12T12:57:04.082667372Z [12:57:04 Debug] IdentityServer4.Hosting.EndpointRouter
2018-09-12T12:57:04.082684972Z Request path /connect/authorize matched to endpoint type Authorize
2018-09-12T12:57:04.082698872Z 
2018-09-12T12:57:04.086283241Z [12:57:04 Debug] IdentityServer4.Hosting.EndpointRouter
2018-09-12T12:57:04.086293841Z Endpoint enabled: Authorize, successfully created handler: IdentityServer4.Endpoints.AuthorizeEndpoint
2018-09-12T12:57:04.086298141Z 
2018-09-12T12:57:04.086482040Z [12:57:04 Information] IdentityServer4.Hosting.IdentityServerMiddleware
2018-09-12T12:57:04.086490739Z Invoking IdentityServer endpoint: IdentityServer4.Endpoints.AuthorizeEndpoint for /connect/authorize
2018-09-12T12:57:04.086494739Z 
2018-09-12T12:57:04.086673638Z [12:57:04 Debug] IdentityServer4.Endpoints.AuthorizeEndpoint
2018-09-12T12:57:04.086682338Z Start authorize request
2018-09-12T12:57:04.086685938Z 
2018-09-12T12:57:04.086917636Z [12:57:04 Debug] IdentityServer4.Endpoints.AuthorizeEndpoint
2018-09-12T12:57:04.086926336Z User in authorize request: 6f8aded4-5452-404d-8952-72be464c22d7
2018-09-12T12:57:04.086930136Z 
2018-09-12T12:57:04.087121134Z [12:57:04 Debug] IdentityServer4.Validation.AuthorizeRequestValidator
2018-09-12T12:57:04.087129634Z Start authorize request protocol validation
2018-09-12T12:57:04.087133134Z 
2018-09-12T12:57:04.087355832Z [12:57:04 Debug] IdentityServer4.Validation.AuthorizeRequestValidator
2018-09-12T12:57:04.087380632Z Checking for PKCE parameters
2018-09-12T12:57:04.087384332Z 
2018-09-12T12:57:04.087586030Z [12:57:04 Debug] IdentityServer4.Validation.AuthorizeRequestValidator
2018-09-12T12:57:04.087595730Z No PKCE used.
2018-09-12T12:57:04.087599430Z 
2018-09-12T12:57:04.088024626Z [12:57:04 Debug] IdentityServer4.Validation.AuthorizeRequestValidator
2018-09-12T12:57:04.088033226Z Calling into custom validator: IdentityServer4.Validation.DefaultCustomAuthorizeRequestValidator
2018-09-12T12:57:04.088036926Z 
2018-09-12T12:57:04.088304224Z [12:57:04 Information] IdentityServer4.Endpoints.AuthorizeEndpoint
2018-09-12T12:57:04.088313024Z ValidatedAuthorizeRequest
2018-09-12T12:57:04.088316524Z {
2018-09-12T12:57:04.088320024Z   "ClientId": "BreezeWebClient",
2018-09-12T12:57:04.088323624Z   "ClientName": "Breeze Web Client",
2018-09-12T12:57:04.088327224Z   "RedirectUri": "http://breezeonline.ng/signin-oidc",
2018-09-12T12:57:04.088330824Z   "AllowedRedirectUris": [
2018-09-12T12:57:04.088385323Z     "http://breezeonline.ng/signin-oidc",
2018-09-12T12:57:04.088392323Z     "https://breezeonline.ng/signin-oidc"
2018-09-12T12:57:04.088395923Z   ],
2018-09-12T12:57:04.088399323Z   "SubjectId": "6f8aded4-5452-404d-8952-72be464c22d7",
2018-09-12T12:57:04.088402923Z   "ResponseType": "code id_token",
2018-09-12T12:57:04.088407223Z   "ResponseMode": "form_post",
2018-09-12T12:57:04.088423623Z   "GrantType": "hybrid",
2018-09-12T12:57:04.088476922Z   "RequestedScopes": "openid profile BreezeApi offline_access",
2018-09-12T12:57:04.088518922Z   "State": "CfDJ8N8_2AAgVOJOrHQ43U4UbLtsOv9jds_esgaeJ0OojAk7D5Ue_NjdR8049p2dl1IfR9l1Y4gozSqxu2qhnjHyDrxRyRVLctq90AnIdu5d4UREbYN14Kv5u96BNc8NDuFvW-GM7ufuHRCTKa0_C2Xf1-O7cmZ4lopgGtmnyVMUfZhTWWHl2pC5sWzvE3sK8gxs7szp3fkndoqBZyuqvjyRWpX8-prEgWZQu_2S0X-6Tb5LNFkxZq7hPS_uqNCZZBZY6Kubk6spgEqPlC1aVgJA4lzmf9DPme2p4hfqFl_iiOX-p78cbrRbNCYY4AyS9nMyMoGloGzrRTABi-lTHk3cPZ8",
2018-09-12T12:57:04.088585722Z   "Nonce": "636723538239035673.OWZiYTQ3NTktZWU1Mi00MzE1LWEyMjYtMTk2ODBmZTlhOWYxNDkxOTI3MjktZTUxMS00NTY0LWJiYjYtMDFhMjQ3Yjc2MTU3",
2018-09-12T12:57:04.088593021Z   "SessionId": "343ad1a8f6b93ca74e26b7d8b8f0ad86",
2018-09-12T12:57:04.088596621Z   "Raw": {
2018-09-12T12:57:04.088600121Z     "client_id": "BreezeWebClient",
2018-09-12T12:57:04.088603721Z     "redirect_uri": "http://breezeonline.ng/signin-oidc",
2018-09-12T12:57:04.088607221Z     "response_type": "code id_token",
2018-09-12T12:57:04.088653521Z     "scope": "openid profile BreezeApi offline_access",
2018-09-12T12:57:04.088660021Z     "response_mode": "form_post",
2018-09-12T12:57:04.088663621Z     "nonce": "636723538239035673.OWZiYTQ3NTktZWU1Mi00MzE1LWEyMjYtMTk2ODBmZTlhOWYxNDkxOTI3MjktZTUxMS00NTY0LWJiYjYtMDFhMjQ3Yjc2MTU3",
2018-09-12T12:57:04.088747920Z     "state": "CfDJ8N8_2AAgVOJOrHQ43U4UbLtsOv9jds_esgaeJ0OojAk7D5Ue_NjdR8049p2dl1IfR9l1Y4gozSqxu2qhnjHyDrxRyRVLctq90AnIdu5d4UREbYN14Kv5u96BNc8NDuFvW-GM7ufuHRCTKa0_C2Xf1-O7cmZ4lopgGtmnyVMUfZhTWWHl2pC5sWzvE3sK8gxs7szp3fkndoqBZyuqvjyRWpX8-prEgWZQu_2S0X-6Tb5LNFkxZq7hPS_uqNCZZBZY6Kubk6spgEqPlC1aVgJA4lzmf9DPme2p4hfqFl_iiOX-p78cbrRbNCYY4AyS9nMyMoGloGzrRTABi-lTHk3cPZ8",
2018-09-12T12:57:04.088755120Z     "x-client-SKU": "ID_NETSTANDARD1_4",
2018-09-12T12:57:04.088758720Z     "x-client-ver": "5.2.0.0"
2018-09-12T12:57:04.088762220Z   }
2018-09-12T12:57:04.088765620Z }
2018-09-12T12:57:04.088768920Z 
2018-09-12T12:57:04.223151567Z [12:57:04 Debug] IdentityServer4.Services.DefaultConsentService
2018-09-12T12:57:04.223165167Z Client is configured to not require consent, no consent is required
2018-09-12T12:57:04.223192167Z 
2018-09-12T12:57:04.223466865Z [12:57:04 Debug] IdentityServer4.ResponseHandling.AuthorizeResponseGenerator
2018-09-12T12:57:04.223476264Z Creating Hybrid Flow response.
2018-09-12T12:57:04.223479864Z 
2018-09-12T12:57:04.364702253Z [12:57:04 Debug] IdentityServer4.EntityFramework.Stores.PersistedGrantStore
2018-09-12T12:57:04.364715753Z QdTa1gOWgJjAgiGP99GaUJyC2bPoBsV8oxZXv6+GnIY= not found in database
2018-09-12T12:57:04.364719953Z 
2018-09-12T12:57:04.621719048Z [12:57:04 Debug] IdentityServer4.ResponseHandling.AuthorizeResponseGenerator
2018-09-12T12:57:04.621734248Z Creating Implicit Flow response.
2018-09-12T12:57:04.621756348Z 
2018-09-12T12:57:04.622154145Z [12:57:04 Debug] IdentityServer4.Services.DefaultClaimsService
2018-09-12T12:57:04.622163445Z Getting claims for identity token for subject: 6f8aded4-5452-404d-8952-72be464c22d7 and client: BreezeWebClient
2018-09-12T12:57:04.622187844Z 
2018-09-12T12:57:04.622495642Z [12:57:04 Debug] IdentityServer4.Services.DefaultClaimsService
2018-09-12T12:57:04.622600841Z In addition to an id_token, an access_token was requested. No claims other than sub are included in the id_token. To obtain more user claims, either use the user info endpoint or set AlwaysIncludeUserClaimsInIdToken on the client configuration.
2018-09-12T12:57:04.622608941Z 
2018-09-12T12:57:04.624513325Z [12:57:04 Information] IdentityServer4.Events.DefaultEventService
2018-09-12T12:57:04.624523724Z {
2018-09-12T12:57:04.624527724Z   "Name": "Token Issued Success",
2018-09-12T12:57:04.624531724Z   "Category": "Token",
2018-09-12T12:57:04.624535524Z   "EventType": "Success",
2018-09-12T12:57:04.624539224Z   "Id": 2000,
2018-09-12T12:57:04.624542824Z   "ClientId": "BreezeWebClient",
2018-09-12T12:57:04.624546624Z   "ClientName": "Breeze Web Client",
2018-09-12T12:57:04.624614324Z   "RedirectUri": "http://breezeonline.ng/signin-oidc",
2018-09-12T12:57:04.624621824Z   "Endpoint": "Authorize",
2018-09-12T12:57:04.624625624Z   "SubjectId": "6f8aded4-5452-404d-8952-72be464c22d7",
2018-09-12T12:57:04.624637623Z   "Scopes": "openid profile BreezeApi offline_access",
2018-09-12T12:57:04.624641423Z   "GrantType": "hybrid",
2018-09-12T12:57:04.624645123Z   "Tokens": [
2018-09-12T12:57:04.624648823Z     {
2018-09-12T12:57:04.624652423Z       "TokenType": "id_token",
2018-09-12T12:57:04.624707223Z       "TokenValue": "****m2yQ"
2018-09-12T12:57:04.624714123Z     },
2018-09-12T12:57:04.624717823Z     {
2018-09-12T12:57:04.624721323Z       "TokenType": "code",
2018-09-12T12:57:04.624725023Z       "TokenValue": "****b585"
2018-09-12T12:57:04.624729423Z     }
2018-09-12T12:57:04.624733123Z   ],
2018-09-12T12:57:04.624736623Z   "ActivityId": "0HLGOLLUFJS8Q:00000001",
2018-09-12T12:57:04.624740323Z   "TimeStamp": "2018-09-12T12:57:04Z",
2018-09-12T12:57:04.624744523Z   "ProcessId": 1,
2018-09-12T12:57:04.624748122Z   "LocalIpAddress": "::ffff:xx.yy.aa.abc:80",
2018-09-12T12:57:04.624805822Z   "RemoteIpAddress": "::ffff:xx.yy.aa.abc"
2018-09-12T12:57:04.624812822Z }
2018-09-12T12:57:04.624816222Z 
2018-09-12T12:57:04.629383683Z [12:57:04 Information] IdentityServer4.Endpoints.AuthorizeEndpoint
2018-09-12T12:57:04.629420382Z Authorize endpoint response
2018-09-12T12:57:04.629458082Z {
2018-09-12T12:57:04.629463682Z   "SubjectId": "6f8aded4-5452-404d-8952-72be464c22d7",
2018-09-12T12:57:04.629467982Z   "ClientId": "BreezeWebClient",
2018-09-12T12:57:04.629471982Z   "RedirectUri": "http://breezeonline.ng/signin-oidc",
2018-09-12T12:57:04.629654980Z   "State": "CfDJ8N8_2AAgVOJOrHQ43U4UbLtsOv9jds_esgaeJ0OojAk7D5Ue_NjdR8049p2dl1IfR9l1Y4gozSqxu2qhnjHyDrxRyRVLctq90AnIdu5d4UREbYN14Kv5u96BNc8NDuFvW-GM7ufuHRCTKa0_C2Xf1-O7cmZ4lopgGtmnyVMUfZhTWWHl2pC5sWzvE3sK8gxs7szp3fkndoqBZyuqvjyRWpX8-prEgWZQu_2S0X-6Tb5LNFkxZq7hPS_uqNCZZBZY6Kubk6spgEqPlC1aVgJA4lzmf9DPme2p4hfqFl_iiOX-p78cbrRbNCYY4AyS9nMyMoGloGzrRTABi-lTHk3cPZ8",
2018-09-12T12:57:04.629663480Z   "Scope": "openid profile BreezeApi offline_access"
2018-09-12T12:57:04.629667480Z }
2018-09-12T12:57:04.629670880Z 

Вы также можете посмотреть конфигурацию IdentityServer в Startup для IdentityServer и веб-клиента

IdentityServer Startup.cs

var builder = services.AddIdentityServer(options =>
{
    if (!Environment.IsDevelopment())
        options.PublicOrigin = Configuration["HostSettings:RemotePublicOrigin"];
    options.Events.RaiseErrorEvents = true;
    options.Events.RaiseInformationEvents = true;
    options.Events.RaiseFailureEvents = true;
    options.Events.RaiseSuccessEvents = true;
    options.Authentication.CookieLifetime = TimeSpan.FromSeconds(1800);
})
    //.AddSigningCredential(cert)
    .AddConfigurationStore(options =>
    {
        options.ConfigureDbContext = db => db.UseNpgsql(connectionString,
            sql => sql.MigrationsAssembly(migrationsAssembly));
    })
    .AddOperationalStore(options =>
    {
        options.ConfigureDbContext = db =>
            db.UseNpgsql(connectionString,
                sql => sql.MigrationsAssembly(migrationsAssembly));
    })
    .AddAspNetIdentity<ApplicationUser>()
    .AddConfigurationStoreCache()
    .AddProfileService<OAuthProfileService>();

if (Environment.IsDevelopment())
{
    builder.AddDeveloperSigningCredential();
}
else
{

    X509Certificate2 cert = null;
    using (X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser))
    {
        certStore.Open(OpenFlags.ReadOnly);
        X509Certificate2Collection certCollection = certStore.Certificates.Find(
            X509FindType.FindByThumbprint,
            "**Retracted thumbprint**",
            false);
        // Get the first cert with the thumbprint
        if (certCollection.Count > 0)
        {
            cert = certCollection[0];
            Log.Logger.Information($"Successfully loaded cert from registry: {cert.Thumbprint}");
        }
    }
    if (cert == null)
    {
        cert = new X509Certificate2(Path.Combine(Environment.ContentRootPath, "5f2d3bb6331537975a0a195996182c34.pfx"), "breeze");
        Log.Logger.Information($"Falling back to cert from file. Successfully loaded: {cert.Thumbprint}");
    }

    builder.AddSigningCredential(cert);
}

Конфигурация клиента

{
    "ClientId": "BreezeWebClient",
    "ClientName": "Breeze Web Client",
    "RequireConsent": false,
    "RedirectUris": [
      "https://breezeonline.ng/signin-oidc",
      "http://breezeonline.ng/signin-oidc"
    ],
    "properties": {
      "version": "20"
    },
    "FrontChannelLogoutUri": "https://breezeonline.ng/signout-oidc",
    "PostLogoutRedirectUris": [
      "https://breezeonline.ng/signout-callback-oidc",
      "http://breezeonline.ng/signout-callback-oidc"
    ],
    "AllowOfflineAccess": true,
    "AllowedScopes": [
      "openid",
      "profile",
      "email",
      "address",
      "phone",
      "offline_access",
      "BreezeApi",
      "openidc"
    ],
    "AccessTokenLifetime": 1800,
    "IdentityTokenLifetime": 1800,
    "AbsoluteRefreshTokenLifetime": 1800,
    "SlidingRefreshTokenLifetime": 1800
  }

Для RedirectUris и PostLogoutRedirectUris мне пришлось включить http://для обоих, потому что он выбрасывал RequireHttpsMetadata ошибку клиента после установки RequireHttpsMetadata на true.

Веб-клиент Startup.cs

services.AddAuthentication(options =>
{
    options.DefaultScheme = "Cookies";
    options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
    options.SignInScheme = "Cookies";
    options.Authority = idSvrUrl;
    if (Environment.IsDevelopment())
        options.RequireHttpsMetadata = false;
    else
        options.RequireHttpsMetadata = true;
    options.ClientId = "BreezeWebClient";
    options.ClientSecret = "**My Secret**";

    options.ClaimActions.Add(new RoleClaimAction());
    options.ClaimActions.Add(new FullNameClaimAction());
    options.ClaimActions.Add(new RoleSubClaimAction());
    options.ClaimActions.Add(new CompanyIdClaimAction());

    options.ResponseType = OidcConstants.ResponseTypes.CodeIdToken;

    options.SaveTokens = true;
    options.GetClaimsFromUserInfoEndpoint = true;

    options.Scope.Add("BreezeApi");
    options.Scope.Add("offline_access");

    options.TokenValidationParameters = new TokenValidationParameters
    {
        NameClaimType = JwtClaimTypes.Name,
        RoleClaimType = JwtClaimTypes.Role
    };
});

Так что это. Я не знаю, где я ошибся. Мне не нужно упоминать, что это работает безупречно на локальном хосте. Пожалуйста помоги.

  • 0
    Я пытался открыть ваш сайт, но ничего не сделал в адресной строке: https://applicationhost.breezeonline.ng/account/login?returnUrl=/connect/authorize/callback?client_id=BreezeWebClient&redirect_uri=http://breezeonline.ng/signin-oidc&response_type=codeid_token&scope=openidprofileBreezeApioffline_access&response_mode=form_post&nonce=636724122191637437.MjBjZjkxN2UtYmVjMi00NzVhLTllZmMtOGRkYzUxYmEyNGM3N2I5NDA1ZjYtMTQ0MC00YTc2LTk4MTUtOTI0MjkxMDA2MTNi&state=CfDJ8N8_WAY_TOO_LONG_FOR_COMMENT&x-client-SKU=ID_NETSTANDARD1_4&x-client-ver=5.2.0.0
  • 0
    Кажется, что многое происходит только для достижения страницы входа в систему https://breezeonline.ng/signin-oidc
Показать ещё 4 комментария
Теги:
azure
asp.net-core
identityserver4

2 ответа

1
Лучший ответ

Наконец-то я получил решение. Проблема была просто проблемой перенаправления. Все, что я сделал, это удалить http://breezeonline.ng/signin-oidc из файла конфигурации клиента и добавить следующий код в startup.cs в проект MVC под app.UseHttpsRedirection() и app.UseAuthentication()

app.UseForwardedHeaders(new ForwardedHeadersOptions
{
   ForwardedHeaders = ForwardedHeaders.XForwardedProto
});

Как раз так, моя битва с лазурным развертыванием с 2 недель была выиграна.

0

у меня возникла похожая проблема при попытке подключения с помощью клиента Xamarin Forms. Мой URL перенаправления похож на com.abc://callback. Как посмотреть журналы на сервере в Azure?

Ещё вопросы

Сообщество Overcoder
Наверх
Меню