jadjoubran / laravel5-angular-material-starter

Get started with Laravel 5.3 and AngularJS (material)
https://laravel-angular.readme.io/
MIT License
1.67k stars 401 forks source link

how to implement JWT authentication in front end #79

Closed masterpowers closed 8 years ago

masterpowers commented 8 years ago

I see you have a controller name jwt_auth.js under this directory angular/app/jwt_auth/jwt_auth.js

which can be called when i hit the url authenticate/data

likewise an auth.js file in the directory angular/config/auth.js

which is responsible for calling the url api/authenticate/auth

now my question is how i can implement this on the front end i know i will add something like this

$stateProvider
            .state('auth', {
                url: '/auth',
                templateUrl: '../views/authView.html',
                controller: 'AuthController as auth'
            })

in the route.js directory is angular/route.js

but since the jwt_auth.js is not on the public folder. im looking for a way to add it in the front end since i cant add it on script tag please help

jadjoubran commented 8 years ago

Hi @masterpowers Thanks for asking a question here. Please make sure to post using Markdown in order to make the question clearer. I have edited your question for now.

jadjoubran commented 8 years ago

jwt_auth.js is concatenated and included in your js/app.js (if you're running gulp watch or gulp) Does that make any difference? I'm not sure I got your question

masterpowers commented 8 years ago

I see guide on your article here http://www.sitepoint.com/flexible-and-easily-maintainable-laravel-angular-material-apps/

I see i can add front end login by doing this at angular/routes.js

i did add this

.state('login', {
            url: '/login',
            views: {
                main: {
                    templateUrl: getView('login')
                },
                footer: {
                    templateUrl: getView('footer')
                }
            }
        });

plus created login.html and footer.html

but i havent seen a way to consume how to implement the jwt authentication can you point me to the right direction thanks

masterpowers commented 8 years ago

I see you have included a sample in the jwt_auth.html

<md-content class="Page-Container" ng-controller="JwtAuthCtrl" layout="column" layout-align="start center">

    <md-card>

        <md-toolbar>
            <div class="md-toolbar-tools">
                <h2>angular/config/auth.js</h2>
            </div>
        </md-toolbar>

        <md-card-content class="language-markup"><pre><code class="line-numbers language-* language-javascript">
(function (){
"use strict";

    angular.module('app.config').config(function ($authProvider){
        // Satellizer configuration that specifies which API
        // route the JWT should be retrieved from
        $authProvider.loginUrl = '/api/1/authenticate/auth';
    });

})();</code></pre>
        </md-card-content>

        <md-card-content>
            <p>
                JWT-auth is configured to work out of the box with dingo/api. Checkout the <a ui-sref="app.rest_api">REST API</a> docs.
            </p>
            <p>
                <md-button ng-click="requestToken()">Request Token</md-button>
                <md-button ng-click="getData()">GetData</md-button>
            </p>
        </md-card-content>

    </md-card>

</md-content>

I uncomment Request Token also add GetData

but im not getting something in return.

masterpowers commented 8 years ago

this is what i get in the console Failed to load resource: the server responded with a status of 401 (Unauthorized)

jadjoubran commented 8 years ago

Yes you're on the right track.

You just need to send the token just like they mentioned here in the docs

Authorization: Bearer {yourtokenhere}

You can configure restangular to send the default header

All of these features are expected to work out of the box once I implement #41

masterpowers commented 8 years ago

thanks for your patience and help and reply , i really like your project. Hopefully i can contribute in any way

jadjoubran commented 8 years ago

@masterpowers Thanks :D Asking questions is one of the best methods of contribution - it helps other people

Let me know if it works for you

jadjoubran commented 8 years ago

This is how you can do it:

Restangular.defaultHeaders['Authorization'] = 'Bearer ' + token;

It sets the default headers from now on which sends the Authorization: Bearer {token} requested by JWT. I haven't tried it though.

masterpowers commented 8 years ago

i tried to add

public function getData()
    {
        //auth protected data
        // return ['auth', 'protected', 'data'];
        return response($content)
            ->header('Content-Type', $type)
            ->header('X-Header-One', 'auth')
            ->header('X-Header-Two', 'protected')
        ->header('Authorization', 'Bearer ' . $token);

    }

in the AuthenticateController.php but i still got same error in console log POST http://rfnbeta.app:8000/api/authenticate/auth 401 (Unauthorized)

jadjoubran commented 8 years ago

The authorization should be sent with the request. Try using my code, before doing the request

masterpowers commented 8 years ago

ill try now your comment

masterpowers commented 8 years ago

cant make it work still i try to add that in jwt_auth.js

$scope.requestToken = function(){
            // Use Satellizer's $auth service to login because it'll automatically save the JWT in localStorage
            $auth.login(credentials).then(function (data){
                // If login is successful, redirect to the users state
                //$state.go('dashboard');
                Restangular.defaultHeaders['Authorization'] = 'Bearer ' + token;
            });

        };
jadjoubran commented 8 years ago

Is the login API call returning 401? ($auth.login)

masterpowers commented 8 years ago

yes its returning 401

jadjoubran commented 8 years ago

can you show me your routes file?

masterpowers commented 8 years ago

here is my route.php

Route::get('/', 'AngularController@serveApp');

Route::get('/unsupported-browser', 'AngularController@unsupported');

$api = app('Dingo\Api\Routing\Router');

$api->version('v1', function ($api) {
    /*
     * used for Json Web Token Authentication - https://scotch.io/tutorials/token-based-authentication-for-angularjs-and-laravel-apps
     * Make sure to re-enable CSRF middleware if you're disabling JWT
     */
    $api->controller('authenticate', 'App\Http\Controllers\AuthenticateController');

    $api->get('test/simple', 'App\Http\Controllers\WelcomeController@getSimple');
    $api->get('test', 'App\Http\Controllers\WelcomeController@getSample');
});

//protected with JWT
$api->version('v1', ['middleware' => 'api.auth'], function ($api) {

    $api->post('test/sample', 'App\Http\Controllers\WelcomeController@sample');

});
jadjoubran commented 8 years ago

Seems related to #81

jadjoubran commented 8 years ago

Fixed by PR #82 Feel free to further document your progress in this Cheers!

jadjoubran commented 8 years ago

@masterpowers you can check the latest commit #41