php – Oauth2-server-laravel自定义消息响应

前端之家收集整理的这篇文章主要介绍了php – Oauth2-server-laravel自定义消息响应前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用 Oauth-server-laravel身份验证.

到目前为止我做了什么:

当我将错误的access_token发布到我在laravel中创建的API时,它会给出以下响应,

{
  "error": "access_denied","error_description": "The resource owner or authorization server denied the request."
}

我在路线中使用了oauth作为中间件,如下所示,

Route::group(['namespace' => 'Modules\User\Http\Controllers','middleware' => 'oauth'],function () {

    // Get User Profile Details
    Route::post('getUserProfileDetail','UserController@getUserProfileDetail');
});

问题:

If credentials are wrong then oauth automatically respond with it’s default message and i want to customize that response messages,

我有一半成功,如果凭据是正确的,那么它调用在路由中指定的函数,并且我附加我要发送的mre响应.

$response = $this->authorizer->issueAccessToken();

$code = 200; //Response OK
$response['result'] = 'success';
$response['user_id'] = $user['id'];
$response['email'] = $user['email'];
$response['name'] = $user['name'];

但是当凭据不正确时我无法发送它,因为它无法调用函数并将其默认响应发送给用户.

解决方法

我将这类问题设置为自定义消息然后 this worked for me(我写的关于这篇文章博客文章)]

首先在app / Http / Middleware中创建一个中间件.我的中间件名称是OauthExceptionMiddleware

然后打开

app/Http/kernel.PHP

并把这个中间件放在$middleware数组中的oauth2以前的中间件中,就像这样

protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,\App\Http\Middleware\OauthExceptionMiddleware::class,];

Oauth2自定义异常错误消息

<?PHP
/**
 * Created by PHPStorm.
 * User: kingpabel
 * Date: 3/23/16
 * Time: 4:40 PM
 */
namespace app\Http\Middleware;
use Closure;
use League\OAuth2\Server\Exception\OAuthException;
class OauthExceptionMiddleware
{
    public function handle($request,Closure $next)
    {
        try {
            $response = $next($request);
            // Was an exception thrown? If so and available catch in our middleware
            if (isset($response->exception) && $response->exception) {
                throw $response->exception;
            }
            return $response;
        } catch (OAuthException $e) {
            $data = [
//                'error' => $e->errorType,//                'error_description' => $e->getMessage(),'error' => 'Custom Error','error_description' => 'Custom Description',];
            return \Response::json($data,$e->httpStatusCode,$e->getHttpHeaders());
        }
    }
}

猜你在找的Laravel相关文章