【发布时间】:2017-04-04 23:43:48
【问题描述】:
我正在使用auth0 来验证我对单页应用程序(基于 React 构建)的登录。我主要使用基本 API 调用(列出 here)。
我正在使用的流程是:
当用户在我的应用程序的登录页面上输入它们时获取用户名/电子邮件和密码
使用这些值向/oauth/ro 发送 POST 请求 - 这是代码:
export const login = (params, err) => {
if (err) return err
const {email, password} = params
const {AUTH0_CLIENT_ID, AUTH0_DOMAIN} = process.env
return fetch(`${AUTH0_DOMAIN}/oauth/ro`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
'client_id': AUTH0_CLIENT_ID,
'username': email,
'password': password,
'connection': 'Username-Password-Authentication',
'grant_type': 'password',
'scope': 'openid',
'device': '',
'id_token': ''
})
})
.then(response => response.json())
.then(json => {
const {id_token, access_token} = json
setCookieValue('id_token', id_token) // utility function I wrote
return getProfile(access_token)
.then(data => {
const {user_id, email: emailAddress, picture, name} = data
return {id_token, user_id, emailAddress, picture, name}
})
})
.catch(error => console.log(`ERROR: ${error}`))
}
这都是通过 Redux 发送的,并且用户已经登录(假设用户名/密码正确)。
但是,我试图弄清楚在刷新页面/返回应用程序时如何保持登录。我将id_token(这是一个JWT)保存在浏览器的cookies中,并且可以在应用程序呈现服务器端时获取它。我可以解码 JWT 并获取有效负载(sub 是来自 auth0 的用户 ID)。但是,要获取配置文件数据,我需要 Auth0 在使用 /oauth/ro POST 请求时提供的 access_token。显然,如果 JWT 令牌已过期,那么它只会拒绝它并让用户退出。
这是我解码 JWT 的代码(发生在应用程序渲染上):
const ID_TOKEN = req.cookies.id_token || false
if (ID_TOKEN) {
verifyJwt(ID_TOKEN, (err, decoded) => {
if (err) { console.log(`JWT Verification error: ${err}`) }
else {
const {sub} = decoded
getProfile(sub).then(data => store.dispatch(fetchUserDetails(data))) // fails as `sub` (the user id) is not the `access_token` which it requires
}
})
}
我尝试再次使用/oauth/ro 调用,但这次指定"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer" 并使用从cookie 中检索到的id_token,并指定device。但是,当我进行此调用时,我从 Auth0 收到此错误:
{
"error": "invalid_request",
"error_description": "there is not an associated public key for specified client_id/user_id/device"
}
所以我的问题是,我需要进行什么 API 调用才能从 id_token JWT 获取 access_token?
另外,作为奖励 - 当我发出 POST 请求登录时,password 正在通过纯文本传输。发送到 auth0 时如何加密它,以便他们可以解密回来?我认为它涉及使用 auth0 提供的client_secret,但我不知道该怎么做。
【问题讨论】:
标签: javascript oauth jwt auth0