代码之家  ›  专栏  ›  技术社区  ›  Prafulla Kumar Sahu umang naik

如何在Laravel中启用API和Web防护

  •  0
  • Prafulla Kumar Sahu umang naik  · 技术社区  · 7 年前
    Laravel 5.7
    
    PHP 7.2.10
    

    目前我可以使用任何一个web和api防护,有没有任何方法允许两者都使用,这样web应用和api都可以一起工作。

    类似的东西

    return [
    
        /*
        |--------------------------------------------------------------------------
        | Authentication Defaults
        |--------------------------------------------------------------------------
        |
        | This option controls the default authentication "guard" and password
        | reset options for your application. You may change these defaults
        | as required, but they're a perfect start for most applications.
        |
        */
    
        'defaults' => [
            'guard' => 'api|web',
            'passwords' => 'users',
        ],
    

    如果不使用模式, here 是一个解决方案/解决方案,需要在模式中进行更改,这是我不喜欢的。另外,我不需要访问令牌来注册,这个答案正在做什么。

    API.PHP

    Route::group([
        'middleware' => 'api|web',
        'prefix' => 'auth'
    ], function ($router) {
    
       Route::post('register', 'Auth\AuthController@register')->name('api.register');
        Route::post('forgot-password', 'Auth\ForgotPasswordController@forgotPassword')->name('api.forgot-password');
        Route::post('login', 'Auth\AuthController@login')->name('api.login');
        Route::middleware('auth')->post('logout', 'Auth\AuthController@logout')->name('api.logout');
    

    PHP

    Auth::routes(['verify' => true]);
    Route::prefix('admin')->group(function () {
     Route::middleware('auth', 'permission:super-admin|association-member')->resource('users', 'Auth\UserController');
    });
    

    配置/Auth.PHP

    return [
    
        /*
        |--------------------------------------------------------------------------
        | Authentication Defaults
        |--------------------------------------------------------------------------
        |
        | This option controls the default authentication "guard" and password
        | reset options for your application. You may change these defaults
        | as required, but they're a perfect start for most applications.
        |
        */
    
        'defaults' => [
            'guard' => 'web', //api
            'passwords' => 'users',
        ],
    
        /*
        |--------------------------------------------------------------------------
        | Authentication Guards
        |--------------------------------------------------------------------------
        |
        | Next, you may define every authentication guard for your application.
        | Of course, a great default configuration has been defined for you
        | here which uses session storage and the Eloquent user provider.
        |
        | All authentication drivers have a user provider. This defines how the
        | users are actually retrieved out of your database or other storage
        | mechanisms used by this application to persist your user's data.
        |
        | Supported: "session", "token"
        |
        */
    
        'guards' => [
            'web' => [
                'driver' => 'session',
                'provider' => 'users',
            ],
    
            'api' => [
                'driver' => 'jwt',
                'provider' => 'users',
            ],
        ],
    

    更新 正如@apokryfos所说, If you want both to work for both then yes. However, I think that's bad practice. API routes should only allow API authentication since web authentication usually uses the session which API routes don't use anyway. If I were you I'd take a step back and rethink my entire strategy.

    我也不想让两者同时工作,我只想让API和Web应用同时工作,现在我可以使用它们中的任何一个。

    更新2 正如@lim kean phang建议的那样,Git问题链接

    我变了

      protected function respondWithToken($token)
        {
            return response()->json([
                'access_token' => $token,
                'token_type' => 'bearer',
                'expires_in' =>  auth('api')->factory()->getTTL() * 60,//auth()->factory()->getTTL() * 60,
                'status' => 200,
                "response" => "Successfully login",
            ]);
        }
    

    Expires的值为,但现在我没有获得访问令牌。

    API响应是

    {
        "access_token": true,
        "token_type": "bearer",
        "expires_in": 31536000,
        "status": 200,
        "response": "Successfully login"
    }
    

    更新3 增加了一个 github 找不到任何可行的解决方案来解决问题。

    2 回复  |  直到 7 年前
        1
  •  0
  •   Lim Kean Phang    7 年前

    API路由,应该使用chrome/app中的postman来测试API

    Route::group(['prefix' => 'auth',namespace =>'App\Http\Controller'], function () {
        Route::post('login', 'Auth\AuthController@login')->name('api.login');
    
        Route::group(['middleware' => 'auth:api'], function () {
    
           Route::post('register', 'Auth\AuthController@register')->name('api.register');
            Route::post('forgot-password', 'Auth\ForgotPasswordController@forgotPassword')->name('api.forgot-password');
            Route::post('logout', 'Auth\AuthController@logout')->name('api.logout');
    });
    });
    

    配置/Auth.PHP

    return [
    
    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */
    
    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],
    
    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session", "token"
    |
    */
    
    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
    
        'api' => [
            'driver' => 'jwt',
            'provider' => 'users',
        ],
    ],
    
        2
  •  0
  •   Prafulla Kumar Sahu umang naik    7 年前

    我改变了 AuthController 像这样的

    <?php
    
    namespace App\Http\Controllers;
    
    use Auth;
    use Illuminate\Http\Request;
    
    class AuthController extends Controller
    {
        /**
         * Create a new AuthController instance.
         *
         * @return void
         */
        public function __construct()
        {
            $this->middleware('auth:api', ['except' => ['login']]);
        }
    
        /**
         * Get a JWT via given credentials.
         *
         * @return \Illuminate\Http\JsonResponse
         */
        public function login()
        {
            $credentials = request(['username', 'password']);
    
            $token = auth()->guard('api')->attempt($credentials);
    
            if (!$token) {
                return response()->json(['error' => 'Unauthorized'], 401);
            }
    
            return $this->respondWithToken($token);
        }
    
        /**
         * Log the user out (Invalidate the token).
         *
         * @return \Illuminate\Http\JsonResponse
         */
        public function logout()
        {
            auth()->guard('api')->logout();
    
            return response()->json(['message' => 'Successfully logged out']);
        }
    
        /**
         * Refresh a token.
         *
         * @return \Illuminate\Http\JsonResponse
         */
        public function refresh()
        {
            return $this->respondWithToken(auth()->refresh());
        }
    
        /**
         * Get the token array structure.
         *
         * @param string $token
         *
         * @return \Illuminate\Http\JsonResponse
         */
        protected function respondWithToken($token)
        {
            return response()->json([
                'access_token' => $token,
                'token_type'   => 'bearer',
                'expires_in'   => auth('api')->factory()->getTTL() * 60,
            ]);
        }
    }
    

    在api.php中,将auth改为jwt.auth解决了这个问题。

    Route::group([
        'middleware' => 'api',
        'prefix' => 'auth'
    ], function ($router) {
    
        Route::post('register', 'Auth\AuthController@register')->name('api.register');
        Route::post('forgot-password', 'Auth\ForgotPasswordController@forgotPassword')->name('api.forgot-password');
        Route::post('login', 'Auth\AuthController@login')->name('api.login');
        Route::middleware('jwt.auth')->post('logout', 'Auth\AuthController@logout')->name('api.logout');
        Route::middleware('auth')->post('refresh', 'Auth\AuthController@refresh')->name('api.refresh');
        Route::middleware('jwt.auth')->post('me', 'Auth\AuthController@me')->name('api.me');
    });
    
    推荐文章