jwt: use pre-computed JWT header

JWT header is unmodifable and can be used as constant.

Signed-off-by: Alexey Markevich <buhhunyx@gmail.com>
This commit is contained in:
Alexey Markevich 2020-10-05 16:35:58 +03:00 committed by Anas Nashif
commit 5ee6793e57

View file

@ -127,16 +127,6 @@ static int base64_append_bytes(const char *bytes, size_t len,
return 0; return 0;
} }
struct jwt_header {
char *typ;
char *alg;
};
static struct json_obj_descr jwt_header_desc[] = {
JSON_OBJ_DESCR_PRIM(struct jwt_header, alg, JSON_TOK_STRING),
JSON_OBJ_DESCR_PRIM(struct jwt_header, typ, JSON_TOK_STRING),
};
struct jwt_payload { struct jwt_payload {
int32_t exp; int32_t exp;
int32_t iat; int32_t iat;
@ -152,25 +142,31 @@ static struct json_obj_descr jwt_payload_desc[] = {
/* /*
* Add the JWT header to the buffer. * Add the JWT header to the buffer.
*/ */
static void jwt_add_header(struct jwt_builder *builder) static int jwt_add_header(struct jwt_builder *builder)
{ {
static const struct jwt_header head = { /*
.typ = "JWT", * Pre-computed JWT header
* Use https://www.base64encode.org/ for update
*/
const char jwt_header[] =
#ifdef CONFIG_JWT_SIGN_RSA #ifdef CONFIG_JWT_SIGN_RSA
.alg = "RS256", /* {"alg":"RS256","typ":"JWT"} */
"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9";
#endif #endif
#ifdef CONFIG_JWT_SIGN_ECDSA #ifdef CONFIG_JWT_SIGN_ECDSA
.alg = "ES256", /* {"alg":"ES256","typ":"JWT"} */
"eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9";
#endif #endif
}; int jwt_header_len = ARRAY_SIZE(jwt_header);
int res = json_obj_encode(jwt_header_desc, ARRAY_SIZE(jwt_header_desc), if (jwt_header_len > builder->len) {
&head, base64_append_bytes, builder); builder->overflowed = true;
if (res != 0) { return -ENOSPC;
/* Log an error here. */
return;
} }
base64_flush(builder); strcpy(builder->buf, jwt_header);
builder->buf += jwt_header_len - 1;
builder->len -= jwt_header_len - 1;
return 0;
} }
int jwt_add_payload(struct jwt_builder *builder, int jwt_add_payload(struct jwt_builder *builder,
@ -314,7 +310,5 @@ int jwt_init_builder(struct jwt_builder *builder,
builder->overflowed = false; builder->overflowed = false;
builder->pending = 0; builder->pending = 0;
jwt_add_header(builder); return jwt_add_header(builder);
return 0;
} }