首页 文章

angular2与Slim框架jwt认证

提问于
浏览
0

我正在尝试创建一个服务来验证angular2中的用户名和密码 . 这是authentication.service.ts的代码

import { Injectable } from '@angular/core';
    import { Http, Headers, Response } from '@angular/http';
    import { Observable } from 'rxjs';
    import {Md5} from 'ts-md5/dist/md5';

    export interface User {
        userName: string;
        password: string; }

    @Injectable()
    export class AuthenticationService {

        public token: string;

        constructor(private http: Http) {
            // set token if saved in local storage
            var currentUser = JSON.parse(localStorage.getItem('currentUser'));
            this.token = currentUser && currentUser.token;
        }

        login(user:User): Observable {

            return this.http.post('http://localhost/hj1/api/authenticate', 
                JSON.stringify({ 'user': user.userName, 'password': Md5.hashStr(user.password) }))
                .map((response: Response) => {
                    // login successful if there's a jwt token in the response
                    console.log(response);
                    let token = response.json() && response.json().token;
                    if (token) {
                        // set token property
                        this.token = token;

                        // store username and jwt token in local storage to keep user logged in between page refreshes
                        localStorage.setItem('currentUser', JSON.stringify({ user: user, token: token }));

                        // return true to indicate successful login
                        return true;
                    } else {
                        // return false to indicate failed login
                        return false;
                    }
                }
            );
        }

        logout() {
            localStorage.removeItem("currentUser");
            this.token = null;
        }
    }

这是我使用slim框架的index.php

getContainer();

    $container["jwt"] = function ($container) {
        return new StdClass;
    };


    $app->add(new \Slim\Middleware\JwtAuthentication([
        "path" => "/",
        "passthrough" => "/authenticate",
        "secret" => getenv("HJ_ENV"),
        "error" => function ($request, $response, $arguments) {
            $data["status"] = "error";
            $data["message"] = $arguments["message"];
            return $response
                ->withHeader("Content-Type", "application/json")
                ->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
        },
        "callback" => function ($request, $response, $arguments) use ($container) {
            $body = $response->getBody();
            $body->write($arguments["decoded"]);
            $container["jwt"] = $arguments["decoded"];
        }
    ]));

    $app->post('/authenticate', 'authenticate');

    $app->run();

    function authenticate(Request $request, Response $response)
    {
        $params = json_decode($request->getBody());
        $sql = "select * from users where userName = :userName";
        $result = json_decode( runQuery($sql, [ ':userName', $params->user ]) );
        $body = $response->getBody();
        if ( $result && $result[0]->password == $params->password )
        {
            $decoded = $request->getAttribute("jwt");
            $body->write( json_encode([ 'token' => $decoded ]) );
        }
        else
        {
            $body->write( json_encode(['token' => null]) );
        }
    }

    function runQuery($sql, ...$params)
    {
        try
        {
            $db = getConnection();
            $stmt = $db->prepare($sql);
            foreach ( $params as $param )
            {
                $stmt->bindParam( $param[0], $param[1] );
            }

            $stmt->execute();
            $rows = [];
            while($row=$stmt->fetch(PDO::FETCH_OBJ))
            {
                /*its getting data in line.And its an object*/
                array_push($rows, $row );
            }
            $db = null;
            return json_encode($rows);
        }
        catch(PDOException $e)
        {
            $db = null;
            return $e->getMessage() ; 
        }
    }

    ?>

我的问题是我无法从容器['jwt']获取令牌 . 如果我提供不正确的用户名和密码,则令牌保持为空 . 但是,如果我给出正确的用户名和密码 . $ result变量从我的数据库中提供数据 . 我可以验证密码 . 但是$ request-> getAttribute(“jwt”)这个方法给了我null . 我也检查了$ decoding = $ container [“jwt”],但这也给了我null . 所以我不知道如何获得由jwt创建的令牌 . 谢谢 .

1 回答

  • 0
    add(new \Slim\Middleware\JwtAuthentication([
            "path" => "/",
            "passthrough" => "/authenticate",
            "error" => function ($request, $response, $arguments) {
                $data["status"] = "error";
                $data["message"] = $arguments["message"] ;
                return $response
                    ->withHeader("Content-Type", "application/json")
                    ->write(json_encode($data, JSON_UNESCAPED_SLASHES | 
                        JSON_PRETTY_PRINT));
            }
        ]));
    
        $app->post('/authenticate', function (Request $request, Response $response )
        {
            $params = json_decode($request->getBody());
                /* $params will contain user and password posted by angular for 
                   verification in data base */
    
                /* here you retrieve user name and password from database */
            if ( /* check here user name and password */ )
            {
                $now = new DateTime();
                $future = new DateTime("now +2 hours");
                $payload = [
                    "iat" => $now->getTimeStamp(),
                    "exp" => $future->getTimeStamp()
                ];
                $secret = getenv("HJ_ENV"); /* put your secret key here */
                $token = JWT::encode($payload, $secret, "HS256");
                $data["status"] = "ok";
                $data["token"] = $token;
                return $response->withStatus(201)
                    ->withHeader("Content-Type", "application/json")
                    ->write(json_encode($data, JSON_UNESCAPED_SLASHES | 
                          JSON_PRETTY_PRINT));
            }
            else
            {
                $data["status"] = "error";
                $data["message"] = "Invalid Token" ;
                return $response
                    ->withHeader("Content-Type", "application/json")
                    ->write(json_encode($data, JSON_UNESCAPED_SLASHES | 
                        JSON_PRETTY_PRINT));
            }
        });
    

相关问题