token_sequence.txt (2879B)
1 sequenceDiagram 2 participant Client 3 participant OAuth2 Gateway 4 participant OAuth2 Gateway DB 5 6 Client ->> OAuth2 Gateway: POST /token \n{code, grant_type} 7 8 OAuth2 Gateway ->> OAuth2 Gateway: Validate grant_type == \n'authorization_code' 9 10 alt Invalid grant type 11 OAuth2 Gateway -->> Client: 400 BAD REQUEST \n{error: 'unsupported_grant_type'} 12 else Valid grant type 13 OAuth2 Gateway ->> OAuth2 Gateway DB: WITH code_data AS (\n SELECT id, used AS was_already_used, session_id\n FROM authorization_codes\n WHERE code = $1 AND expires_at > NOW()\n FOR UPDATE\n),\nupdated_code AS (\n UPDATE authorization_codes ac\n SET used = TRUE,\n used_at = CASE WHEN NOT ac.used THEN NOW() ELSE ac.used_at END\n FROM code_data cd\n WHERE ac.id = cd.id\n RETURNING ac.id, ac.session_id\n)\nSELECT uc.id AS code_id,\n cd.was_already_used,\n uc.session_id,\n vs.status AS session_status,\n at.token AS existing_token,\n at.expires_at AS token_expires_at\nFROM updated_code uc\nJOIN code_data cd ON uc.id = cd.id\nJOIN verification_sessions vs ON vs.id = uc.session_id\nLEFT JOIN access_tokens at\n ON at.session_id = vs.id AND at.revoked = FALSE 14 15 alt No code found or DB error 16 OAuth2 Gateway DB -->> OAuth2 Gateway: 0 rows / Error 17 OAuth2 Gateway -->> Client: Error Response:\n- 400 BAD REQUEST {error: 'invalid_grant'}\n- 500 INTERNAL SERVER ERROR 18 else Code found 19 OAuth2 Gateway DB -->> OAuth2 Gateway: code, session, and token data 20 21 OAuth2 Gateway ->> OAuth2 Gateway: Check state 22 23 alt Token already exists (idempotent) 24 OAuth2 Gateway -->> Client: 200 OK \n{access_token: existing_token, \ntoken_type: 'Bearer', expires_in: 3600} 25 else Invalid state 26 OAuth2 Gateway -->> Client: 400 BAD REQUEST \n{error: 'invalid_grant'}\n- Code already used\n- Session not verified 27 else Valid - create token 28 OAuth2 Gateway ->> OAuth2 Gateway: generate_access_token() 29 30 OAuth2 Gateway ->> OAuth2 Gateway DB: WITH updated AS (\n UPDATE verification_sessions \n SET status = 'completed', completed_at = NOW() \n WHERE id = $1 RETURNING id\n)\nINSERT INTO access_tokens \n(session_id, token, expires_at) \nVALUES ($1, $2, NOW() + INTERVAL '1 hour') \nRETURNING token, expires_at 31 32 alt Error 33 OAuth2 Gateway DB -->> OAuth2 Gateway: Error 34 OAuth2 Gateway -->> Client: 500 INTERNAL SERVER ERROR 35 else Success 36 OAuth2 Gateway DB -->> OAuth2 Gateway: token, expires_at 37 OAuth2 Gateway -->> Client: 200 OK \n{access_token, token_type: 'Bearer', expires_in: 3600} 38 end 39 end 40 end 41 end