Authentication with Angular 5 - authentication

I have a login page and I need to go to my home page after successful login. That login functionality login to a ldap server and send a response whether the authentication is success or not. I don't want that to keep in localstorage since this app has only two pages. login and home. When login success it should redirect to home page, if not it should redirect to again to the login page.
And please the console.log in the browser, "inside auth guard true" prints thousands times..
The only code I have in my app.component.html is <router-outlet></router-outlet>

In the canActivate(), all you need to do is return true or false. When you are redirecting it to home from inside the function you are entering into an infinite loop.
This is because on redirecting to home the canActivate() gets called and its expects a boolean return value. If the value is false, it won't load the component.
canActivate() {
if (this.authService.loggedIn) {
console.log('Inside Auth Gaurd');
return true;
}
console.log('auth gaurd false path');
return false;
}
For more detail on canActivate() refer this

Related

Infinite page reload with Vue when redirecting to external authentication URL

Here is what I'd like to implement in my Quasar 2 / Vue 3 application:
User visits any route.
Upon each route change, a backend call is made to check if the user is still authenticated.
If the user is not authenticated, she shall get redirected to the external URL of the authentication provider.
This is my current approach:
router.beforeEach(() => {
api.get('/api/user/current').then((response) => {
userInfoStore.authenticated = true;
userInfoStore.givenName = response.data.givenName;
userInfoStore.fullName = response.data.fullName;
}).catch(() => {
userInfoStore.authenticated = false;
});
if (!userInfoStore.authenticated) {
redirect('http://localhost:8555/oauth2/authorization/keycloak');
}
});
However the following problems occur:
The app constantly reloads itself.
The call to /api/user/current gives NS_BINDING_ABORTED in the browser console.
The console shows Changed to http://localhost:8555/oauth2/authorization/keycloak but gives this error message.
ChunkLoadError: Loading chunk src_layouts_MainLayout_vue failed.

Google OAuth2 SignIn method fires at page load

I have used the official button for Google SignIn:
SignIn Page:
<div class="g-signin2" data-onsuccess="AuthenticateGoogleUser"></div>
function AuthenticateGoogleUser(googleUser){
.....
capture the user info and redirect to Home page
.....
}
When configuring for the credentials, I have set the redirection URL to the signin page.
This is how the Signout happens for the app:
function SignOutGoogleUser() {
if (gapi != null && gapi != undefined &&
gapi.auth2 != null && gapi.auth2 != undefined) {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
auth2.disconnect();
....Redirect to Home page...
});
}
}
The methods work fine. If I signout, will be redirected to home page.
But, when I manually browse the SignIn page after signout, the AuthenticateGoogleUser method is triggered and I am auto signed into the app (with google account).
The AuthenticateGoogleUser method should be only triggered on the button click. Is that right.
But here it is being triggered on load of SignIn page. Is that expected. Can this be stopped.
I'm using MVC C# as backend.
Without seeing all of your code, I am working on the assumption that you have not placed the function in a document ready wrapper and made sure to only kick it off on a button click or other event from which you would like to have it fire. As it stands now, it will fire on that page load.
$(document).ready(function(){
$("btnLogin").click(function(){
AuthenticateGoogleUser(googleUser);
});
});

preventing user to go back once logged out in laravel 5

I have a logout function like this
public function logout() {
Auth::logout(); // logout user
return Redirect::to('login'); //redirect back to login
}
When logout function is triggered through routes which looks like
Route::get('logout', array(
'uses' => 'userController#logout'
));
user get redirected to the login page. But when goes back using browser, dashboard view gets opened which i don't want to. What can be the best way to prevent users from going back to dashboard once they logged out? Though there are some discussion on this topic, but didn't helped me.
Since you're using the Auth, you can utilise the existing Middleware to stop the back button putting them on dashboard.
Wrap the routes you want to protect with a Route::group
Route::group(['middleware' => 'auth'], function () {
Route::get('dashboard', function () {
// Uses Auth Middleware
});
});
Any attempt to access dashboard without login will put them back on the home page (default location in the middleware). Modify the middleware (found in app/Http/Middleware/Authenticate.php) to change the redirect url.
you need to add a middleware in your dashboard so that even if they press back the button they can go back to the page but can't do anything unless they login again.

