MediaWiki master
extractClaimsFromJwt.php
Go to the documentation of this file.
1<?php
10use Lcobucci\JWT\Encoding\JoseEncoder;
11use Lcobucci\JWT\Token\Parser;
12use Lcobucci\JWT\Token\Plain;
14
15// @codeCoverageIgnoreStart
16require_once __DIR__ . '/Maintenance.php';
17// @codeCoverageIgnoreEnd
18
26
27 public function __construct() {
28 parent::__construct();
29 $this->addDescription( 'Read the JWT token and output the claims' );
30 $this->addArg( 'jwt', 'A JWT Token string', false );
31 $this->addOption( 'validate', 'Validate if JWT has all required fields (iss, sub)' );
32 }
33
39 private function readJWTFromInput(): string {
40 $content = $this->getArg( 'jwt' );
41 if ( $content === null ) {
42 $content = $this->getStdin( Maintenance::STDIN_ALL );
43 }
44 if ( $content === '' || $content === false ) {
45 $this->fatalError( 'Empty JWT token. Pass it as an argument or as stdin' );
46 }
47 return $content;
48 }
49
50 public function execute() {
51 $jwtCodec = $this->getServiceContainer()->getJwtCodec();
52 if ( !$jwtCodec->isEnabled() ) {
53 $this->fatalError( 'JWT is not enabled on this wiki. Please setup JwtPublicKey and JwtPrivateKey' );
54 }
55
56 $token = trim( $this->readJWTFromInput() );
57
58 if ( $this->hasOption( 'validate' ) ) {
59 try {
60 $data = $jwtCodec->parse( $token );
61 } catch ( Exception $e ) {
62 $this->fatalError( 'Error while parsing JWT: ' . $e->getMessage() );
63 }
64 $this->output( json_encode( $data, JSON_PRETTY_PRINT ) . PHP_EOL );
65 } else {
66 $parser = new Parser( new JoseEncoder() );
67 try {
68 $plain = $parser->parse( $token );
69 } catch ( Exception $e ) {
70 $this->fatalError( 'Error while parsing JWT: ' . $e->getMessage() );
71 }
72'@phan-var Plain $plain';
73 $this->output( json_encode( $plain->claims()->all(), JSON_PRETTY_PRINT ) . PHP_EOL );
74 }
75 }
76}
77
78// @codeCoverageIgnoreStart
79$maintClass = ExtractClaimsFromJwt::class;
80require_once RUN_MAINTENANCE_IF_MAIN;
81// @codeCoverageIgnoreEnd
Maintenance script to read a JWT token and output claims.
execute()
Do the actual work.
__construct()
Default constructor.
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
addArg( $arg, $description, $required=true, $multi=false)
Add some args that are needed.
getArg( $argId=0, $default=null)
Get an argument.
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
getStdin( $len=null)
Return input from stdin.
addDescription( $text)
Set the description text.