Pārlūkot izejas kodu

一些BUG修复
认证API接口

Zhouzhendong 4 gadi atpakaļ
vecāks
revīzija
490dfc9565

+ 0 - 1
app/Http/ApiControllers/LoginController.php

@@ -37,7 +37,6 @@ class LoginController
         //获取公私钥
         try {
             $privateKey = file_get_contents(base_path().'/private.pem');
-            //$publicKey = file_get_contents(base_path().'/public.pem');
         }catch (\Exception $e){
             $response["status_code"] = 410;
             if (strpos($e->getMessage(),"No such file or directory")!==false)$response["message"] = "服务器异常,资源丢失";

+ 7 - 35
app/Http/Controllers/TestController.php

@@ -86,49 +86,21 @@ class TestController extends Controller
 
     public function test4()
     {
-        $user = User::query()->first();
+
+        $a = file_get_contents(base_path() . '/private.pem');
+        Cache::forever("privatekey",$a);
         $b = file_get_contents(base_path() . '/public.pem');
-        $decoded = JWT::decode("eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJkYXRhIjp7ImZpZWxkMSI6MSwiZmllbGQyIjoic3RyaW5nIGRhdGEifSwiaXNzIjoiaHR0cDpcL1wvZXhhbXBsZS5vcmciLCJhdWQiOiJodHRwOlwvXC9leGFtcGxlLmNvbSIsImlhdCI6MTYyOTc3NDUxMywiZWF0IjoxNjI5NzgxNzEzfQ.Twl3_KPMLP4Pi4zaGZig8SKhE9M6nZlCI8bVifWjuYIWuqZtlujp35Zvv1oY0GnPIkUmq-PGJZLU96mmT-RTRDL-83sPF2l7PPTeriYMoiKP1r2rsI421BtrgLs0qP7QCPxH5BmHWXAVbwTtnwv8JagKzcZxkZJRH3Lj8blRapumnCk-tMfHz4xiXHIATfMS1I23vhJJLomC-KW4Ou3pjTu6X3HiiUGe9ZBGTu5mHfiKm25dxXO5Fm3JMg2-anLf_Gy6D6D7IQJ5pM5HFEN-HdD7FibeEMraMxbk5B_82L15OjhaoCV7b7ioXNSs2QAdlRfuRgx0XIE_toFwb_152a", $b, ['RS256']);
+        Cache::forever("publickey",$b);
         $payload = [
             'data' => ['field1' => 1, 'field2' => 'string data'],
             "iss" => "http://example.org",
             "aud" => "http://example.com",
             "iat" => time(),
-            "eat" => time() + 7200,
+            "eat" => time() + 172800,
         ];
-        try {
-            $token = JWT::encode($payload, $a, 'RS256');
-        } catch (\Exception $e) {
-            $this->error("HTTP:409,资源异常,无法反馈");
-        }
-        try {
-            $a = file_get_contents("test");
-        } catch (\Exception $e) {
-            if (strpos($e->getMessage(), "No such file or directory") !== false) $this->error("HTTP:410,服务器异常,资源丢失");
-            else $this->error("HTTP:403,访问某些资源失败");
-        }
-
-
-        $payload = [
-
-            'data' => ['field1' => 1, 'field2' => 'string data'],
-
-            "iss" => "http://example.org",
-
-            "aud" => "http://example.com",
-
-            "iat" => time(),
-
-            "eat" => time() + 7200,
-
-        ];
-
-        $token = JWT::encode($payload, $a, 'RS256');
-
+        $token = JWT::encode($payload, Cache::get("privatekey"), 'RS256');
         echo "Token:\n" . print_r($token, true) . "\n";
-
-        $decoded = JWT::decode($token, $b, ['RS256']);
-
+        $decoded = JWT::decode($token, Cache::get("publickey"), ['RS256']);
         $decoded_array = (array)$decoded;
 
         echo "Decoded:\n" . print_r($decoded_array, true) . "\n";

+ 2 - 0
app/Http/Kernel.php

@@ -2,6 +2,7 @@
 
 namespace App\Http;
 
+use App\Http\Middleware\AuthorizingApi;
 use App\Http\Middleware\CheckCsrfToken;
 use App\Http\Middleware\LogPostRequest;
 use Illuminate\Foundation\Http\Kernel as HttpKernel;
@@ -75,6 +76,7 @@ class Kernel extends HttpKernel
         'auth.api' => \App\Http\Middleware\ApiAuth::class,
         'procurement.auth.api' => \App\Http\Middleware\ProcurementApiAuth::class,
         'check.token' => CheckCsrfToken::class,
+        'authorizing' => AuthorizingApi::class,
     ];
 
     /**

+ 33 - 3
app/Http/Middleware/AuthorizingApi.php

@@ -3,18 +3,48 @@
 namespace App\Http\Middleware;
 
 use Closure;
+use Firebase\JWT\JWT;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Cache;
 
 class AuthorizingApi
 {
     /**
      * Handle an incoming request.
      *
-     * @param  \Illuminate\Http\Request  $request
-     * @param  \Closure  $next
+     * @param  Request  $request
+     * @param  Closure  $next
      * @return mixed
      */
-    public function handle($request, Closure $next)
+    public function handle(Request $request, Closure $next)
     {
+        $token = $request->header("token");
+        if (!$token) return response()->json([
+                        'message' => '没有认证,请前去认证',
+                        'status_code' => 401,
+                    ]);
+        try {
+            $publicKey = Cache::remember("TOKEN_PUBLIC_KEY",7200,function (){
+                return file_get_contents(base_path().'/public.pem');
+            });
+        }catch (\Exception $e){
+            $response["status_code"] = 410;
+            if (strpos($e->getMessage(),"No such file or directory")!==false)$response["message"] = "服务器异常,资源丢失";
+            else $response["message"] = "访问某些资源失败";
+            return response()->json($response);
+        }
+        try {
+            $payload = JWT::decode($token, $publicKey, ['RS256']);
+        }catch (\Exception $e){
+            $response["status_code"] = 401;
+            $response["message"] = "token非法";
+            return response()->json($response);
+        }
+        if ($payload["exp"]<time()){
+            $response["status_code"] = 401;
+            $response["message"] = "token失效";
+            return response()->json($response);
+        }
         return $next($request);
     }
 }

