How to validate JWS using square/go-jose package - node.js

I am generating a JSON web signature in JavaScript using node-jws package (https://www.npmjs.com/package/jws). In Headers, I am giving crit: ["exp"] and exp: someTimeStamp. The snippet given below is used in generating the JWS:
let token = jws.sign({
header: { alg: 'HS256', crit: ["exp"], exp: Math.floor(Date.now() / 1000) + (60 * 60) },
payload: "somestring" ,
privateKey: 'supersecret',
});
I am verifying this token in Golang using the snippet given below:
import (
"github.com/square/go-jose"
)
func main() {
jsonWebSig, err := jose.ParseSigned(token)
if err != nil {
panic(err)
}
payload, err := jsonWebSig.Verify([]byte("supersecret"))
fmt.Println(string(payload))
fmt.Println(err)
}
The above code in GO works if I don't give the crit: ["exp"] in header while generating the token in JS. Otherwise, it gives me the error saying square/go-jose: error in cryptographic primitive.
I have to use crit: ["exp"] in headers at any cost. Is there any way to verify this?

Related

Verify JWT Token fails in Golang

I have a JWT token generated in nodejs app. It is signed using HS256. I've written the code to validate it in golang. I get an error message of "signature is invalid" even though I verified it in the JWT.io site.
The code validates also Public/Private, but this works. Only the HS256 is not
I've also printed the token and the secret to make sure they are the right values.
Any help will be appreciated.
My golang code:
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// Validate the alg is the expected algorithm:
if conf.JwtAlgorithm != token.Header["alg"] {
log.Printf("unexpected signing method: %s, conf algorithm: %s\n", token.Header["alg"], conf.JwtAlgorithm)
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
log.Printf("JWT algo is: %s, Public is %s, secret is %s", token.Header["alg"], publicKey, secret)
if secret != "" {
log.Printf("Returning secret %s", secret)
return []byte(secret), nil
}
if publicKey != "" {
pub, _ := jwt.ParseRSAPublicKeyFromPEM([]byte(publicKey))
fmt.Println("pub is of type RSA:", pub)
return pub, nil
}
return nil, fmt.Errorf("PublicKey and secret are empty")
})
Since you only have a single HMAC key, you'll want something like this:
package main
import (
"log"
"github.com/golang-jwt/jwt/v4"
)
func main() {
const tokenString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.drt_po6bHhDOF_FJEHTrK-KD8OGjseJZpHwHIgsnoTM"
var keyfunc jwt.Keyfunc = func(token *jwt.Token) (interface{}, error) {
return []byte("mysecret"), nil
}
parsed, err := jwt.Parse(tokenString, keyfunc)
if err != nil {
log.Fatalf("Failed to parse JWT.\nError: %s", err.Error())
}
if !parsed.Valid {
log.Fatalln("Token is not valid.")
}
log.Println("Token is valid.")
}
It's certainly confusing what the return type should be for a jwt.Keyfunc. For an HMAC key, the return type should be []byte.
Please note that HMAC keys do not use public key cryptography and therefore are only a private key that shouldn't be shared.
If the JWTs you need to parse and verify start to become more complex, check out this package: github.com/MicahParks/keyfunc. It has support for multiple given keys like HMAC and remote JWKS resources.

Get Access Token Azure AD using client certificate with Golang

