Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update create-for-sa.md #805

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 48 additions & 18 deletions ru/iam/operations/iam-token/create-for-sa.md
Original file line number Diff line number Diff line change
Expand Up @@ -430,38 +430,33 @@ yc iam create-token

- Node.js {#node}

Пример создания JWT с использованием [node-jose](https://github.com/cisco/node-jose):
Пример создания JWT с использованием [node-jsonwebtoken](https://github.com/auth0/node-jsonwebtoken):
- Проверено для Node.js v20.12.1 и node-jose 2.2.0.
- Необходимые данные читаются из JSON-файла, полученного при создании авторизованного ключа.

```js
var jose = require('node-jose');
var fs = require('fs');
const jwt = require('jsonwebtoken');
const fs = require('fs');

var json = JSON.parse(fs.readFileSync(require.resolve('<JSON-файл_c_ключами>')));
const json = JSON.parse(fs.readFileSync(require.resolve('<JSON-файл_c_ключами>')));

var key = json.private_key;
var serviceAccountId = json.service_account_id;
var keyId = json.id;
const key = json.private_key;
const serviceAccountId = json.service_account_id;
const keyId = json.id;

var now = Math.floor(new Date().getTime() / 1000);
const now = Math.floor(new Date.now() / 1000);

var payload = {
const payload = {
aud: "https://iam.{{ api-host }}/iam/v1/tokens",
iss: serviceAccountId,
iat: now,
exp: now + 3600
};

jose.JWK.asKey(key, 'pem', { kid: keyId, alg: 'PS256' })
.then(function (result) {
jose.JWS.createSign({ format: 'compact' }, result)
.update(JSON.stringify(payload))
.final()
.then(function (result) {
console.log(result);
});
});
const token = jwt.sign(payload, key, {
algorithm: "PS256",
keyid: keyId
});
```

- PHP {#php}
Expand Down Expand Up @@ -703,6 +698,41 @@ yc iam create-token
return data.IAMToken
}
```
- Node.js {#node}

Пример обмена JWT на IAM-токен:

```js
/**
* @param {string} token - JWT, который был сформирован в примере выше
*/
async getYCIAMToken(token) {
try {

const response = await fetch('https://iam.api.cloud.yandex.net/iam/v1/tokens', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({jwt: token})
});

if(response.ok && response.status === 200) {
const data = await response.json();
return data;
}

else {
// обработка ошибки ответа
throw new Error(`Server response error - response.status: ${response.status}`);
}
}
catch(e) {
console.log(e);
}
}

```

{% endlist %}

Expand Down