0

我们在 asp.net mvc 应用程序中使用基于 OpenIdConnect 的身份验证。初始登录工作正常。但是,当我们使用 Ajax 调用来调用操作方法时,用户将作为未通过身份验证的方式出现。我签入了自定义授权 -HttpContext.Request.IsAuthenticated是假的。

我检查了cookie ".AspNet.Cookies",它具有价值。为什么开放 ID 未对用户进行身份验证。

下面是我的验证码

app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = AuthenticationConfig.ClientId,
                Authority = AuthenticationConfig.AADInstance + AuthenticationConfig.TenantId,
                PostLogoutRedirectUri = AuthenticationConfig.PostLogoutRedirectURI,
                RedirectUri = AuthenticationConfig.RedirectUri,
                Scope = OpenIdConnectScope.OpenIdProfile,
                ResponseType = OpenIdConnectResponseType.Code,
                SaveTokens = true,

                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(AuthenticationConfig.ClientSecret)),
                    ValidateIssuer = true,
                    ValidIssuer = AuthenticationConfig.AADInstance + AuthenticationConfig.TenantId + "/v2.0",
                },

                SignInAsAuthenticationType = "Cookies",

                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    // when an auth code is received...
                    AuthorizationCodeReceived = OnAuthorizationCodeReceived,
                    AuthenticationFailed = OnAuthenticationFailed,
                    SecurityTokenValidated = async n =>
       {
           var nid = new ClaimsIdentity(n.AuthenticationTicket.Identity);

           //var claimsIdentity = filterContext.HttpContext.User.Identity as ClaimsIdentity;
           var user = nid.Claims.Where(r => r.Type == PreferedUserNameClaimType).Select(v => v.Value).FirstOrDefault();

           var userRolesroles = GetRolesForUser(user);

           //nid.AddClaim(new Claim("expires_at", DateTimeOffset.Now.AddSeconds(int.Parse(n.ProtocolMessage.ExpiresIn)).ToString()));

           userRolesroles.ToList().ForEach(ui => nid.AddClaim(new Claim(ClaimTypes.Role, ui)));

           // keep the id_token for logout
           nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));

           // add access token for sample API
           nid.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken));

           n.AuthenticationTicket = new AuthenticationTicket(
              nid,
              n.AuthenticationTicket.Properties);

           UserService.SetUserInformation(user);

       },
                    RedirectToIdentityProvider = ctx =>
                    {
                        bool isAjaxRequest = (ctx.Request.Headers != null && ctx.Request.Headers["X-Requested-With"] == "XMLHttpRequest");

                        if (ctx.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication)
                        {
                            if (isAjaxRequest && ctx.Response.StatusCode == (int)HttpStatusCode.Unauthorized)
                            {
                                ctx.Response.Headers.Remove("Set-Cookie");
                                ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                                ctx.HandleResponse();
                                return Task.FromResult(0);
                            }
                        }
                        return Task.FromResult(0);

                    }
                }

            });


    }
4

1 回答 1

0

通常在 asp.net 中,ApiControllers 没有控制器身份验证的概念。根据构建方式,您需要添加一个带有不记名访问令牌的授权标头,以让 API 了解经过身份验证的用户。

于 2020-01-09T19:27:28.137 回答