I have a Single Page Application which requests JWTs from AWS cognito to access protected resources in a resource server. However, when the JWT expires, I would like to programmatically refresh it. To do this, I need to know if the token is expired to trigger a refresh. Here is the JWT below.
{
"sub": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
"aud": "xxxxxxxxxxxxexample",
"email_verified": true,
"token_use": "id",
"auth_time": 1500009400,
"iss": "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_example",
"cognito:username": "janedoe",
"exp": 1500013000, // <---- this is what we want
"given_name": "Jane",
"iat": 1500009400,
"email": "janedoe#example.com"
}
My dilemma however is that I do not know how to check when it expires without sending it to the resource server to validate it and I cannot do validation on front end as that would expose application secrets. I figure the exp variable is possibly the number of milliseconds from a particular date, however I'm not sure (and nothing on Google corroborates this).
So I'd like to ask, how does one determine the expiry date from the exp variable?
The exp claim is indeed what you're looking for. It's the expiration time, encoded as a numeric value representing the number of seconds since 1970-01-01 00:00 UTC (also refered to as UNIX Epoch time)
You can check your token on https://jwt.io/ and see the converted timestamp, if you point with the mouse on the numeric timestamp.
Here's a small js snippet, that demonstrates how you can calculate the remaining time:
// exp = 2019-09-01 00:00 UTC
var exp = 1567296000
var currentTimeSeconds = Math.round(+new Date()/1000);
console.log(currentTimeSeconds)
var remainingSeconds = exp - currentTimeSeconds
console.log(remainingSeconds + " seconds remaining")
and here is how to convert it to date type, output in local time:
// exp = 2019-09-01 00:00 UTC
var exp = 1567296000
var expDate = new Date(exp*1000);
var expYear = expDate.getYear() + 1900
var expMonth = expDate.getMonth() + 1
var expDay = expDate.getDate()
var expHours = "0" + expDate.getHours()
var expMinutes = "0" + expDate.getMinutes()
var expSeconds = "0" + expDate.getSeconds()
var expFormatted = expYear + "-" + expMonth + "-" + expDay + " " + expHours.substr(-2) + ':' + expMinutes.substr(-2) + ':' + expSeconds.substr(-2);
console.log(expFormatted)
Cognito provides some standard session validation in their libraries.
If you're using JavaScript, you can get a valid set of tokens using
CognitoUser.getSession((err, session) => {
...
})
This checks the id and access tokens and if either is expired, will retrieve updated tokens using the refresh token.
Related
I was playing with this was able to get it working immediately using Node/Javascript, took a while using Golang (this is just generating the user/password to be sent to coturn.) Notice the secret should match the coturn configuration and in the API JS/Go side.
The configuration on coturn: /etc/turnserver.conf
listening-port=443
tls-listening-port=443
listening-ip=10.100.0.2
relay-ip=10.100.0.2
external-ip=123.456.78.9
min-port=10000
max-port=20000
verbose
fingerprint
lt-cred-mech
server-name=myserver
realm=myserver
cert=/etc/SSL/fullchain.pem
pkey=/etc/SSL/privkey.pem
log-file=/var/log/turnserver.log
use-auth-secret
static-auth-secret=MySecret
The following is Node/Js Implementation API (copied from elsewhere - worked):
var crypto = require('crypto');
var unixTimeStamp = parseInt(Date.now()/1000) + 24*3600, // this credential valid for 24 hours
TempUser = [unixTimeStamp, "SomeUser"].join(':'),
TempPassword,
hmac = crypto.createHmac('sha1', "MySecret");
hmac.setEncoding('base64');
hmac.write(TempUser);
hmac.end();
TempPassword = hmac.read();
The following is GOLANG Implementation API (took a while):
UserId := "SomeUser"
// This worked, returned the exact seconds
timestamp := strconv.FormatInt(time.Now().UTC().Unix()+24*3600, 10)
// Example: The above is 1602692130
secret := "MySecret"
TempUser := timestamp + ":" + UserId // For API Auth, coturn expects this format, the timestamp is the expiry date of the final temp user/password.
// Create a new HMAC by defining the hash type and the key (as byte array)
//h := hmac.New(sha256.New, []byte(secret)) // sha256 does not work, use sha1
h := hmac.New(sha1.New, []byte(secret))
h.Write([]byte(TempUser))
//sha := b64.URLEncoding.EncodeToString(h.Sum(nil)) // URLEncoding did not work
TempPassword := b64.StdEncoding.EncodeToString(h.Sum(nil)) // StdEncoding worked
The JS on the Webrtc client. Notice we are using the TempUser and TempPassword here to be sent to coturn.
...
const stunUrl = 'stun:mystun_server',
turnUsername = TempUser,
turnPassword = TempPassword,
...
'iceServers': [
{ 'url': stunUrl },
{
'urls': turnUrl1,
'username': turnUsername,
'credential': turnPassword
},
Now coturn will authenticate using the TempUser and TempPassword above. Hope someone will find this useful. Thanks!
We are doing a MS Graph API call to get the Sharepoint URL of a Team.
API URL: GET https://graph.microsoft.com/v1.0/groups/{GroupID}/sites/root/weburl
We get this :
Response:
{
"error": {
"code": "serviceNotAvailable",
"message": "The service is not available. Try the request again after a delay. There may be a Retry-After header.",
"innerError": {
"request-id": "9f23d067-e851-4c43-8701-abe137683b87",
"date": "2020-03-05T13:53:43"
}
}
}
What could be the issue?
I have been experiencing a similar problem in searching sites ( GET /sites?search=* ) with the Graph API since March 2nd. I have not been able to recover. I have experienced this over multiple O365 tenants, both free and licensed.
Microsoft docs say this error code is due to MSFT induced throttling, but my request rate is like 50 per hour.
This seems to be a Microsoft bug. I posted a stack overflow issue for this and #rafa-ayadi reported that MSFT was fixing it their side for one of his customers.
I bought an Azure Developer Support subscription for this issue, but MSFT closed it and referred me to Sharepoint Developer Support, for which I can find no link or pricing. So no luck yet in getting MSFT to acknowledge and fix for me.
/**
You need do authentication delegated. See the follow code:
First of all you need from portal.azure.com register app and get:
folder id it is tenantID
App Id. it is clientId
**/
URL urlObj = new
URL("https://login.microsoftonline.com/"+config.tenantID+"/oauth2/v2.0/token");
HttpURLConnection httpCon = (HttpURLConnection) urlObj.openConnection();
String urlParameters = "" + // para la v2.0
"grant_type"+"="+"password"+"&"+ /
"scope" + "=" + "https%3A%2F%2Fgraph.microsoft.com%2F.default" +"&" +
"client_id" + "=" + config.clientId +"&" +
"client_secret" + "=" + config.clientSecret +"&" +
"username" + "=" + config.username +"&" +
"password" + "=" + config.contrasena +"&";
byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
httpCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpCon.setRequestProperty("Content-Length",String.valueOf(postDataLength));
httpCon.setRequestMethod("POST");
httpCon.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(httpCon.getOutputStream());
writer.write(urlParameters);
writer.flush();
int status = httpCon.getResponseCode();
BufferedReader in = new BufferedReader(new
InputStreamReader(httpCon.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
String body = getBody(content.toString());
String token = null;
final ObjectNode node = new ObjectMapper().readValue(body, ObjectNode.class);
if (node.has("access_token")) {
token = node.get("access_token").asText();
}
httpCon.disconnect();
return token;
My similar problem accessing any resource in the sites API was caused by having both the Groups.Create and Groups.ReadWrite.All permissions granted at the same time for application type access.
Removing Groups.Create allowed the all CRUD calls to be successful without serviceNotAvailable errors, even command line calls that just access sites.
Be sure to update admin grant and your token if you change the permissions for a test.
User #user13034886 mentioned the permission clash in another post.
I need help constructing the Authorization header to PUT a block blob.
PUT\n\n\n11\n\n\n\n\n\n\n\n\nx-ms-blob-type:BlockBlob\nx-ms-date:Sat, 25 Feb 2017 22:20:13 GMT\nx-ms-version:2015-02-21\n/myaccountname/mycontainername/blob.txt\n
I take this, UTF 8 encode it. Then I take my access key in my Azure account and HMAC sha256 this UTF 8 encoded string with the key. Then I output that in base64. Let's call this output string.
My authorization header looks like this: SharedKey myaccountname:output string
It is not working.
The header in Postman also has x-ms-blob-type, x-ms-date, x-ms-version, Content-Length, and Authorization. The body for now says hello world.
Can anyone help me make this successful request in Postman?
<?xml version="1.0" encoding="utf-8"?>
<Error>
<Code>AuthenticationFailed</Code>
<Message>Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
RequestId:cdeb9a5e-0001-0029-5fb5-8f7995000000
Time:2017-02-25T22:22:32.0300016Z</Message>
<AuthenticationErrorDetail>The MAC signature found in the HTTP request 'jiJtirohvi1syXulqkPKESnmQEJI4GpDU5JBn7BM/xY=' is not the same as any computed signature. Server used following string to sign: 'PUT
11
text/plain;charset=UTF-8
x-ms-date:Sat, 25 Feb 2017 22:20:13 GMT
x-ms-version:2015-02-21
/myaccountname/mycontainername/blob.txt'.</AuthenticationErrorDetail>
</Error>
EDIT:
First, I want to thank you and everyone who responded. I truly truly appreciate it. I have one last question and then I think I'll be set!! I'm not using that code - I'm doing this all by hand. If I have my key: X2iiy6v47j1jZZH5555555555zzQRrIAdxxVs55555555555av8uBUNGcBMotmS7tDqas14gU5O/w== changed slightly for anonymity - do I decode it: using an online base64decoder. Then, when I have my string which now looks like this: PUT\n\n\n11\n\ntext/plain;charset=UTF-8\n\n\n\n\n\n\nx-ms-blob-type:BlockBlob\nx-ms-date:Mon, 27 Feb 2017 21:53:13 GMT\nx-ms-version:2015-02-21\n/myaccount/mycontainer/blob.txt\n so I run this in https://mothereff.in/utf-8 and then use this in HMAC with my decoded key: https://www.liavaag.org/English/SHA-Generator/HMAC/ - using sha256 and base64 at the end.
Is that how I get the correct string to put here?: SharedKey myaccount:<string here>
I believe there's an issue with how you're specifying StringToSign here:
PUT\n\n\n11\n\n\n\n\n\n\n\n\nx-ms-blob-type:BlockBlob\nx-ms-date:Sat,
25 Feb 2017 22:20:13
GMT\nx-ms-version:2015-02-21\n/myaccountname/mycontainername/blob.txt\n
If you notice the error message returned from the server, string to sign by server is different than yours and the difference is that the server is using Content-Type (text/plain;charset=UTF-8) in signature calculation while you're not. Please include this content type in your code and things should work just fine.
Here's the sample code (partial only) I used:
var requestMethod = "PUT";
var urlPath = "test" + "/" + "myblob.txt";
var storageServiceVersion = "2015-12-11";
var date = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture);
var blobType = "BlockBlob";
var contentBytes = Encoding.UTF8.GetBytes("Hello World");
var canonicalizedResource = "/" + accountName + "/" + urlPath;
var canonicalizedHeaders = "x-ms-blob-type:" + blobType + "\nx-ms-date:" + date + "\nx-ms-version:" + storageServiceVersion + "\n";
var stringToSign = requestMethod + "\n" +
"\n" + //Content Encoding
"\n" + //Content Language
"11\n" + //Content Length
"\n" + //Content MD5
"text/plain;charset=UTF-8" + "\n" + //Content Type
"\n" + //Date
"\n" + //If - Modified - Since
"\n" + //If - Match
"\n" + //If - None - Match
"\n" + //If - Unmodified - Since
"\n" + //Range +
canonicalizedHeaders +
canonicalizedResource;
string authorizationHeader = GenerateSharedKey(stringToSign, accountKey, accountName);
private static string GenerateSharedKey(string stringToSign, string key, string account)
{
string signature;
var unicodeKey = Convert.FromBase64String(key);
using (var hmacSha256 = new HMACSHA256(unicodeKey))
{
var dataToHmac = Encoding.UTF8.GetBytes(stringToSign);
signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
}
return string.Format(CultureInfo.InvariantCulture, "{0} {1}:{2}", "SharedKey", account, signature);
}
According to your error message, it indicates that authorization signature is incorrect.
If the Content-Type "text/plain; charset=UTF-8" is not included in the header, please add it in the stringTosign and postman.
When we try to get the signature, we need to make sure the length of the blob.txt matches the Content length in the stringTosign. That means request body length should match the content length in the stringTosign.
I test it with Postman, it works correctly. We can get the signature with the code in another SO Thread. The following is my detail steps
Add the following header
Add the request body (example: Hello World)
Send the put blob request.
Update :
Please have a try to use the online tool to generate signature for test.
Let me start by saying I'm no expert in cryptography algorithms...
I am trying to build a method which formats an HTTP header for Windows Azure - and this header requires part of its message to be encrypted via HMAC with SHA256 (and then also base64 encoded).
I chose to use CryptoJS because it's got an active user community.
First, my code:
_encodeAuthHeader : function (url, params, date) {
//http://msdn.microsoft.com/en-us/library/windowsazure/dd179428
var canonicalizedResource = '/' + this.getAccountName() + url;
/*
StringToSign = Date + "\n" + CanonicalizedResource
*/
var stringToSign = date + '\n' + canonicalizedResource;
console.log('stringToSign >> ' + stringToSign)
var encodedBits = CryptoJS.HmacSHA256(stringToSign, this.getAccessKey());
console.log('encodedBits >> ' + encodedBits);
var base64Bits = CryptoJS.enc.Base64.stringify(encodedBits);
console.log('base64Bits >> ' + base64Bits);
var signature = 'SharedKeyLite ' + this.getAccountName() + ':' + base64Bits;
console.log('signature >> ' + signature);
return signature;
},
The method successfully returns a "signature" with the appropriate piece encrypted/encoded. However, Azure complains that it's not formatted correctly.
Some example output:
stringToSign >> Mon, 29 Jul 2013 16:04:20 GMT\n/senchaazurestorage/Tables
encodedBits >> 6723ace2ec7b0348e1270ccbaab802bfa5c1bbdddd108aece88c739051a8a767
base64Bits >> ZyOs4ux7A0jhJwzLqrgCv6XBu93dEIrs6IxzkFGop2c=
signature >> SharedKeyLite senchaazurestorage:ZyOs4ux7A0jhJwzLqrgCv6XBu93dEIrs6IxzkFGop2c=
Doing some debugging, I am noticing that CryptoJS is not returning the same value (HMAC with SHA256) as alternative implementations. For example, the string "Mon, 29 Jul 2013 16:04:20 GMT\n/senchaazurestorage/Tables" appears as:
"6723ace2ec7b0348e1270ccbaab802bfa5c1bbdddd108aece88c739051a8a767" via CryptoJS
"faa89f45ef029c63d04b8522d07c54024ae711924822c402b2d387d05398fc9f" via PHP hash_hmac('sha256', ... )
Digging even deeper, I'm seeing that most HMAC/SHA265 algorithms return data which matches the output from PHP... am I missing something in CryptoJS? Or is there a legitimate difference?
As I mentioned in my first comment, the newline ("\n") was causing problems. Escaping that ("\ \n", without the space inbetween) seems to have fixed the inconsistency in HMAC/SHA256 output.
I'm still having problems with the Azure HTTP "Authorization" header, but that's another issue.
How can I add a new user to the ACL for a Google Calendar? I'm trying to send a POST HTTP request. Perhaps there is something wrong with the XML? The code below generates a server error (400). (Edit: Shows the oAuth).
//---------------------------------------------------------------
// Add a rule to the Access Control List for 'Fake Calendar 1.0'
//---------------------------------------------------------------
function addRule() {
// Get Calendar ID, script user's email, and the API Key for access to Calendar API
var calId = '12345calendar.google.com';
var userEmail = Session.getActiveUser().getEmail();
var API_KEY = 'ABC123';
var newUserEmail = 'person#example.net';
// Get authorization to access the Google Calendar API
var apiName = 'calendar';
var scope = 'https://www.googleapis.com/auth/calendar';
var fetchArgs = googleOAuth_(apiName, scope);
fetchArgs.method = 'POST';
var rawXML = "<entry xmlns='http://www.w3.org/2005/Atom' " +
"xmlns:gAcl='http://schemas.google.com/acl/2007'>" +
"<category scheme='http://schemas.google.com/g/2005#kind' " +
"term='http://schemas.google.com/acl/2007#accessRule'/>" +
"<gAcl:role value='owner'/>" +
"<gAcl:scope type='user' value='"+userEmail+"'/>" +
"</entry>";
fetchArgs.payload = rawXML;
fetchArgs.contentType = 'application/atom+xml';
// Get the requested content (the ACL for the calendar)
var base = 'https://www.googleapis.com/calendar/v3/calendars/';
var url = base + calId + '/acl?key=' + API_KEY;
var content = UrlFetchApp.fetch(url, fetchArgs).getContentText();
Logger.log(content);
}
//--------------------------------------------------------------
// Google OAuth
//--------------------------------------------------------------
function googleOAuth_(name,scope) {
var oAuthConfig = UrlFetchApp.addOAuthService(name);
oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oAuthConfig.setConsumerKey("anonymous");
oAuthConfig.setConsumerSecret("anonymous");
return {oAuthServiceName:name, oAuthUseToken:"always"};
}
Have you gone through the oAuth authorization process before executing this piece of code. Your app has to be explicitly authorized before it can do anything significant with the Calendar API
Srik is right. You need to use oAuth Arguments in your UrlFetchApp.
Given Reference URL shows few examples for using oAuth in Apps script to work with Google's REST APIs
https://sites.google.com/site/appsscripttutorial/urlfetch-and-oauth