从 API 中访问 Auth0 登录用户?

托马斯·福克斯

我有一个 React 应用程序,它在快速 API 服务器旁边使用 auth0。

我的问题是,我可以从 Auth0 用户对象获取客户端中的用户信息,但是我不确定在调用安全端点时如何在 api 中访问它。

使用任何请求将信息发送到 api 似乎比在后端以某种方式使用访问令牌安全得多,但我不确定如何做,或者是否有可能。

接口服务器

const express = require('express')
const app = express()
const port = 8000
const jwt = require('express-jwt')
const cors = require('cors')

var jwtCheck = jwt({
    secret: '',
    audience: 'http://localhost:8000',
    issuer: 'https://dev-ml4yg9zg.us.auth0.com/',
    algorithms: ['HS256']
});

app.use(cors())

app.get('/unprotected',(req,res) =>{
    res.send("not secured resource")
})

app.get('/authed', jwtCheck,(req,res) =>{
    
    // GET THE DATA FOR THE LOGGED IN USER WHO MADE THE CALL
    
    res.send("secured resource")
})

app.listen(port, () =>{
    console.log(`app listening on port ${port}`)
})

反应应用程序

import React,{useEffect, useState} from 'react';
import axios from 'axios'
import {useAuth0} from '@auth0/auth0-react'

function App() {

  const [accessToken, setAccessToken] = useState(null)
  const [userMetaData, setUserMetadata] = useState(null)

  const {
      loginWithRedirect, 
      logout, 
      user, 
      isAuthenticated,
      isLoading,
      getAccessTokenSilently
  } = useAuth0()

  console.log(user)

  const getToken = async () => {
    try {
      const accessToken = await getAccessTokenSilently({
        audience: `http://localhost:8000`,
        scope: "read:current_user",
      });

      setAccessToken(accessToken)
    } catch (e) {
      console.log(e.message);
    }
  };


  const callProtected = () =>{
    axios.get('http://localhost:8000/authed',{
        headers:{
          Authorization:`Bearer ${accessToken}`
        }
      }).then(res =>{
        console.log(res.data)
      }).catch(e =>{
        console.log(e)
      })
  }

  const callUnprotected = ()=>{
    axios.get('http://localhost:8000/unprotected')
    .then(res =>{
      console.log(res.data)
    }).catch(e =>{
      console.log(e)
    })
  }

  return (
    <div className="App">
      <button onClick={() => loginWithRedirect()}>Login</button>
      <button onClick={() => logout({returnTo:window.location.origin})}>Log out</button>
      <button onClick={() => getToken()}>Get token</button>
      <button onClick={() => callUnprotected()}>Call unprotected resource</button>
      <button onClick={() => callProtected()}>Call protected resource</button>
      <div>
        User : {user?.name}
      </div>
    </div>
  );
}

export default App;

托马斯·福克斯

所以我不知道用户管理 API

为了解决在我的 API 服务器中获取用户数据以确认身份验证的问题,我解码了包含用户 ID 的 JWT 令牌服务器端,然后我在对管理 API 的调用中使用该 ID 来获取完整的用户数据。

可以在 Auth0 网站上的 API 仪表板中生成用于调用管理 API 的身份验证令牌

app.get('/authed', jwtCheck, async (req,res) =>{
    
    let token = req.headers.authorization.substring(7, req.headers.authorization.length)
    // GET THE DATA FOR THE LOGGED IN USER WHO MADE THE CALL
    var decoded = jwt_decode(token);
    console.log(decoded.sub)

    axios.get(`https://************.us.auth0.com/api/v2/users/${decoded.sub}`,{
        headers:{
            Authorization:`Bearer *`,
        }
    }).then((res) =>{
        console.log(res)
    }).catch(e =>{
        console.log(e)
    })

    res.send("secured resource")
})

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章