I am trying to do the modern authentication from azure ad with client certificate.
The process says.
Create an azure application.
Upload the certificate to azure application and get the thumbprint.
Generate the JWT token using that certificate(https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-certificate-credentials)
Then use that jwt-token to get the access-token.
To get the access-token, call an API (https://login.microsoftonline.com//oauth2/token)
The HTTP method is of type POST and post body data will be x-www-form-urlencoded
After doing all the steps when i try to get the token.
I get this error.
{
"error": "invalid_client",
"error_description": "AADSTS700023: Client assertion audience claim does not match Realm issuer. Review the documentation at https://learn.microsoft.com/azure/active-directory/develop/active-directory-certificate-credentials .\r\nTrace ID: 714b5009-b74d-46b5-bd0e-3bea76272a01\r\nCorrelation ID: 2cb703bb-f325-44b5-a669-605bc7a81ac0\r\nTimestamp: 2020-08-28 07:31:19Z",
"error_codes": [
700023
],
"timestamp": "2020-08-28 07:31:19Z",
"trace_id": "714b5009-b74d-46b5-bd0e-3bea76272a01",
"correlation_id": "2cb703bb-f325-44b5-a669-605bc7a81ac0"
}
I am generating the JWT token using go code and parsing the PFX file.
func getAuthJWTToken() (string, error) {
clientID := "**********************"
_tenantName := "******************"
pfxFilePath := `E:\abcd.pfx`
certPassword := `*********`
authToken := ""
pfxFile, err := os.Open(pfxFilePath)
if err != nil {
return authToken, err
}
pfxfileinfo, _ := pfxFile.Stat()
var size int64 = pfxfileinfo.Size()
pfxbytes := make([]byte, size)
buffer := bufio.NewReader(pfxFile)
_, err = buffer.Read(pfxbytes)
//PFX to PEM for computation of signature
var pembytes []byte
blocks, err := pkcs12.ToPEM(pfxbytes, certPassword)
for _, b := range blocks {
pembytes = append(pembytes, pem.EncodeToMemory(b)...)
}
//Decoding the certificate contents from pfxbytes
pk, cert, err := pkcs12.Decode(pfxbytes, certPassword)
if cert == nil {
fmt.Printf("Bye")
return authToken, nil
}
if pk == nil {
}
pfxFile.Close() // close file
notToBeUsedBefore := time.Now()
expirationTime := time.Now().Add(3000 * time.Minute)
URL := fmt.Sprintf("https://login.microsoftonline.com/%s/oauth2/token", _tenantName)
id := guid.New()
claims := &claims{
StandardClaims: jwt.StandardClaims{
// In JWT, the expiry time is expressed as unix milliseconds
ExpiresAt: expirationTime.Unix(),
Audience: URL,
Issuer: clientID, // consumer key of the connected app, hardcoded
NotBefore: notToBeUsedBefore.Unix(),
Subject: clientID,
Id: id.String(),
},
}
//token_header map[string]interface{}
token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
sha1Fingerprint := sha1.Sum(cert.Raw)
var slice []byte
slice = sha1Fingerprint[:]
b64FingerPrint := base64.StdEncoding.EncodeToString([]byte(slice))
token.Header["x5t"] = b64FingerPrint
signKey, err := jwt.ParseRSAPrivateKeyFromPEM(pembytes) // parse the RSA key
tokenString, err := token.SignedString(signKey) // sign the claims with private key
fmt.Printf(fmt.Sprintf("JWT token is %s", tokenString))
return tokenString, err
}
I need the help to resolve this issue.

How to verify an ES256 JWT token using Web Crypto when public key is distributed in PEM?

I need to verify ES256 JWT tokens in a Cloudflare Worker. To my understanding they do not run Node.js there and I will have to make everything work with the Web Crypto API (available in browsers, too, as window.crypto.subtle). However, I am expecting to receive the public keys as PEM files and I think I am having problems importing them.
I have been trying to modify an existing open source JWT implementation that only supports HS256 to support ES256.
In addition to trying to use the actual tokens and keys, and keys generated in browsers and OpenSSL, I have tried to use a working example from the JWT.io website (after converting it to JWK format using node-jose), since it should validate correctly. But I am not getting any errors, my code running in browser just tells me the token is not valid.
Here is my Node REPL session I used for converting the key from JWT.io to JWK:
> const jose = require('node-jose')
> const publicKey = `-----BEGIN PUBLIC KEY-----
... MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEEVs/o5+uQbTjL3chynL4wXgUg2R9
... q9UU8I5mEovUf86QZ7kOBIjJwqnzD1omageEHWwHdBO6B+dFabmdT9POxg==
... -----END PUBLIC KEY-----`
> const keyStore = jose.JWK.createKeyStore()
> keyStore.add(publicKey, 'pem')
> keyStore.toJSON()
{
keys: [
{
kty: 'EC',
kid: '19J8y7Zprt2-QKLjF2I5pVk0OELX6cY2AfaAv1LC_w8',
crv: 'P-256',
x: 'EVs_o5-uQbTjL3chynL4wXgUg2R9q9UU8I5mEovUf84',
y: 'kGe5DgSIycKp8w9aJmoHhB1sB3QTugfnRWm5nU_TzsY'
}
]
}
>
Here is the failing validation, based on code from webcrypto-jwt package:
function utf8ToUint8Array(str) {
// Adapted from https://chromium.googlesource.com/chromium/blink/+/master/LayoutTests/crypto/subtle/hmac/sign-verify.html
var Base64URL = {
stringify: function (a) {
var base64string = btoa(String.fromCharCode.apply(0, a));
return base64string.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
},
parse: function (s) {
s = s.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, '');
return new Uint8Array(Array.prototype.map.call(atob(s), function (c) { return c.charCodeAt(0); }));
}
};
str = btoa(unescape(encodeURIComponent(str)));
return Base64URL.parse(str);
}
var cryptoSubtle = (crypto && crypto.subtle) ||
(crypto && crypto.webkitSubtle) ||
(window.msCrypto && window.msCrypto.Subtle);
// Token from JWT.io
var tokenParts = [
'eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9',
'eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTUxNjIzOTAyMn0',
'tyh-VfuzIxCyGYDlkBA7DfyjrqmSHu6pQ2hoZuFqUSLPNY2N0mpHb3nk5K17HWP_3cYHBw7AhHale5wky6-sVA'
];
// Public key from JWT.io converted in Node using node-jose
var publicKey = {
kty: 'EC',
kid: '19J8y7Zprt2-QKLjF2I5pVk0OELX6cY2AfaAv1LC_w8',
crv: 'P-256',
x: 'EVs_o5-uQbTjL3chynL4wXgUg2R9q9UU8I5mEovUf84',
y: 'kGe5DgSIycKp8w9aJmoHhB1sB3QTugfnRWm5nU_TzsY'
};
var importAlgorithm = {
name: 'ECDSA',
namedCurve: 'P-256',
hash: 'SHA-256',
};
cryptoSubtle.importKey(
"jwk",
publicKey,
importAlgorithm,
false,
["verify"]
).then(function (key) {
var partialToken = tokenParts.slice(0,2).join('.');
var signaturePart = tokenParts[2];
cryptoSubtle.verify(
importAlgorithm,
key,
utf8ToUint8Array(signaturePart),
utf8ToUint8Array(partialToken)
).then(function (ok) {
if (ok) {
console.log("I think it's valid");
} else {
console.log("I think it isn't valid");
}
}).catch(function (err) {
console.log("error verifying", err);
});
}).catch(function(err) {
console.log("error importing", err);
});
Since I copied a valid key and a valid token from JWT.io, I am expecting the code to log "I think it's valid" without errors. It does not show any errors, indeed, but it ends up in "I think it isn't valid" branch.
Answered here How to verify a signed JWT with SubtleCrypto of the Web Crypto API?
So, if I understood correctly, the problem was that base64 encoding included in the open source upstream just does not work correctly in one of the directions, since it uses the browser's btoa. Adapting https://github.com/swansontec/rfc4648.js instead works.

