Reputation: 315
home.ts code
userdetails()
{
// for getting token values
this.showLoader();
this.authService.details(this.localStoragekey).then(
(result) => {
this.loading.dismiss();
this.data = result;
console.log('Hello HomePage token details final',this.data);
}, (err) => {
this.loading.dismiss();
this.presentToast(err);
});
}
service provider code
details(token)
{
return new Promise((resolve, reject) => {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', "Bearer" + token );
this.http.post(apiUrl+'details', {}, {headers: headers})
.subscribe(res => {resolve(res.json());
},
(err) => { reject(err); } );
});
}
php laravel code
Route::group(['middleware' => 'auth:api'], function(){
Route::post('details', 'API\UserController@details');
});
public function details()
{
$user = Auth::user();
return response()->json(['success' => $user], $this->successStatus);
}
php code works on postman... but when I tried using ionic 2 I got POST http://127.0.0.1:8000/api/details 401 (Unauthorized) error....
CORS is working fine..
thanks....
Upvotes: 0
Views: 1003
Reputation: 133
Your unauthorized error, as stated by Juxture in the comment, comes from the following line:
headers.append('Authorization', "Bearer" + token );
This implies that your Authorization header is as follows:
BearereyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
as opposed to the expected:
Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
So try adding a space between Bearer and your actual token, and try it. If you have any other problems implementing JWT I suggest you take a look at https://jwt.io/introduction/
Upvotes: 0