UnauthorizedError: jwt malformed error when authenticating - express

Im using Auth0 for authenticating users for my react application.I have been trying to access resources on server side but I keep getting UnauthorizedError: jwt malformed as an Error.
I’ve followed a the following thread on the community forums: https://community.auth0.com/t/unauthorizederror-jwt-malformed-in-express-js/7352
Many users have suggested that the audience value from the guide is wrong. The audience given in the guide is https:///userinfo but it should be ‘https://.auth0.com/api/v2/’, I’ve made that change and the error is still there.
This has worked for some people but not for me.
This is the guide ive been following: https://auth0.com/blog/react-tutorial-building-and-securing-your-first-app/
const checkJwt = jwt({
secret: jwksRsa.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: `https://<domain>/.well-known/jwks.json`
}),
// Validate the audience and the issuer.
audience: "https://<something>/api/v2/",
issuer: `https://<something>/`,
algorithms: ["RS256"]
});
this is the code ive written on the express side.
this.auth0 = new auth0.WebAuth({
// the following three lines MUST be updated
domain: "<Domain>",
audience: "https://<Something>/api/v2/",
clientID: "clientID",
redirectUri: "http://localhost:3000/callback",
responseType: "token",
scope: "openid"
});
This is the code written on the frontend of the application.

One of our senior engineers had a good recommendation on this that I will share below:
If you haven't done so already you should perform these steps:
capture the token you receive; for example, using a console.log statement given this is in development.
review the captured token; does it look like a JWT?
if its a JWT and you can parse it at jwt.io then update the API to log the received token before trying to validate it; does the received
token match the one you expect?
In conclusion, try to take steps that allow you to gather a bit more
of information.

Related

Not getting authorization code from google auth api with ruby

Recently google authorization api breaks and because of that other things affects like events on Calender.
We are using google_client_api for rails app and we have checked with other Client Id and Client Secret but still this fails to provide to authorization code in response and because of this everything. Is there anyone who can help me out with this. I
client = Signet::OAuth2::Client.new(client_options)
Client_options = {
client_id: Rails.application.secrets.google_client_id,
client_secret: Rails.application.secrets.google_client_secret,
authorization_uri: 'https://accounts.google.com/o/oauth2/auth',
token_credential_uri: 'https://accounts.google.com/o/oauth2/token',
scope: 'https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/userinfo.email',
redirect_uri: callback_url
}
Not getting authorization code in response any solution.

What does the Auth0 error message "Suspicious request requires verification" mean?

I'm trying to implement a password-based login for a Vue app. Everything seems to work fine, but when I try this:
this.auth0.client.login(
{
realm: 'Username-Password-Authentication',
username: 'user#whatever.com',
password: 'totallyValidpassw0rd',
audience: 'https://my-site.eu.auth0.com/userinfo',
scope: 'read:order write:order'
},
(err, authResult) => {
console.log(err);
});
the result is a cryptic Suspicious request requires verification error message. What exactly is suspicious, and what should be verified?
It's supposed to mean that the captcha hasn't been solved. As I found, password based login (Password Grant or Resource Owner Password flow) can't be used together with the Bot detection feature, which is a fancy name for a captcha. Turning off Bot detection solves the problem.
Of course now a third party captcha (like Google reCaptcha) will have to be added to the login form.

Passed scopes to Twitch API being ignored by Auth0

I have been trying to read twitch user subscription data using Auth0 - to no avail.
I found some information in their documentation, explaining how to add customs scopes to the authentication request.
I am importing the createAuth0Client function from "#auth0/auth0-spa-js" and calling the below
this.auth0Client = await createAuth0Client({
domain: options.domain,
client_id: options.clientId,
audience: options.audience,
redirect_uri: redirectUri,
scope: 'email profile user:read:subscriptions' // change the scopes that are applied to every authz request. **Note**: `openid` is always specified regardless of this setting
});
When I am redirected to twitch to authenticate, it is only requesting access to my email. Read subscriptions is never requested, and thus is not authorized.
Any guidance or example would be greatly appreciated.

Keycloak API always returns 401

