How should I make sure the user accessing a backend rendered frontend route is authenticated? - angularjs

I'm using Laravel and Angular to write a web app.
In the front end Laravel is used to create the basic template, but otherwise controlled by Angular. In the back end laravel is used to create a restful API.
I have a few routes like this:
Route::group(['domain' => 'domain.com'], function() {
Route::get('/', ['as' => 'home', function () {
return view('homepage');
}]);
Route::get('/login', ['as' => 'login', function () {
return view('login');
}]);
//users should be authenticated before accessing this page
Route::get('/dashboard', ['as' => 'dashboard', function () {
return view('dashboard');
}]);
});
Route::group(['domain' => 'api.domain.com', 'middleware' => ['oauth']], function() {
Route::post('/post/create', ['uses' => 'PostController#store']);
Route::get('/post/{id}', ['uses' => 'PostController#show']);
//other API endpoints
// ...
});
I want to make sure my domain.com/dashboard URL is only accessed by authenticated users.
In my backend I have OAuth implemented for my API routes which makes sure the user accessing those routes are authentic. Laravel's Auth::once() is used by the OAuth library to make sure the user credentials are correct then generates an access_token. Since Auth::once() is a "stateless" function no session or cookies are utilized and I cannot use Auth::check() to make sure a user is authenticated before the dashboard page is rendered.
How should I go about checking to see if the user trying to access domain.com/dashboard is authenticated? Should I send the access_token in the header when I forward the user from /login to /dashboard? Or should I implement Laravel's a session/cookie based authentication?
EDIT: As per this: Adding http headers to window.location.href in Angular app I cannot forward the user to the dashboard page with an Authorization header.
In order to reuse my API for my mobile apps I STRONGLY prefer to use some sort of token based authentication.

I would advise to use JWT (JSON Web Tokens) to control for authentication.
I think there are several tutorials for their use with Lavarel and AngularJS. I'm more into Python and I use Flask, but the followings look interesting :
Simple AngularJS Authentication with JWT : the AngularJS configuration
Token-Based Authentication for AngularJS and Laravel Apps : the connection with Laravel
JSON Web Token Tutorial: An Example in Laravel and AngularJS

Pierre was right in suggesting JWT for your token based auth.
When the user successfully logs in, before you finish the request, you can create a JWT and pass that back to the client. You can store it on the client (localStorage, sessionStorage) if you want. Then on subsequent requests, put the JWT inside of your Authorization header. You can then check for this header in your middleware and prevent access to your API routes if the token is valid. You can also use that token on the client and prevent Angular from switching routes if the token doesn't exists or isn't valid.
Now if you are trying to prevent the user from accessing the page entirely on initial load (Opens browser, goes straight to domain.com/dashboard), then I believe that is impossible since there is no way to get information about the client without first loading some code on the page.

