0
votes

I am trying to create a survice to authenticate user name and password in angular2. Here is the code for 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;
        }
    }

and this is my index.php using slim framework


    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() ; 
        }
    }

    ?>

my question is I am not able to get token from container['jwt']. If i give incorrect user name and password then token remain null. But if i give correct user name and password. the $result variable give me data from my database. i can verify password. but $request->getAttribute("jwt") this method gives me null. also i have checked $decoded = $container["jwt"] but this also gives me null. SO i could not know how to get the token created by jwt. Thank you.

1

1 Answers

0
votes

    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));
        }
    });