I am using ruby-jwt gem to generate token. I am not sure it's safe or not? How can I secure my payload. I tried different ways but still can hack payload.
> payload = {email: "gagangami#gmail.com", token: "xyz#123"}
# Way1
> token1 = JWT.encode(payload, Rails.application.secrets.secret_key_base, 'HS256')
#=> "eyJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImdhZ2FuZ2FtaUBnbWFpbC5jb20iLCJ0b2tlbiI6Inh5ekAxMjMifQ.l42W9P4lyP2XWXytu8qpasc6mAFg01Dg57Az1bfxgS8"
# Way 2
> rsa_private = OpenSSL::PKey::RSA.generate 2048
> rsa_public = rsa_private.public_key
> token2 = JWT.encode payload, rsa_private, 'RS256'
=> "eyJhbGciOiJSUzI1NiJ9.eyJlbWFpbCI6ImdhZ2FuZ2FtaUBnbWFpbC5jb20iLCJ0b2tlbiI6Inh5ekAxMjMifQ.U6DO9f9KZ_-GVhviACpXmuyc0dQUznPxZdCaaspr5JP36EweAuP8Wn_R2jvK2ahW0BR-RAh7Z9ChyIk94tDjasSbUYdoW_re299RB-ZmS0NVpCEa-g20sT-5JKCTwbD25vXYdxM4E0swQ81sKw35H5T8ZXSHsrE4bP5mA-me_Wli3hyGacb5O3esStPMdRC5r20qCoK7QW7Wl7NnZHLYjIn8k7lxsFmheNyl1l3OSLY92bxGkSyx4lom6bWqEMXSFdLWqPdKTOX9RZbNVi_6fGms79W6XXnb29htqkM1Z1h0RLXzjCODbALpa7At88xWr32IkHzwNxRJ28VAOJB3Qw"
If I try to decode JWT token manually without secret it gives error. works fine.
But If I paste above token token1 and token2 at https://jwt.io/ I am able to see payload. Is this safe way or Bug? for reference I am attaching two screenshots.
JWT is not for encryption, but for identification.
The JWT generator signed the payload with a private key, you can verify if it is generated by the specific generator or not, using a public key. But the payload is not encrypted, anyone can read it.
For example. John sends you a message that "he is at home.", and signed it by his private key. Everyone can read this message but you can verify it is really sent by John, not someone else like Alice.
Anyone can decode, but only those who have your secret can verify the token.
It is important to understand that the purpose of using JWT is NOT to hide or obscure data in any way. The reason why JWT are used is to prove that the sent data was actually created by an authentic source.
https://medium.com/vandium-software/5-easy-steps-to-understanding-json-web-tokens-jwt-1164c0adfcec
Related
Get Access Token request of OAuth1.0 only work once for Magento1.9 after being redirected back from Authorization URL. Next time when requesting for Access Token I get reject_token.
What I noticed there is difference in signature of both objects' signature.
Request 1(successful):
OAuth::Consumer.new(consumer_data)
OAuth::RequestToken.from_hash(some_hash)
request_token.get_access_token(oauth_verifier: 'asdfasdagbadbv')
with signature having
oauth_nonce=\"iIHmN7obLeONSitOxFFZQI71v0k4mAsEFLFen0Lw\",
oauth_signature=\"lwj0n1AK3VJLdaXHIWEOFlYp5qc%3D\"
Request 2(unsuccessful):
OAuth::Consumer.new(consumer_data)
OAuth::RequestToken.from_hash(some_hash)
request_token.get_access_token(oauth_verifier: 'asdfasdagbadbv')
with signature having
oauth_nonce=\"KciY4tiiPDu1u029Nbdu1C325svchfESTYV1l8mvw\",
oauth_signature=\"KciY4tiiPt5Du1u029Nbdu1CzCHzvc%3D\"
This may be or may not be the issue but this is the only difference I found so far in both requests.
Please someone help me in updating oauth_nonce and signature or devise some other solution.
The problem is in the second line.
request_token.get_access_token(oauth_verifier: 'asdfasdfa')
According to Auth documentation request token should be used one time. Request token expires once we use them. You are using expired request token in the second call which causes reject_token 401 unauthorized.
Solution
Actually, request tokens are used to generate Access Token. Access Tokens can be used multiple times. So what you need is to store Access Token somewhere, generated in first request_token.get_access_token(oauth_verifier: 'asdfasdfa') line. Then you can use saved access token in the reset of your API calls. The syntax of using access token is the following:
#consumer = OAuth::Consumer.new(...)
#token = OAuth::Token.new('ACCESS_TOKEN', 'ACCESS_TOKEN_SECRET') // saved access token and secret here
#consumer.request(:post, '/people', #token, {}, #person.to_xml, { 'Content-Type' => 'application/xml' })
I try to use Google Photos API to upload my images, base on the steps of the following link.
https://developers.google.com/photos/library/guides/upload-media
After following the Using OAuth 2.0 for Web Server Applications, I just get the Oauth2.0_token response(a JSON format with access_token, refresh_token...). However, after I put this token string with "Bearer " into request headers, the response is error 401, the error message is "code 16 Authentication session is not defined".
I cannot find any information to deal with it, thank for any help.
You probably have incorrect permissions. Make sure you request the token with the appropriate scope. For write-only access you need 'https://www.googleapis.com/auth/photoslibrary.appendonly'
src: https://developers.google.com/photos/library/guides/authentication-authorization#what-scopes
One reason this might be happening is that you initially authorized your user for read-only access. If you went through the authorization flow with a .readonly scope, your bearer token reflects that authorization (and the token is retained in your credentials file). If you change your scope but don't get a new auth token you will get this error when trying to upload. Simply redo the authorization flow with the new scope defined:
SCOPES = 'https://www.googleapis.com/auth/photoslibrary'
store = file.Storage('path_to_store')
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('google_credentials.json', SCOPES)
creds = tools.run_flow(flow, store)
and your store will be populated with a new token that can be used for uploading.
You say you "just get the Oauth2.0_token response(a JSON format with access_token, refresh_token...)" and "put this token string with "Bearer " into request headers".
Unfortunately documentation on this isn't super clear in a lot of places. What you are supposed to provide after "Bearer" is the "access_token" field only, not the entire JSON string with all the token fields in it. For reference, this is a single string of random looking characters which probably starts with "ya29." and is pretty long - in my case it's 170 characters.
I'm adding the ability to post todos to my Todist list via a simple app. At the moment I am getting the response "error"=>"invalid_grant" when exchanging my code for an access_token.
I'm unsure exactly what 'invalid_grant' is referring too in this context. Other answers I find seem to be regarding various Google APIs. The Todoist API documentation makes no mention of it.
The post request for token exchange is:
uri = URI('https://todoist.com/oauth/access_token')
result = Net::HTTP.post_form(uri, client_id: ENV['TODOIST_CLIENT_ID'], client_secret: ENV['TODOIST_CLIENT_SECRET'], code: params[:code])
json_body = JSON.parse(result.body) # <- prints error
Any help understanding and solving this is much appreciated.
Update
After reading Takahiko Kawasaki's answer, I have updated the request to the following, but have the same error message.
uri = URI('https://todoist.com/oauth/access_token')
data = {
:client_id => ENV['TODOIST_CLIENT_ID'],
:client_secret => ENV['TODOIST_CLIENT_SECRET'],
:code => params[:code],
:grant_type => 'authorization_code',
}
result = Net::HTTP.post_form(uri, data)
json_body = JSON.parse(result.body)
Add the following.
grant_type: 'authorization_code'
See RFC 6749, 4.1.3. Access Token Request for details.
Additional comment for the revised question.
It seems that the OAuth implementation by Todoist is not mature. I took a look at their API document and soon found some violations against RFC 6749.
For example, (1) scopes must be delimited by spaces but their document says commas should be used. (2) Their token endpoint does not require the grant_type request parameter, which is required by the specification. (3) The value of the error parameter in the response from a token endpoint should be invalid_grant when the presented authorization code is wrong, but their API document says the value will be bad_authorization_code, which is not an official value.
In addition, this is not a violation, but the specification of their API to revoke access tokens implies that they don't know the existence of the official specification for access token revocation, RFC 7009.
For public clients (RFC 6749, 2.1. Client Types), e.g. smartphone applications, the client_secret request parameter of a token endpoint should be optional, but their API document says it is required.
Because their OAuth implementation does not comply with the specification, it would be better for you to ask Todoist directly.
The latest version of the Todoist API (v8) does not require the grant_type parameter so this is not currently the issue.
Two possible reasons for receiving the invalid_grant error are:
The code was not used within a certain length of time and has expired
The code has already been used to generate an access token and so is no longer valid
In both cases, generating a new code before making the POST request should sort the problem.
when we request by click on authorize.........
request send to the
http://localhost:3000/oauth/authorize?client_id=57070f3927deea2d38c50afa042ae0o9u0c539e4d45a79e203cd66d286f9ec8e&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2F&response_type=code
the response come
http://localhost:3000/?code=1560b332321dd2obc99ed3411c78614ce0d59c90e9264c87b7f2f179441d6b4e
now i hve to copy the "code" put in console like below code.....
app_id = "57070f3927deea2d38c50afa042ae0o9u0c539e4d45a79e203cd66d286f9ec8e"
secret = "1dbd541132ca2bdeb9fe83b41d24490b2be445c30fd1856e5914f6d343c4a71b"
client = OAuth2::Client.new(app_id, secret, site: "http://localhost:3000/")
client.auth_code.authorize_url(redirect_uri: callback)
access = client.auth_code.get_token('1560b332321dd2obc99ed3411c78614ce0d59c90e9264c87b7f2f179441d6b4e', redirect_uri: callback)
access.token
this how the access_token is generated...
is there a better way to get the access code from the dookeeper
This is standard way described by oauth2.0 specification for autorization code based retrieval of access token. There are other ways like implicit, password and client credentials. Check out the details in RFC and try it with Doorkeeper.
How to work with Dwolla API which required Client_id & Client_Secret
https://www.dwolla.com/oauth/rest/users/{account_identifier}?client_id={client_id}&client_secret={client_secret}
I already register Application. And Got Key and Secret
But when I call above described API Endpoint via Fiddler. Got bellow response.
{"Success":false,"Message":"Invalid application credentials.","Response":null}
Note: I tested Client_id = API Key / Client_id = Application Key. But the response remain same. What is the problem ?
The client_id is just another name for the API/Application Key, which identifies your application. The client/application secret is a string that functions as a password for your application. Just like a password, you should never give out your application secret; and if it's ever compromised, let us know immediately and we'll generate a new key/secret pair for you.
About your failed request: Try encoding your application key and secret. If special characters aren't escaped from the URL, the request will be interpreted differently from what you intend.
You can quickly encode the two strings from your Javascript console:
var key = "EUFH378&36%394749D\DWIHD";
encodeURIComponent(key);
Result: "EUFH378%2636%25394749DDWIHD"
var secret = "WOIDJ38&IDI\DK389DDDDD";
encodeURIComponent(secret);
Result: "WOIDJ38%26IDIDK389DDDDD"
And place their encoded equivalents back into your request URL:
https://www.dwolla.com/oauth/rest/users/gordon#dwolla.com?client_id=EUFH378%2636%25394749DDWIHD&client_secret=WOIDJ38%26IDIDK389DDDDD