I am trying to connect Spartacus 3.2 with Auth0. With below config I am able to successful login from Auth0
provideConfig(<AuthConfig>{authentication: {
OAuthLibConfig: {
responseType: 'token',
redirectUri: redirectURL,
},
baseUrl: 'https://DomainName',
client_id: 'clientID',
loginUrl: '/authorize',
}})
Issue is:
How to pass accesstoken bearer token (Authorization) and idtoken in headers that is from Auth0? in every page call.
Can I please know how to solve this?
Related
I have a react native app authenticated with Auth0.
I have an API that uses react native.
When a user signs in, i take the accessToken that is given for that user, and I make request to the API with the accessToken set as the authorization header.
I do so like this:
const requestHeader = {
headers: {
Authorization: `Bearer ${accessToken}`,
}
}
axios.post(API_BASE + '/api/example/', requestHeader)
The accessToken is something short like this: aBQdd0kOvb1pNj-9XDj_C6bKWkMg9D_q
When I try to validate the request with the API, I get this error:
UnauthorizedError: jwt malformed
I know i'm getting this error because the access token isn't a JWT.
I'm validating in the API like this:
exports.checkJwt = jwt({
secret: jwksRsa.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: 'https://dev-0p1doq9r.auth0.com/.well-known/jwks.json'
}),
audience: 'ddasdsfasdfasd',
issuer: 'safsdfasdfasdfafsdf',
algorithms: ['RS256']
});
I know that accessToken needs to be transformed into a JWT on the client, BUT HOW? I have not found any documentation for this; I have also not found what other properties need to be included in the JWT for validation.
In my React Native app -- init app not Expo -- I'm trying to refresh the access_token but my POST call is failing with 401. I'm testing this functionality so I make the POST call some 30 seconds after I login so not sure if this plays a role or not.
In my initial login, I do get a refresh_token along with a valid access_token. I then tell my app to wait 30 seconds and make a POST call that looks like this:
const url = 'https://mydomain.auth0.com/oauth/token';
const postOptions = {
method: 'POST',
url: url,
headers: {
"content-type": 'application/x-www-form-urlencoded'
},
form: {
grant_type: 'refresh_token',
client_id: 'MY_CLIENT_ID',
refresh_token: 'REFRESH_TOKEN_RECEIVED_DURING_LOG_IN'
}
};
fetch(url, postOptions)
.then((response) => {
debugger;
// this is where I get response.status 401
})
Any idea what the issue is here?
Also want to mention that under my application settings, Refresh Token is checked under "Grant Types" but refresh token rotation or expiration are NOT enabled.
I figured this out and sharing it in case others need it in the future.
First, Auth0 documentation is misleading at best. They keep mentioning a regular POST call which doesn't work.
In my React Native app, I use their react-native-auth0 library. This library does offer a refreshToken() method which is what I ended up using.
Before I share the code, here are a couple of really important points:
Be sure to include offline_access in the scope of your initial authentication call for the user. Without including offline_access in your scope, you won't get a refresh_token. Once you receive it along with your access_token and id_token, store it as you'll use it many times. This brings me to the second point.
Unless you set it otherwise, your refresh_token doesn't expire. Therefore, store it some place secure and NOT just in AsyncStorage. As mentioned above, unless, you set it otherwise or it gets revoked, your refresh_token doesn't expire and you use it again and again.
With that said, here's the code. Please keep in mind that at start up, I initialize auth0 as a global variable so that I can access it in different parts of my app.
Here's what my initialization looks like in index.js:
import Auth0 from 'react-native-auth0';
global.auth0 = new Auth0({
domain: "MY_DOMAIN.auth0.com",
clientId: "MY_CLIENT_ID",
});
And here's how I use the refreshToken() method:
// First, retrieve the refresh_token you stored somewhere secure after your initial authentication call for the user
global.auth0.auth.refreshToken({ refreshToken: 'MY_REFRESH_TOKEN' })
.then(result => {
// If you're doing it right, the result will include a new access_token
})
you probably need to add the authorization header with your access_token:
const url = 'https://mydomain.auth0.com/oauth/token';
const postOptions = {
method: 'POST',
url: url,
headers: {
"content-type": 'application/x-www-form-urlencoded',
"Authorization" 'bearer '+access_token,
},
body: JSON.stringify({
grant_type: 'refresh_token',
client_id: 'MY_CLIENT_ID',
refresh_token: 'REFRESH_TOKEN_RECEIVED_DURING_LOG_IN'
});
};
fetch(url, postOptions)
.then((response) => {
debugger;
// this is where I get response.status 401
})
I am using react-native-app-auth library and passing in grant type: authorization code with PKCE and client credentials
const config = {
issuer: "***",
clientId: "***",
clientSecret: '***',
redirectUrl: '***:/oauthredirect',
additionalParameters: {},
scopes: ['***']
}
const newAuthState = await authorize(config);
Able to enter credentials and redirect to react native app but getting error of client_id and client_secret is missing or has an incorrect value
client_id, client_secret and scope are correct. And scope, redirectUrl are registered on server.
https://github.com/FormidableLabs/react-native-app-auth
clientAuthMethod - (string) ANDROID Client Authentication Method. Can be either basic (default) for Basic Authentication or post for HTTP POST body Authentication
passing clientAuthMethod as post worked for me.
I'm trying to migrate my app from auth0 to auth0-spa.js. I've been able to get it almost working, and the code is definitely simpler with this new lib so I'd like to keep using it but I also need a valid jwt token for the backend.
I use the following middleware on my node server (express-jwt)
export const jwtCheckMiddleware = jwt({
secret: '....',
getToken: function (req) {
if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
return req.headers.authorization.split(' ')[1];
}
},
issuer: `https://${environment.auth.auth0Domain}/`,
algorithm: 'RS256'
});
Previous I would pass the idToken from auth0 and it worked. Now I get a token via await auth0.getTokenSilently(), however passing that to the middleware gives me "jwt malformed".
How can I get a valid JWT token from auth0-spa.js? Also, how would I ensure that the token I'm passing to the middlware is never expired?
Ok so I was able to get auth-spa.js to give me a jwt token by registering a custom API with Auth0 and then passing the API identifier as the audience.
More info here: https://auth0.com/docs/getting-started/set-up-api
const auth0 = createAuth0Client({
audience: environment.auth.audience, <-----API identifier of custom API in Auth0
client_id: environment.auth.clientId,
domain: environment.auth.clientDomain
});
After adding the audience getTokenSilently() gives me a JWT token which I pass to node. Then I had to add the audience in my jwt middleware:
export const jwtCheckMiddleware = jwt({
secret: jwks.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: `https://${environment.auth.auth0Domain}/.well-known/jwks.json`
}),
audience: environment.auth.auth0ApiAudience, <!--- API identifier
issuer: `https://${environment.auth.auth0Domain}/`,
algorithms: ['RS256']
});
I am building a cordova mobile app and trying to use the auth0 lock API. I am having trouble with the refresh token. I can retreive the refresh token in the authResult but cannot figure out how to actually refresh the id_token ( I suppose i could write the REST calsl myself )
In the v9 docs, it seems there used to be a method: https://auth0.com/docs/libraries/lock/v9/using-a-refresh-token
lock.getClient().refreshToken(refresh_token, function (err, delegationResult) {
// Get here the new JWT via delegationResult.id_token
});
However in lock v10 it seems this method doesn't exist any more: https://auth0.com/docs/libraries/lock/v10/api
Can anyone advise if there is a way to refresh the token using the lock API?
First, you need to either have included Auth0's script tag in your HTML:
<script src="https://cdn.auth0.com/js/lock/10.8/lock.min.js"></script>
Or, if you've installed from npm, you can require Auth0:
var Auth0 = require("auth0-js");
In V10, you create an instance of the Auth0 client (separate from the Auth0Lock instance) which has a function refreshToken():
var auth0 = new Auth0({clientID: YOUR_CLIENT_ID, domain: YOUR_AUTH0_DOMAIN});
...
auth0.refreshToken(refresh_token_here, (err, resp) => {
// resp: {expires_in: 36000, id_token: "id_token here", token_type: "Bearer"}
}
The same can also be achieved by using the getDelegationToken() function:
auth0.getDelegationToken({
client_id: YOUR_CLIENT_ID,
grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
refresh_token: refresh_token_here,
scope: "openid",
api_type: "auth0"
}, (err, resp) => {
// resp: {expires_in: 36000, id_token: "id_token here", token_type: "Bearer"}
});