从 API 中访问 Auth0 登录用户?

Posted

技术标签:

【中文标题】从 API 中访问 Auth0 登录用户?【英文标题】:Accessing Auth0 logged in user from within an API? 【发布时间】:2021-09-30 02:15:51 【问题描述】:

我有一个 React 应用程序,它使用 auth0 和一个 express API 服务器。

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

使用任何请求将信息发送到 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;

【问题讨论】:

【参考方案1】:

所以我不知道用户管理 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")
)

【讨论】:

以上是关于从 API 中访问 Auth0 登录用户?的主要内容,如果未能解决你的问题,请参考以下文章

Strapi,使用 Auth0 访问 Strapi 中的用户数据

如何在 Symfony 中访问已登录的 Auth0 用户的电子邮件地址?

允许使用 Auth0 保护的 API 的开发人员访问令牌

是否可以以某种方式使用recaptcha和auth0来避免让用户登录但仍然有令牌?

auth0 从角度 2 获取所有用户

Auth0 - 规则 & 组 && 用户管理