I'm trying to interact with Keycloak via its REST API. I have the master realm and the default admin user, and a test realm. Firstly, I get an access token for the admin account and test realm:
let data = {
grant_type : 'password',
client_id : 'test-realm',
username : 'admin',
password : 'admin'
};
let headers = {
'Content-Type': 'application/x-www-form-urlencoded'
};
axios.post(
'https://someurl.com:8080/auth/realms/master/protocol/openid-connect/token',
qs.stringify(data),
headers
)
That works ok. Then I try to make a call to create a user (or do anything else) and I get a 401 unauthorized error:
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Bearer ${accessToken}`
};
data = {
rep: {
email: "test#email.com",
username: "test#email.com"
},
path: 'test-realm'
};
axios.post('https://someurl.com:8080/auth/admin/realms/test-realm/users',
qs.stringify(data),
headers
)
Is that not the correct way to include the token? Is the access token the one you use for authenticating other API calls? Shouldn't the admin account's token work for authenticating calls to other clients with the master realm? Would it be some setting in the master realm that I have to change in the admin console? Any help appreciated.
I got a 401 error because I generated the offline token by using http://localhost:8080 and then I tried to request the api by using http://keycloak:8080 which is not allowed. Unfortunately the log doesn't tell you that.
To debug JWT tokens I recommend https://jwt.io/
Is that not the correct way to include the token?
This is a correct way.
You just do something incorrectly.
Please, refer for an example from keycloak-request-token Node.js module:
https://github.com/keycloak/keycloak-request-token/blob/master/index.js#L43
You use
client_id : 'test-realm'
but there is
client_id: 'admin-cli'
there.
Also, to create a user, you should use
'Content-Type': 'application/json'
You can refer for Node.js examples of Keycloak REST API here:
https://github.com/v-ladynev/keycloak-nodejs-example/blob/master/lib/adminClient.js
Examples of other useful stuff like:
custom login
storing Keycloak token in the cookies
centralized permission middleware
can be found in the same project: keycloak-nodejs-example
I fixed it by enabling the below "Service Accounts Enabled" button under Settings for admin-cli
I had this issue and solved it by making sure that there is no more than 1 minute between the first and the second API request. So, if you are doing this manually (2 curl requests), the token may expire and you may get error 401. Nevertheless, you should use admin-cli as mentioned above.
I came this issue recently and after struggling for a while i figured. using a realm name containing white spaces will trigger 401 unauthorized error when interacting with via SDKs or API.
IN SUMMARY:
change: realm name
to: realm-name

Can only get either a long access token or a refresh token

I am using react-native-auth0 sdk. Here is how I use auth0 to do facebook login.
auth0
.webAuth
.authorize({
scope: 'openid profile email offline_access',
//audience: config.auth0.audience, //option (1)
audience: auth0Domain+'/userinfo', //option (2)
responseType: 'token id_token',
})
.then(auth0Cred => {
console.log("Auth0 Auth Result: "+JSON.stringify(auth0Cred));
dispatch(signInAuth0Successful(auth0Cred));
if (callback != null) {
callback(auth0Cred);
}
dispatch(saveAuth0RefreshToken(auth0Cred.refreshToken));
//return auth0Cred;
})
.catch(error => console.log(error));
For the audience there are two options for me.
When I use option (1), it gives me (the long version of) accessToken, idToken, scope, expiresIn, tokenType.
When I use option (2), it gives me (the opaque version of) accessToken, idToken, refreshToken, expiresIn, tokenType.
However, I need both the long accessToken and refreshToken at the same time? Is it possible?
Explanation - When you use an audience for your own API, you are opting in to receive a JWT Access Token (long token). If you only need to call the Auth0 /userInfo endpoint then the default behaviour is only to offer an opaque access token - this is expected behaviour (if somewhat confusing).
Out of interest, why would you require a JWT Access Token if you are not specifying your own audience?
However, to try and solve your request - please check if you have set your Client in the Auth0 Dashboard to OIDC Conformant. Under Clients -> Your Client -> Settings - Advanced (at bottom of page). Screen shot below:
If this doesn't work we can explore other options - so please leave a comment beneath if required.
With OIDC Conformance, you would not receive a Refresh Token for a SPA (implicit flow). Instead, use Silent Auth - see reference docs here, so make sure you do have your Client Type set to Native.
Based on OP feedback - Check that the Resource Server also has allow_offline_access enabled. Can patch this with Management API. Alternatively, just go to your API in the Auth0 Dashboard and toggle the switch on the API settings page.