How to get authenticate with the squareup using backend golang?

In sqaureup application Aplication_name in oauth option there is a redirect url Which will redirect a given url with the QueryString code. While I'm hitting https://connect.squareup.com/oauth2/authorize?client_id=YOUR_CLIENT_ID this url in the browser then it will redirect me to a given url in oauth with attached code. And then to take a access_token you have to give a POST request to given url https://connect.squareup.com/oauth2/token with the body
{
"client_id": "YOUR_APPLICATION_ID",
"client_secret": "YOUR_APPLICATION_SECRET",
"code": "M-Q7k-N0Emx_3cBqwbVLTQ",
"redirect_uri": "YOUR_REDIRECT_URI"
}
I do it same and send By method POST to this url with json data but it will gives me the error:-
{
"message": "Not Authorized",
"type": "service.not_authorized"
}
The Golang Code I'm using for this is :-
func Token(c *gin.Context) {
code := c.Query("code") // code be something like:-sq0cgp-wLVQt5HOLfug6xiVdmCDCf
splitCode := strings.Split(code, "-")
token := models.PostToken{
ClientID: "YOUR_APPLICATION_ID",
ClientSecret: "YOUR_APPLICATION_SECRET",
Code: splitCode[1],
RedirectUri: c.Request.Host + c.Request.URL.RequestURI(),
}
bindData, err := json.Marshal(token)
if err != nil {
panic(err)
}
var jsonStr = []byte(string(bindData))
url := "https://connect.squareup.com/oauth2/token"
req, err := http.Post(url, "application/json", bytes.NewBuffer(jsonStr))
fmt.Println(req, err)
}
Models struct:-
type PostToken struct {
ClientID string `json:"client_id" bson:"client_id"`
ClientSecret string `json:"client_secret" bson:"client_secret"`
Code string `json:"code" bson:"code"`
RedirectUri string `json:"redirect_uri" bson:"redirect_uri"`
}
You have to do some points I mentioned:-
First check your application Id.
In second parameter ClientSecret you have to use Oauth Application Secret key Which you will got from the application dashboard -> Oauth option.
In Code you don't have send the split code send simple string code value which your getting in the variable name code.
Fourth parameter is optional as the documentation says here.
Then you will got what you want :D.

