首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >oidc-client-js总是重定向到登录页面。

oidc-client-js总是重定向到登录页面。
EN

Stack Overflow用户
提问于 2021-11-19 09:39:39
回答 2查看 853关注 0票数 0

我正在从事一个项目,以在react (带有PKCE的授权代码)上设置OIDC身份验证。我在和oidc-client-js库合作。我的代码运行良好,但经过身份验证后,我再次被重定向到登录模式。我看了一下反应路由器,但那似乎不是它。我正在考虑一个异步问题,但我似乎无法摆脱它。你能帮帮我吗?

提前感谢

我的配置

代码语言:javascript
复制
const userManager = new UserManager({
authority: identityProvider,
client_id: window.REACT_APP_CLIENT_ID,
response_type: 'code',
redirect_uri: 'http://localhost:3000/auth-callback',
scope: 'openid',
loadUserInfo: false,
revokeAccessTokenOnSignout: true,
filterProtocolClaims: true,
monitorSession: true,
metadata: {
    issuer: identityProvider,
    jwks_uri: `${identityProvider}/pf/JWKS`,
    end_session_endpoint: `${identityProvider}/idp/startSLO.ping`,
    authorization_endpoint: `${identityProvider}/as/authorization.oauth2`,
    token_endpoint: `${identityProvider}/as/token.oauth2`,
    userinfo_endpoint: `${identityProvider}/idp/userinfo.openid`,
    revocation_endpoint: `${identityProvider}/as/revoke_token.oauth2`,
    introspection_endpoint: `${identityProvider}/as/introspect.oauth2`
}

})

我的AuthProvider

代码语言:javascript
复制
import React, { useEffect, useState } from 'react'

import PropTypes from 'prop-types'

import IdentityProvider from './bo-authentication/context/IdentityProvider'
import useCompleteAuthentication from './useCompleteAuthentication'
import useStartAuthentication from './useStartAuthentication'

const AuthProvider = ({ children }) => {
const [ready, setReady] = useState(false)

useStartAuthentication()
const boAuthentication = useCompleteAuthentication()
console.log(boAuthentication)

useEffect(() => {
    setReady(boAuthentication.token !== undefined)
}, [boAuthentication.token])

if (!ready) return null

return <IdentityProvider value={boAuthentication}>{children}</IdentityProvider>
}

AuthProvider.propTypes = { children: PropTypes.node }

export default AuthProvider

我的服务

代码语言:javascript
复制
export const login = async () => {
await userManager
    .signinRedirect({ redirectUri: window.location.href })
    .then(() => {
        console.log(`User login successful`)
    })
    .catch((error) => console.error(`An error occur during user login flow ${error}`))
}

export const completeAuthentication = once(
async (updater: UserAuthenticationUpdater = () => undefined): Promise<void> => {
    await userManager
        .signinRedirectCallback()
        .then((user: User | null) => {
            if (!user?.access_token) {
                console.warn('The identity provider have not provide the access token')
            } else {
                const userAuthentication = getUserAuthentication(user)
                updater(userAuthentication)
                const millisecondsBeforeExpiration = getMillisecondsBeforeExpiration(
                    userAuthentication.exp as number
                )
                console.log(`The time before refresh token is ${millisecondsBeforeExpiration}`)
            }
        })
        .catch(() => console.error('An error occur during the handle callback from the identity provider'))
}

)

钩子

代码语言:javascript
复制
import { useContext, useEffect, useState } from 'react'
import { completeAuthentication } from '..'
import AuthenticationContext from '../context/AuthenticationContext'
import { UserAuthentication } from '../model/userAuthentication'

const useBoAuthentication = (): UserAuthentication => {
const authenticationContextValue = useContext(AuthenticationContext)

const [authenticationContext, setAuthenticationContext] = useState<UserAuthentication>(authenticationContextValue)

useEffect(() => {
    if (authenticationContextValue.authenticated) return
    completeAuthentication(setAuthenticationContext)
}, [authenticationContextValue.authenticated])

return authenticationContext

}

导出默认useBoAuthentication

钩子

代码语言:javascript
复制
import { useContext, useEffect } from 'react'
import AuthenticationContext from '../context/AuthenticationContext'
import { login } from '../index'

const useStartAuthentication = () => {
const authenticationContextValue = useContext(AuthenticationContext)

useEffect(() => {
    if (authenticationContextValue.authenticated) return
    login()
}, [authenticationContextValue.authenticated])
}

export default useStartAuthentication
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-11-19 14:15:01

您需要根据signInRedirect是否返回任何内容,对何时调用userManager.getUser进行更严格的控制。首先,我要从以下几个方面着手:

  • 当页面加载时,将登录状态呈现为屏幕上的标签: true或false
  • 使用临时登录按钮触发重定向中的签名,而不是在useEffect中自动执行

一旦这是可靠的,你可以把onLoad自动重定向。如果有帮助的话,下面是我的一些代码来比较--您也可以很容易地运行这个代码示例。

票数 0
EN

Stack Overflow用户

发布于 2021-11-20 13:02:56

当我检查userManager实例中的用户时,它可以工作。我认为我的验证在钩子级别上已经足够了。

非常感谢您的效率和反应性。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70032731

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档