有时在/ signin-oidc

如何解决有时在/ signin-oidc

我在.NET Framework 4.6.2中实现了OpenIdConnect。大部分时间都可以正常工作,但有时在/ signin-oidc上给出404。登录后从IdentityServer4重定向回调用网站时。

如果我从浏览器的网址中删除了/ signin-oidc并按Enter,则我已经登录。如果找不到/ signin-oidc,则不会发生这种情况,因为那是在我相信的网站。

我将.Net Core 3.1中的IdentityServer4(具有AspNetCore身份)实现用作授权。

该网站使用以下程序包运行.NET Framework 4.6.2:

<package id="Microsoft.IdentityModel.JsonWebTokens" version="6.6.0" targetFramework="net462" />
<package id="Microsoft.IdentityModel.Logging" version="6.6.0" targetFramework="net462" />
<package id="Microsoft.IdentityModel.Protocols" version="6.6.0" targetFramework="net462" />
<package id="Microsoft.IdentityModel.Protocols.OpenIdConnect" version="6.6.0" targetFramework="net462" />
<package id="Microsoft.IdentityModel.Tokens" version="6.6.0" targetFramework="net462" />
<package id="Microsoft.Owin" version="4.1.0" targetFramework="net462" />
<package id="Microsoft.Owin.Host.SystemWeb" version="4.1.0" targetFramework="net462" />
<package id="Microsoft.Owin.Security" version="4.1.0" targetFramework="net462" />
<package id="Microsoft.Owin.Security.Cookies" version="4.1.0" targetFramework="net462" />
<package id="Microsoft.Owin.Security.OpenIdConnect" version="4.1.0" targetFramework="net462" />

我用以下代码配置了openId连接:

// Clear default.
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

// register global exception middle ware to handle owin exceptions
app.Use<OwinExceptionMiddleware>();

app.UseCookieAuthentication(
new CookieAuthenticationOptions
{
  AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,LogoutPath = new PathString("/Login.aspx"),LoginPath = new PathString("/Logout.aspx"),// We can not use a sliding expiration because some user controls open a request every minute,so with sliding window the cookie would never expire.
  ExpireTimeSpan = TimeSpan.FromMinutes(timeOutDuration),SlidingExpiration = false,CookieSecure = CookieSecureOption.SameAsRequest,// Create a cookie authentication provider so we can log when something happens.
  Provider = new CookieAuthenticationProvider
  {
    OnApplyRedirect = context => { _logger.Debug($"Redirect to {context.RedirectUri} from {context.Request.Uri}"); },OnValidateIdentity = context =>
    {
      // redirect to re-login for the automatic calls

      var seconds = Math.Round(context.Properties.ExpiresUtc?.Subtract(DateTimeOffset.UtcNow).TotalSeconds ?? double.MaxValue,MidpointRounding.AwayFromZero);
      if (seconds < 10)
        _logger.Debug($"Authentication cookie expires in {seconds} seconds at {DateTime.Now.AddSeconds(seconds)}");

      return Task.CompletedTask;
    },OnResponseSignedIn = context => { _logger.Debug($"ResponseSignedIn with {context.Identity?.Name} from {context.Request.Uri}"); },OnResponseSignIn = context => { _logger.Debug($"ResponseSignIn with {context.Identity?.Name} from {context.Request.Uri}"); },OnResponseSignOut = context => { _logger.Debug($"ResponseSignOut from {context.Request.Uri}"); },OnException = context => { _logger.Error(context.Exception,"Could not autenticate with CookieAuthentication"); }
  },// So replace the standard cookie manager because of the fact the application also set cookies
  // see https://github.com/aspnet/AspNetKatana/wiki/System.Web-response-cookie-integration-issues for explanation.
  CookieManager = new SystemWebChunkingCookieManager {ChunkSize = _cookieChunckSize}
});

