When I use laravel5.3's Passport Password Grant Tokens
this.$http.post('/oauth/token', this.form)
.then(response => {
console.log(response)
})
I get this message
{"error":"invalid_credentials","message":"The user credentials were incorrect."}
I want to know how to custom this error message.
If your application absolutely needs to support OAuth2, then you should use Laravel Passport. However, if you are attempting to authenticate a single-page application, mobile application, or issue API tokens, you should use Laravel Sanctum.
Passport uses JWT authentication as standard but also implements full OAuth 2.0 authorization.
According @driesvints in #937 Laravel Passport is working to develop a simplified way to customize Passport's errors. Until then you can use the following codes. I tested them and use them.
App\Providers\AppServiceProvider.php
add: use Laravel\Passport\Http\Controllers\AccessTokenController;
...
public function register()
{
$this->app->bind( AccessTokenController::class, \App\myOAuth\AccessTokenController::class);
}
App\myOAuth\AccessTokenController.php
<?php
namespace App\myOAuth;
use GuzzleHttp\Exception\ClientException;
use Laravel\Passport\Http\Controllers\AccessTokenController as PassportAccessTokenController;
use League\OAuth2\Server\Exception\OAuthServerException;
use Psr\Http\Message\ServerRequestInterface;
use Zend\Diactoros\Response as Psr7Response;
class AccessTokenController extends PassportAccessTokenController
{
/**
* Authorize a client to access the user's account.
*
* @param ServerRequestInterface $request
*
* @return \Psr\Http\Message\ResponseInterface
* @throws \League\OAuth2\Server\Exception\OAuthServerException
*/
public function issueToken(ServerRequestInterface $request)
{
try {
return $this->server->respondToAccessTokenRequest($request, new Psr7Response);
} catch (ClientException $exception) {
$error = json_decode($exception->getResponse()->getBody());
throw OAuthServerException::invalidRequest('access_token', object_get($error, 'error.message'));
}
}
}
App\Exceptions\Handler.php
add your customized Exceptionspublic function render($request, Exception $exception)
{
...
$class = get_class($exception);
...
if ($class == 'League\OAuth2\Server\Exception\OAuthServerException' ){
return response()->json([
'code'=>$exception->getHttpStatusCode(),
'error'=>$exception->getMessage(),
'error_type'=>$exception->getErrorType()
],
$exception->getHttpStatusCode());
}
...
return parent::render($request, $exception);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With