允许跨域

public function handle(Request $request, \Closure $next)
    {
        $response = $next($request);
        return $this->setCorsHeadersAll($response);


        $this->headers = [
            'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE',
            'Access-Control-Allow-Headers' => $request->header('Access-Control-Request-Headers'),
            'Access-Control-Allow-Credentials' => 'true',//允许客户端发送cookie
            'Access-Control-Max-Age' => 1728000 //该字段可选,用来指定本次预检请求的有效期,在此期间,不用发出另一条预检请求。
        ];

        $this->allow_origin = [
            'http://192.168.0.109:3000',
            'http://localhost:3000',
            'http://127.0.0.1',
            'http://139.9.0.195',
            'http://127.0.0.1',
        ];
        $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';

        //如果origin不在允许列表内,直接返回403
        if (!in_array($origin, $this->allow_origin) && !empty($origin))
            return new Response('Forbidden', 403);
        //如果是复杂请求,先返回一个200,并allow该origin
        if ($request->isMethod('options'))
            return $this->setCorsHeaders(new Response('OK', 200), $origin);
        //如果是简单请求或者非跨域请求,则照常设置header
        $response = $next($request);
        $methodVariable = array($response, 'header');
        //这个判断是因为在开启session全局中间件之后,频繁的报header方法不存在,所以加上这个判断,存在header方法时才进行header的设置
        if (is_callable($methodVariable, false, $callable_name)) {
            return $this->setCorsHeaders($response, $origin);
        }
        return $response;
    }

    /**
     * @param $response
     * @return mixed
     */
    public function setCorsHeaders($response, $origin)
    {
        foreach ($this->headers as $key => $value) {
            $response->header($key, $value);
        }
        if (in_array($origin, $this->allow_origin)) {
            $response->header('Access-Control-Allow-Origin', $origin);
        } else {
            $response->header('Access-Control-Allow-Origin', '');
        }
        return $response;
    }

    public function setCorsHeadersAll($response)
    {
        $response->header('Access-Control-Allow-Origin', '*');
//        $response->header('Content-Type', 'application/json;charset=utf-8');
//        $response->header('Access-Control-Allow-Headers', 'Content-Type');
        $response->header('Access-Control-Allow-Headers', '*');
        return $response;
    }

JWT

安装

composer require tymon/jwt-auth 1.*@rc

在config/app.php 里配置


'providers' => [
'providers' => [

    Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
]


'aliases' => [
	'JWTAuth'=> Tymon\JWTAuth\Facades\JWTAuth::class,
        'JWTFactory'=> Tymon\JWTAuth\Facades\JWTFactory::class,
]

发布配置文件

php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"

生成加密密钥

php artisan jwt:secret

给用户模型 添加两个方法

//implements JWTSubject
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }
 
    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }

配置auth.php 文件 把guards的api改成jwt

控制器代码示例:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AuthController extends Controller
{
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth('api')->factory()->getTTL() * 60
        ]);
    }

    public function login(){

        $data = request(['name','password']);
        // dd($data);
        if($token = auth('api')->attempt($data)){

            return $this->respondWithToken($token);
        }

        return response()->json(['error'=>'Unauthorized'],401);
    }

    public function me()
    {
        // dd(11);
        return response()->json(auth('api')->user());
    }

    public function logout(){

        $data = auth('api')->logout();

        return response()->json(['msg'=>'success','data'=>$data]);
    }
}

一些问题

Could not create token: Using integers for registered date claims is deprecated, please use DateTimeImmutable objects instead.

composer require tymon/jwt-auth

或者

composer require lcobucci/jwt:3.3.3 && composer update

GeorgieのBlog,分享生活的点点滴滴,分享代码干货