app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
// Open Id configuration
AuthenticationType = OpenIdConnectAuthenticationDefaults.AuthenticationType,SignInAsAuthenticationType = CookieAuthenticationDefaults.AuthenticationType,// Authority 
Authority = _authorityUrl,RequireHttpsMetadata = false,// Client
ClientId = _clientId,ClientSecret = _clientSecret,// Call back
RedirectUri = _clientRedirectUri,PostLogoutRedirectUri = _clientPostLogoutRedirectUri,// OpenID Connect Hybrid Flow,PKCE not supported in .Net Framework only in .Net Code 3.
ResponseType = OpenIdConnectResponseType.CodeIdToken,// Set scope
Scope = "openid profile role email lastlogindate IdentityServerApi id offline_access",// keeps id_token smaller
SaveTokens = true,// make sure the ExpireTimeSpan is used.
UseTokenLifetime = false,// So replace the standard cookie manager because of the fact the application also set cookies
// see https://github.com/aspnet/AspNetKatana/wiki/System.Web-response-cookie-integration-issues for explanation.
CookieManager = new SystemWebChunkingCookieManager {ChunkSize = _cookieChunckSize},// set default claim names.
TokenValidationParameters = new TokenValidationParameters
{
  NameClaimType = NameClaimType,RoleClaimType = RoleClaimType
},Notifications = new OpenIdConnectAuthenticationNotifications
{
  // on receiving authorization code get user information (profile and roles etc) and add to Claims Identity
  AuthorizationCodeReceived = async n =>
  {
    // retrieve a http client.
    var client = HttpClientFactory.GetClient(_authorityUrl);

    // use the code to get the access and refresh token
    var tokenResponse = await client.RequestAuthorizationCodeTokenAsync(new AuthorizationCodeTokenRequest
    {
      Address = _authorityUrl + AuthenticationService.TokenEndpoint,GrantType = OpenIdConnectGrantTypes.AuthorizationCode,ClientId = _clientId,RedirectUri = _clientRedirectUri,Code = n.ProtocolMessage.Code
    });

    _logger.Debug($"Access token expires in {tokenResponse.ExpiresIn} seconds at {DateTime.Now.AddSeconds(tokenResponse.ExpiresIn)}");

    if (tokenResponse.IsError)
    {
      _logger.Error($"Could not retrieve access_token: {tokenResponse.Error}");
      return;
    }

    // use the access token to retrieve claims from user info
    var userInfoResponse = await client.GetUserInfoAsync(new UserInfoRequest
    {
      Address = _authorityUrl + AuthenticationService.UserInfoEndpoint,Token = tokenResponse.AccessToken
    });

    // create new identity
    var id = new ClaimsIdentity(n.AuthenticationTicket.Identity.AuthenticationType,NameClaimType,RoleClaimType);

    // add user properties to claims
    if (userInfoResponse.IsError)
    {
      _logger.Error($"Could not retrieve user information: {userInfoResponse.Error}");
      return;
    }

    // set user information (in Microsoft format) in claims
    if (userInfoResponse.Claims.Any())
      id.AddClaims(userInfoResponse.GetMicrosoftClaims());

    // add tokens to the claims collection
    if (!string.IsNullOrEmpty(tokenResponse.AccessToken))
      id.AddClaim(new Claim(OpenIdConnectParameterNames.AccessToken,tokenResponse.AccessToken));

    if (!string.IsNullOrEmpty(n.ProtocolMessage.IdToken))
      id.AddClaim(new Claim(OpenIdConnectParameterNames.IdToken,n.ProtocolMessage.IdToken));

    if (!string.IsNullOrEmpty(tokenResponse.RefreshToken))
      id.AddClaim(new Claim(OpenIdConnectParameterNames.RefreshToken,tokenResponse.RefreshToken));

    if (tokenResponse.ExpiresIn != default)
    {
      var expiresAt = DateTime.UtcNow + TimeSpan.FromSeconds(tokenResponse.ExpiresIn);
      id.AddClaim(new Claim("expires_at",expiresAt.ToString("o",CultureInfo.InvariantCulture)));
    }

    // add profile to claims
    var userId = id.GetClaim<string>("id");
    if (string.IsNullOrEmpty(userId))
    {
      _logger.Error("No user id found in the claims,which should not happen.");
      return;
    }

    // retrieve profile
    var apiClient = IdentityServerClientFactory.GetApiClient();
    var profile = await apiClient.GetProfileAsync(new ProfileRequest
      {Token = tokenResponse.AccessToken,UserId = userId});

    if (profile == null)
    {
      _logger.Error($"Profile is null for user {userId},which should not happen.");
      return;
    }

    id.AddClaims(profile.ToClaims());

    // create a new authentication  ticket.
    n.AuthenticationTicket = new AuthenticationTicket(
      new ClaimsIdentity(id.Claims,n.AuthenticationTicket.Identity.AuthenticationType,RoleClaimType),n.AuthenticationTicket.Properties);
  },// Set IdTokenHint on logout,so we can logout on Identity Server.
  RedirectToIdentityProvider = n =>
  {
    if (n.ProtocolMessage.RequestType != OpenIdConnectRequestType.Logout)
      return Task.CompletedTask;


    var idToken = n.OwinContext.Authentication.User.FindFirst("id_token")?.Value;
    n.ProtocolMessage.IdTokenHint = idToken;

    return Task.CompletedTask;
  },// Log on authentication failed.
  AuthenticationFailed = n =>
  {
    // hack for: Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectProtocolInvalidNonceException: IDX21323: RequireNonce is '[PII is hidden]'
    if (n.Exception.Message.Contains("IDX21323"))
    {
      n.SkipToNextMiddleware();
      return Task.FromResult(0);
    }

    _logger.Error(n.Exception,"Could not autenticate with OpenIdConnect");

    return Task.CompletedTask;
  }
}
});