Authenticating in Play without using routes

I've followed this tutorial for authentication and it works:
http://www.playframework.com/documentation/2.2.x/JavaGuide4
But I was wondering if there was another way to do it so that the user can't just go to myapp.com/login and get the login screen even if they're already logged in. Is there a way to do this so I can go to the login screen but still have myapp.com as the route?
This is easy. Just have the controller method for route "/" display the login page instead of your landing page when the user is not logged in.
Say / routes to Application.index() and it has a function isLoggedIn() to check login status, you could do something like this:
public static index() {
if (isLoggedIn()) {
return ok (index.render());
}
else {
return ok (login.render());
}
}

Refresh MVC view after logging in using Angular

Working with the Breeze Angular SPA template found here, http://www.breezejs.com/samples/breezeangular-template, I'm trying to update a menu that changes after user authenticates.
My example is slightly different from the default template in that I've moved the Login and Register views into modal windows. When the modal closes after a successful login, the menu, which is in the MVC View (and not the Angular View) does not update as a complete page refresh does not occur.
In the SPA template, authentication is required before entering the SPA, then a hard redirect/refresh occurs and the SPA is loaded. In my case, you could be browsing views/pages in the SPA before authenticating.
MVC View Code Snippet (Views/Home/Index.cshtml)
...
<li>
#if (#User.Identity.IsAuthenticated)
{
User Logged In: #User.Identity.Name
}
else
{
User Logged In: Annon
}
</li></ul>
<div ng-app="app">
<div ng-view></div>
</div>
....
I have working the root redirect, after login, the page hard refreshes if json.redirect is set to '/'. However, if its set to the current page, i.e. '#/about', Angular handles the routing and therefore no hard refresh occurs, thus the menu is not updated.
Ajax Login Code Snippet (App/ajaxlogin.js)
... part of login/register function
if (json.success) {
window.location = json.redirect || location.href;
} else if (json.errors) {
displayErrors($form, json.errors);
}
...
Is this possible to do using my current setup? Or do I need to move the menu somewhere inside the SPA and use Angular to determine what menu to show? If the latter, direction in how to best do this? I'm new to both Angular and Breeze.
The TempHire sample in Breeze has a really good way of handling authentication for a SPA (in my opinion at least!) Granted this is using Durandal so you will need to adapt it to Angular, but they are both frameworks doing the same basic principles so good luck! -
Basically, the Controller action has an annotation [Authorize] on the action that the prepare method is calling on the entitymanagerprovider. If a 401 is returned (not authorized) the SPA takes the bootPublic path and only exposes a login route to the user. When the login is successful, the login method tells the window to reload everything, at which time the authorization passes, and the bootPrivate method is called -
shell.js (Durandal, but should be adaptable)
//#region Internal Methods
function activate() {
return entitymanagerprovider
.prepare()
.then(bootPrivate)
.fail(function (e) {
if (e.status === 401) {
return bootPublic();
} else {
shell.handleError(e);
return false;
}
});
}
function bootPrivate() {
router.mapNav('home');
router.mapNav('resourcemgt', 'viewmodels/resourcemgt', 'Resource Management');
//router.mapRoute('resourcemgt/:id', 'viewmodels/resourcemgt', 'Resource Management', false);
log('TempHire Loaded!', null, true);
return router.activate('home');
}
function bootPublic() {
router.mapNav('login');
return router.activate('login');
}
login.js -
function loginUser() {
if (!self.isValid()) return Q.resolve(false);
return account.loginUser(self.username(), self.password())
.then(function() {
window.location = '/';
return true;
})
.fail(self.handleError);
}
The account.loginUser function is basically just an ajax call that passes credentials to the account controller and returns a success or failure. On success you can see the callback is fired for window.location = '/' which does a full reload. On failure simply show an alert or something.