BotCraftHub / MystiGuardian

MystiGuardian - Your server's mystical protector and entertainment extraordinaire. Uniting moderation with fun, it ensures a secure and delightful Discord experience.
Apache License 2.0
0 stars 0 forks source link

JWT implementation #15

Closed RealYusufIsmail closed 9 months ago

RealYusufIsmail commented 9 months ago

General Troubleshooting

Feature Request

JWT purpose is to take an access token and decipher it in a way where an attacker is unable to take that token, unscramble and use it for malicious purposes.

When we send a request to discord for auth we get the following back

   String accessToken = tokens.getAccessToken();
   String refreshToken = tokens.getRefreshToken();

This is an example json that is returned once the user authenticats with discord.

{
  "access_token": "6qrZcUqja7812RVdnEKjpzOL4CvHBFG",
  "token_type": "Bearer",
  "expires_in": 604800,
  "refresh_token": "D43f5y0ahjqew82jZ4NViEr2YafMKhue",
  "scope": "identify"
}

Here we can see that the prior mentioned tokens + the expiry duration.

The access token is the token that gives us access to the protected resources but they are short lived. For discord case the expiry duration of the token is provided.

The refresh token on the other hand allows clients to request new acess tokens. These need to be have a higher level of protection.

Thats why JWT is required.

JWTs consist of thee parts:

  1. Header
  2. Payload
  3. Signature

so a jwt token would look like this

xxxxx.yyyyy.zzzzz

In order for us to use JWT for our access key when need key pairs which we need to generate once and store.

We can run a java main programmer and get the key pair we generate and store

Example :

public class JwtGenerator {

    private KeyPairGenerator keyPairGenerator;
    private KeyPair keyPair;

    public JwtGenerator() throws NoSuchAlgorithmException {
        keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);
        keyPair = keyPairGenerator.generateKeyPair(); // For test use In real case we need to store our key pair
    }

    public String generateJwt(Map<String, String> payload) throws Exception {

        Builder tokenBuilder = JWT.create()
                .withIssuer("https://keycloak.quadmeup.com/auth/realms/Realm")
                .withClaim("jti", UUID.randomUUID().toString())
                .withExpiresAt(Date.from(Instant.now().plusSeconds(300)))
                .withIssuedAt(Date.from(Instant.now()));

        payload.entrySet().forEach(action -> tokenBuilder.withClaim(action.getKey(), action.getValue()));

        return  tokenBuilder.sign(Algorithm.RSA256(((RSAPublicKey) keyPair.getPublic()), ((RSAPrivateKey) keyPair.getPrivate())));
    }

}

Example Use-Case

No response

github-actions[bot] commented 9 months ago

Hi/Hello Thank you for raising your first issue. Please make sure it is detailed so we know what it is about.