Law*_*Law 5 jwt next.js apollo-client next-auth
我正在创建一个 nextjs 应用程序,它利用 NextAuth 进行身份验证并生成具有自定义编码和解码的 JWT。传递 hasura 声明需要自定义编码和解码。
如何将该 jwt 传递给 apollo 以便附加带有所述 jwt 的请求标头,以便 hasura 验证我的请求?我看了几个例子,人们从本地存储中提取令牌,但 NEXTAuth 将 JWT 存储在 cookie 中。我不知道如何访问它。我尝试将令牌添加到我的会话中并使用 NextAuth getSession() 方法读取会话,但它返回 null。
lib\apollo.ts
import {
ApolloClient,
InMemoryCache,
ApolloLink,
HttpLink,
concat,
} from '@apollo/client'
import { WebSocketLink } from '@apollo/client/link/ws'
import { getSession } from 'next-auth/react'
// TODO - Replace URIs with environment variables
async function sesFunc() {
const sesh = await getSession()
return sesh
}
var ses = sesFunc()
console.log(`Session in apollo: ${JSON.stringify(ses)}`)
const graphLink = new HttpLink({
uri: 'http://localhost:8080/v1/graphql',
})
//GraphQL Relay Endpoint
const relayLink = new HttpLink({
uri: 'http://localhost:8080/v1beta1/relay',
})
const wsLink =
typeof window !== 'undefined'
? new WebSocketLink({
uri: 'ws://localhost:8080/v1/graphql',
options: {
reconnect: true,
},
})
: undefined
const authMiddleware = new ApolloLink((operation, forward) => {
//const { data: session, status } = useSession()
// console.log(`AuthMiddle Session: ${session}`)
operation.setContext(({ headers = {} }) => ({
headers: {
...headers,
Authorization:
'Bearer <token>',
},
}))
return forward(operation)
})
const apolloClient = new ApolloClient({
link: concat(
authMiddleware,
ApolloLink.split(
(operation) => operation.getContext().clientName === 'relayLink',
relayLink,
ApolloLink.split(
(operation) => operation.getContext().clientName === 'graphLink',
graphLink,
wsLink
)
)
),
cache: new InMemoryCache(),
})
export default apolloClient
Run Code Online (Sandbox Code Playgroud)
_app.tsx
import '../styles/globals.css'
import type { AppProps } from 'next/app'
import { SessionProvider } from 'next-auth/react'
import IdleTimerContainer from '../components/IdleTimerContainer'
import Layout from '../components/Layout'
import { ApolloProvider } from '@apollo/client'
import apolloClient from '../lib/apollo'
function MyApp({ Component, pageProps: { session, ...pageProps } }: AppProps) {
return (
<SessionProvider session={session}>
<ApolloProvider client={apolloClient}>
<Layout>
<Component {...pageProps} />
</Layout>
</ApolloProvider>
<IdleTimerContainer />
</SessionProvider>
)
}
export default MyApp
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
914 次 |
| 最近记录: |