Not sure about Angular, as I have never used it, but have you tried targeting a controller with your dashboard route? For example
Route::get('/dashboard', [
'uses' => 'UserController#getDashboard',
'as' => 'dashboard',
'middleware' => 'auth'
]);
UserController.php (I'm assuming you have a blade called dashboard.blade.php)
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
class UserController extends Controller
{
public function getDashboard()
{
if(Auth::user()) {
return view('dashboard');
} else {
redirect()->back();
}
}
}
Also, you could always group whichever routes you want to protect with this (taken from the Laravel 5.2 documentation):
Route::group(['middleware' => 'auth'], function () {
Route::get('/', function () {
// Uses Auth Middleware
});
Route::get('user/profile', function () {
// Uses Auth Middleware
});
});
EDIT: Regarding the session token, your login blade should have this in its code:
<input type="hidden" name="_token" value="{{ Session::token() }}">

When the /dashboard HTML loads, does it already include data specific to the user's account?
I would suggest to load the /dashboard HTML separately from the user's data, and hide the dashboard items with ng-cloak while Angular loads the data to populate it.
Redirect to /dashboard URL
Load (static?) dashboard HTML / Angular app, hiding all parts with ng-cloak.
Have Angular access the API using the access_token to load all dashboard data.
Revealing the parts of the dashboard when the data from the API comes in, or showing an error message if the access_token wan't valid.
That way, your /dashboard HTML could actually be just a static HTML file and directly served by the web server and cached by any proxy on the way.
If that isn't an option, you could put your access_token into a cookie with Javascript that runs on the /login view, then redirect to /dashboard, then have your server-side /dashboard view read the cookie to check if the access_token is valid. But that sounds messy and mixes up things that should be separated.

#Pierre Cordier #Mr_Antivius Thank you guys for your answer, it helped me get insight into the problem and allowed me to tinker with with JWT but ultimately did not product a solution for me.
To allow only authenticated users to access domain.com/dashboard I had to implement a hybrid session and OAuth authentication system. I decided to go with Sentinel (instead of Laravel's out of the box auth system) because it has a user permission system I need in other places in my app. I use this library for the OAuth Server.
Here is what I do in my controller:
POST domain.com/auth/authenticate:
public function processLogin(Request $request)
{
$credentials = [
'email' => $request->input('username'),
'password' => $request->input('password'),
];
try
{
$sentinel = Sentinel::authenticate($credentials);
}
catch (\Cartalyst\Sentinel\Checkpoints\ThrottlingException $e)
{
$response = ['error' => [$e->getMessage()]];
$httpStatus = 429;
return response()->json($response, $httpStatus);
}
catch (\Cartalyst\Sentinel\Checkpoints\NotActivatedException $e)
{
$response = ['error' => [$e->getMessage()]];
$httpStatus = 401;
return response()->json($response, $httpStatus);
}
if ($sentinel) //user credentials correct
{
//get oauth token
$oauthToken = Authorizer::issueAccessToken();
$response = ['success' => true, 'user' => ['id' => $sentinel->id, 'email' => $sentinel->email]] + $oauthToken;
$httpStatus = 200;
}
else
{
$response = ['success' => false, 'error' => ['Incorrect credentials']];
$httpStatus = 401;
}
return response()->json($response, $httpStatus);
}
Here is the method the OAuth library looks at to authenticate the user:
public function verifyAuth($email, $password)
{
$credentials = [
'email' => $email,
'password' => $password,
];
if ($user = Sentinel::stateless($credentials))
{
return $user->id;
}
else
{
return false;
}
}
This would create a response like so:
{
"success": true,
"user": {
"id": 1,
"email": "email#domain.tld"
},
"access_token": "6a204bd89f3c8348afd5c77c717a097a",
"token_type": "Bearer",
"expires_in": 28800,
"refresh_token": "092a8e1a7025f700af39e38a638e199b"
}
Hope this helps someone out there
Side Note: I'm sending a POST request to domain.com/auth/authenticate instead of api.domain.com/auth/authenticate because I could not get domain.com/dashboard to recognize sentinel's cookie if I posted to api.domain.com. I've tried changing domain in config/session.php to .domain.com but still nothing. Maybe I'm doing something wrong?

Related

Google SignIn: Redirect Uri in GSI client flow

I’m trying to use the new Google Identity Services to sign in an user to get access to manage his calendars.
My current auth function looks like this in JS:
const auth = async () => {
return new Promise((resolve) => {
const GTokenClient = google.accounts.oauth2.initTokenClient({
client_id: GOOGLE_CLIENT_ID,
scope: GOOGLE_CALENDAR_SCOPE,
prompt: '',
callback: resolve
});
if (gapi.client.getToken() === null) {
GTokenClient.requestAccessToken({ prompt: 'consent' });
} else {
GTokenClient.requestAccessToken({
prompt: ''
});
}
});
};
In desktop web browsers it works fine and the promise resolves but in smartphones (currently trying with an iPhone12) the browser opens a new tab and it stays there loading after giving permissions.
I’m aware that you can set a redirect with the code flow, but it is possible to do the same with the client flow?
I don’t know what to do honestly because there are no examples to implement this behavior using the client flow in the Google documentation.
I only want to be able to redirect the user to the initial screen, if I close the tab that google creates for signing in the calendar is loaded and everything seems fine, it is just a matter of redirection.

how to redirect to another app after login?

I have a React js application "login", which makes a request to the backend and gets the jwt. I need that after the authentication is done, the "login" application redirects to another react application (hosted on another server) which needs to use the jwt
You can redirect a user to another page via the res.redirect method of ExpressJS.
So for example after a user logged in to your backend, you can do something like this:
app.all('/login', (req, res) => {
let isAuthenticated = tryAuthenticate(req);
if (isAuthenticated)
return res.redirect('/anotherApplicationOnAnotherServer');
else
return res.redirect('/login');
});
Framework-agnostic way
Whenever you get your jwt from the backend you call this to redirect:
window.location.href = `https://path-to-another-app?token=${jwt}`;
Then, at the target app you can get your token like this:
const url = new URL(window.location.href);
const jwt = url.searchParams.get("token");

Node API - How to link Facebook login to Angular front end?

Rewriting this question to be clearer.
I've used passport-facebook to handle login with facebook on my site.
My front end is in Angular so I know now need to understand whats the correct way of calling that api route. I already have several calls using Angular's $http service - however as this login with facebook actually re-routes the facebook page can i still use the usual:
self.loginFacebook = function )() {
var deferred = $q.defer();
var theReq = {
method: 'GET',
url: API + '/login/facebook'
};
$http(theReq)
.then(function(data){
deferred.resolve(data);
})
return deferred.promise;
}
or is it perfectly ok/secure/correct procedure to directly hit that URL in a window location:
self.loginFacebook = function (){
$window.location.href = API + '/login/facebook';
}
Furthermore, from this how do I then send a token back from the API? I can't seem to modify the callback function to do that?
router.get('/login/facebook/callback',
passport.authenticate('facebook', {
successRedirect : 'http://localhost:3000/#/',
failureRedirect : 'http://localhost:3000/#/login'
})
);
Thanks.
I was stacked on the same problem.
First part:
I allow in backend using cors and in frontend i use $httpProvider, like this:
angular.module('core', [
'ui.router',
'user'
]).config(config);
function config($httpProvider) {
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
};
The second part:
<span class="fa fa-facebook"></span> Login with facebook
This call my auth/facebook route that use passport to redirect to facebook page allowing a user to be authenticated.
If the user grant access, the callback /api/auth/facebook/callback is called and the facebook.strategy save the user with the profile data.
After saving the user, i create a special token with facebook token, id and email. This info is used to validate every time the user access to private states in the front.
My routes are something like this:
router.get('/facebook', passport.authenticate('facebook',
{ session: false, scope : 'email' }));
// handle the callback after facebook has authenticated the user
router.get('/facebook/callback',
passport.authenticate('facebook',
{session: false, failureRedirect: '/error' }),
function(req, res, next) {
var token = jwt.encode(req.user.facebook, config.secret);
res.redirect("/fb/"+token);
});
In frontend i catch the /fb/:token using a state and assign the token to my local storage, then every time the user go to a private section, the token is sent to backend and validate, if the validation pass, then the validate function return the token with the decoded data.
The only bad thing is that i don't know how to redirect to the previous state that was when the user click on login with facebook.
Also, i don't know how you are using the callback, but you need to have domain name to allow the redirect from facebook. I have created a server droplet in digitalocean to test this facebook strategy.
In the strategy you have to put the real domain in the callback function, like this:
callbackURL: "http://yourdomain.com/api/auth/facebook/callback"
In the same object where you put the secretId and clientSecret. Then, in your application in facebook developers you have to allow this domain.
Sorry for my english, i hope this info help you.
Depending on your front-end, you will need some logic that actually makes that call to your node/express API. Your HTML element could look like
<a class='btn' href='login/facebook'>Login</a>
Clicking on this element will make a call to your Express router using the endpoint of /login/facebook. Simple at that.

refreshing user.is_authenticated with angular and django rest framework

I'm using django rest framework on the backend and angularjs on the frontend. The problem is the login, in angular I do:
function ($scope, $http, User) {
$scope.login = function (user) {
$http.post('/login/', user)
.then(function (response, status) { // success callback
console.log("success");
console.log(response);
}, function(response) { // error callback
console.log("error");
console.log(response);
})
}
}
then in my views.py I do:
def login_view(request):
user = authenticate(username=request.data['username'], password=request.data['password'])
if user is not None:
login(request, user)
return HttpResponse(status=200)
return HttpResponse(status=400)
But in my home template which is the only django template that I use, the rest is pure html since I use ui-router with state view, so the {% if user.is_authenticated %} won't get updated and I have to refresh the page manually. Is there any solution to make the 'if' statement in the template to be trigger without refreshing all the page, or any better solution to make a login system in my website?
Thank you.
You should not use Django's templatescripts in AngularJS.
AngularJS is a SPA. Django's templatescripts does not work well with SPAs.
You need to create your client logic in javascript only.
This can be done by creating a server endpoint that returns true if a given user is authenticated.

Marionette JS multiple route ,controller and session management

So my Marionette application has folowing 2 routes and controllers
AuthRoute and AuthController for user login and logout
UserRoute and UserControler for user listing, new user and edit user
In AuthController when user login I need to save the user session somewhere so that it can be acceable to both these routes, So next time when user hits user listing page I can check for user session and then load the user listing page.
How can I achieve this?
Also, what will be the best way to check if user session is valid or not? My plan is to create a service which will return user details if the session is valid or else will return 401, but till the time service returns the response I can't load the route specific views.
Can someone help me on these?
Thanks in Advance
MSK
I usually save session data in a singleton Beckbone.Model referenced by the Marionette.Application.
Session Model:
var SessionModel = Backbone.Model.extend({
initialize: function () {
this.listenTo(this, 'change', function (model) {
// Manage cookies storage
// ex. using js.cookie
Cookies.set('session', model.toJSON(), {expires: 1});
});
},
checkAuth: function () {
...
},
login: function (user, password, remember) {
...
},
logout: function () {
...
}
});
Application:
var app = new Marionette.Application({
session: new SessionModel(),
...
})
app.reqres.setHandlers({
session: function () {
return app.session;
}
});
Then you can access session model from any point through "global channel":
Backbone.Wreqr.radio.channel('global').reqres.request('session').checkAuth()
So you can implement all your session procedures in the session model class that can be accessed from the whole application. Using cookies you will also save the user session in the browser.
If you use backend API for Backbone then:
How can I achieve this?
The best way for saving a user session is cookies. Use it for storing and retrieving the user authentication_token.
Also, what will be the best way to check if user session is valid or
not?
You have to store authentication_token on the backend side. For login, logout, signup you should iterate with your API.

Resources