+ 1 - 1
app/Http/Middleware/DecodingRequest.php

@@ -18,7 +18,7 @@ class DecodingRequest
     {
         if ($request->method() == "GET"){
             foreach ($request->input() as $key => $value){
-                if ($value != null)$request->offsetSet($key, urldecode($value));
+                if ($value != null && is_string($value))$request->offsetSet($key, urldecode($value));
             }
         }
         return $next($request);

+ 1 - 0
app/OrderPackage.php

@@ -87,6 +87,7 @@ class OrderPackage extends Model
     public function setStatusAttribute($value)
     {
         if(!$value)return 0;
+        if (!(self::$enums['status'][$value] ?? false))return 0;
         $this->attributes['status']=self::$enums['status'][$value];
     }
 

+ 0 - 24
app/Services/UserService.php

@@ -143,28 +143,4 @@ class UserService
         $alg = 'RS256';
         return JWT::encode($payload, $key, $alg);
     }
-
-    /**
-     * 获取JWT token
-     *
-     * @param User|\stdClass $user
-     * @param mixed $key
-     * @return string
-     */
-    public function checkJWTToken($user,$key):string
-    {
-        $time = time();
-        $payload = [
-            'iss' => $_SERVER["HTTP_HOST"], //签发者
-            'iat' => $time,
-            'nbf' => $time,
-            'exp' => $time+7200,
-            'data' => [
-                'id' => $user->id,
-                'username' => $user->name
-            ]
-        ];
-        $alg = 'RS256';
-        return JWT::encode($payload, $key, $alg);
-    }
 }

+ 12 - 0
routes/api.php

@@ -14,3 +14,15 @@ use Illuminate\Support\Facades\Route;
 |
 */
 
+Route::prefix("v1")->group(function (){
+    Route::middleware('throttle:' . config('api.rate_limits.sign'))
+        ->group(function () {
+           //登录
+           Route::Get('login', 'LoginController@login');
+        });
+    Route::middleware(['throttle:' . config('api.rate_limits.access'),"authorizing"])
+        ->group(function () {
+
+        });
+});
+