Can't get HMAC Authentication working with API

I'm trying to authenticate using HMAC with the LocalBitcoins API.
Here is the authentication written in Python:
message = str(nonce) + hmac_auth_key + relative_path + get_or_post_params_urlencoded
signature = hmac.new(hmac_auth_secret, msg=message, digestmod=hashlib.sha256).hexdigest().upper()
And the parameters to create the HMAC message:
Nonce. A 63 bit positive integer, for example unix timestamp as milliseconds.
HMAC authentication key. This is the first one of a key/secret pair.
Relative path, for example /api/wallet/.
GET or POST parameters in their URL encoded format, for example foo=bar&baz=quux.
Here is how I am building the HMAC:
var milliseconds = (new Date).getTime();
var key = config.key;
var secret = config.secret;
var nonce = milliseconds.toString()
var message = nonce + key + 'api/myself';
var hmac_digest = crypto.createHmac("sha256", secret).update(message).digest('hex').toUpperCase();
The signature is sent via 3 HTTP Headers. The options for the call to the api/myself method looks like such (using request):
{ url: 'https://localbitcoins.com/api/myself',
method: 'GET',
headers:
{ 'Apiauth-Key': 'my api key',
'Apiauth-Nonce': 1439925212276,
'Apiauth-Signature': 'the created signature' },
timeout: 5000 }
And the request:
var req = request.get(options, function(error, response, body) {
console.log(body);
});
But everytime I get the following error message:
{ error:
{ message: 'HMAC authentication key and signature was given, but they are invalid.',
error_code: 41 } }
I've tried lots of different combinations in testing but can't get anything to work. What am I missing?
It turns out that my path was wrong.
/path needed to be /path/, which I found out through working with a working Python implementation.
The package is up and running now here: https://github.com/mrmayfield/localbitcoins-node
I think that (new Date).getTime(); is not creating a 63 bit integer. Per Dr. Axel's post. JavaScript has 53 bit integers plus a sign.

Resources