Skip to content

Commit 1ac77c2

Browse files
committed
Verify Authentication header
- Add determine_current_user filter and verify the authentication header and validate the token.
1 parent 96e52ed commit 1ac77c2

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

includes/class-jwt-auth.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,8 @@ private function define_public_hooks()
169169
//if ( defined( 'REST_API_VERSION' ) ){
170170
//If the WP-API is installed add all the hooks
171171
$this->loader->add_action('rest_api_init', $plugin_public, 'add_api_routes');
172+
173+
$this->loader->add_filter('determine_current_user', $plugin_public, 'verify_token', 99);
172174
// }
173175
}
174176

public/class-jwt-auth-public.php

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,74 @@ public function user_login($request)
145145
return apply_filters('jwt_auth_token_before_dispatch', $data, $user);
146146
}
147147

148+
public function verify_token($user)
149+
{
150+
/*
151+
* Looking for the HTTP_AUTHORIZATION header, if not present just
152+
* return the user.
153+
*/
154+
$auth = isset($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : false;
155+
if (!$auth) {
156+
return $user;
157+
}
158+
159+
/*
160+
* The HTTP_AUTHORIZATION is present verify the format
161+
* if the format is wrong return the user.
162+
*/
163+
list($token) = sscanf($auth, 'Bearer %s');
164+
if (!$token) {
165+
return $user;
166+
}
167+
168+
/*
169+
* Get the Secret Key
170+
*/
171+
$secret_key = $this->get_option('jwt_main_options', 'secret_key', false);
172+
if (!$secret_key) {
173+
return $user;
174+
}
175+
176+
/*
177+
* Try to decode the token
178+
*/
179+
try {
180+
$token = JWT::decode($token, $secret_key, array('HS256'));
181+
182+
/**
183+
* The Token is decoded now validate the iss
184+
*/
185+
if( $token->iss != get_bloginfo('url') ){
186+
/**
187+
* The iss do not match, return the user
188+
*/
189+
return $user;
190+
}
191+
/**
192+
* So far so good, validate the user id in the token
193+
*/
194+
if( !isset( $token->data->user->id ) ){
195+
/**
196+
* No user id in the token, abort!!
197+
*/
198+
return $user;
199+
}
200+
/**
201+
* Everything looks good, change the user id
202+
*/
203+
return $token->data->user->id;
204+
205+
} catch (Exception $e) {
206+
/*
207+
* Something is wrong, probably the token expired
208+
* I need to find the way to hijack the API response to send the
209+
* error back to the user.
210+
* For now just return the user and let the API validate te call.
211+
*/
212+
return $user;
213+
}
214+
}
215+
148216
private function get_option($section, $option, $default = '')
149217
{
150218
$options = get_option($section);

0 commit comments

Comments
 (0)