发生404时的标头如下:

**General:**
Request URL: https://ipp***.***.nl:*3/signin-oidc
Request Method: POST
Status Code: 404 
Remote Address: 89.**.**.**:*3
Referrer Policy: no-referrer

**Response Headers:**
access-control-allow-origin: *
content-length: 1245
content-type: text/html
date: Tue,11 Aug 2020 08:45:20 GMT
server: Microsoft-IIS/10.0
status: 404

**Request Headers:**
:authority: ipp***.***.nl:*3
:method: POST
:path: /signin-oidc
:scheme: https
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
accept-encoding: gzip,deflate,br
accept-language: en-US,en;q=0.9,nl;q=0.8
cache-control: max-age=0
content-length: 1483
content-type: application/x-www-form-urlencoded
cookie: _ga=GA1.2.1680329711.1591349847; ASP.NET_SessionId=j4kjjmlbas2ujfdcgewwe1yz
origin: null
sec-fetch-dest: document
sec-fetch-mode: navigate
sec-fetch-site: same-site
sec-fetch-user: ?1
upgrade-insecure-requests: 1
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/84.0.4147.105 Safari/537.36

**Form Data:**

code: lNFyWNLLi1QomK....
id_token: eyJhbGciOiJSUzI1NiIsImtpZCI6...
scope: openid profile role email lastlogindate id IdentityServerApi offline_access
state: OpenIdConnect.AuthenticationProperties=VxS5f80S8nNTcArI8n91rOOf58R8BUn3xHPVdz....

我一生都无法弄清为什么有时会抛出404。 Identity Server日志中没有错误,网站日志中也没有错误,因为该呼叫永远不会因为404而到达那里。

更新

在Windows 10 Enterprise 2015 LTSB上的旧浏览器IE11(版本11.0.10240.18638)上,该浏览器是该操作系统的最新浏览器。我一直在/ signin-oidc上看到404。我发现在调用/ signin-oidc时不存在OpenIdConnect.nonce cookie,因此在该浏览器中cookie不会返回IdentityServer4或丢失。无法将提琴手附加到该版本的IE11上以弄清楚情况是什么。

解决方法

如果您遇到的错误取决于浏览器和浏览器版本,则可能是SameSite Cookie问题。在各种浏览中,SameSite的实现都存在很多错误。真是一团糟!

有关解决此问题的起点,请参见此article

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-