How can I have a seperate login page using Durandal that has a different layout then the shell? - durandal

I've read through Durandal login page redirect pattern wow, lots of code to do what I'd think would be pretty simple.
I've also read through https://groups.google.com/forum/#!topic/durandaljs/RdGpwIm1oOU as I'd like the login page to have a simple logo with a login form, but I'd also like routing for a registration and about page as well. The rest of my site will have a menu, header, etc which I don't want to show until the user is logged in. Also, I'm not sure how this approach would update when the user logs in.
Another code example that almost does what I want to do: https://github.com/Useful-Software-Solutions-Ltd/Durandal451/blob/master/Durandal451v2/App/global/session.js
So, what should I do? Is there an official way to do this? There seems to be a mish mash of things out there that people have tried. I would think this would be a really common occurrence but couldn't find anything on the main docs.

I'm not sure this is the simplest way, but this is what I got
you will need to add some extra function after app.start() is triggered.
main.js
var auth = require('authentication'); // Authentication module
app.start().then(function()
{
// This function will wait for the promise
auth.init().then(function(data)
{
// When successfully authenticate, set the root to shell
app.setRoot('views/shell');
}
});
authentication.js
define(function(require)
{
var app = require('durandal/app');
return {
init: function()
{
// Initialize authentication...
return system.defer(function(dfd)
{
// Check if user is authenticate or if there has stored token
var isAuthenticate = someOtherFunctiontoCheck();
if (isAuthenticate)
{
dfd.resolve(true); // return promise
}
else
{
// When not authenticate, set root to login page
app.setRoot('views/login');
}
}
}
};
});
good luck! :)
UPDATE
login.js
define(function(require)
{
var ko = require('knockout');
var auth = require('authentication');
var username = ko.observable();
var password = ko.observable();
return {
username: username,
password: password,
submitForm: function()
{
// Do a login, if success, auth module will take care of it
// and here will take of the error
auth.login(username(), password()).error(function()
{
// notify user about the error (e.g invalid credentials)
});
}
};
});
Authentication.js
define(function(require)
{
var app = require('durandal/app');
return {
init: function()
{
// Initialize authentication...
return system.defer(function(dfd)
{
// Check if user is authenticate or if there has stored token
var isAuthenticate = someOtherFunctiontoCheck();
if (isAuthenticate)
{
dfd.resolve(true); // return promise
}
else
{
// When not authenticate, set root to login page
app.setRoot('views/login');
}
}
},
login: function(username, password)
{
// do authenticate for login credentials (e.g for retrieve auth token)
return $.ajax({
url : 'api/login',
type : 'POST',
data : {
username: username,
password: password
}
}).then(function(token){
// on success, stored token and set root to shell
functionToStoreToken(token);
// Set root to shell
app.setRoot('views/shell');
});
}
};
});

Related

auth0 checkSession({}) returns login_required when logged in through social provider, but not when logging in via username/password

I have an Angular app that uses Auth0 for authentication, and I'm trying to use checkSession({}, …) to persist a user's session if the token hasn't expired yet.
When I log in with my username/pw that I set up for the site, this works fine when I reload the browser/navigate directly to a resource. However, when I log in using a social provider (such as Google), the checkSession({}, …) call on a page reload returns an error and forces the user to log in again.
Some of the relevant code (mostly from the auth0 tutorial(s)):
export class AuthService {
// Create Auth0 web auth instance
private _auth0 = new auth0.WebAuth({
clientID: AUTH_CONFIG.CLIENT_ID,
domain: AUTH_CONFIG.CLIENT_DOMAIN,
responseType: 'token',
redirectUri: AUTH_CONFIG.REDIRECT,
audience: AUTH_CONFIG.AUDIENCE,
scope: AUTH_CONFIG.SCOPE
});
accessToken: string;
userProfile: any;
expiresAt: number;
// Create a stream of logged in status to communicate throughout app
loggedIn: boolean;
loggedIn$ = new BehaviorSubject<boolean>(this.loggedIn);
loggingIn: boolean;
isAdmin: boolean;
// Subscribe to token expiration stream
refreshSub: Subscription;
constructor(private router: Router) {
// If app auth token is not expired, request new token
if (JSON.parse(localStorage.getItem('expires_at')) > Date.now()) {
this.renewToken();
}
}
...
handleAuth() {
// When Auth0 hash parsed, get profile
this._auth0.parseHash((err, authResult) => {
if (authResult && authResult.accessToken) {
window.location.hash = '';
this._getProfile(authResult);
} else if (err) {
this._clearRedirect();
this.router.navigate(['/']);
console.error(`Error authenticating: ${err.error}`);
}
this.router.navigate(['/']);
});
}
private _getProfile(authResult) {
this.loggingIn = true;
// Use access token to retrieve user's profile and set session
this._auth0.client.userInfo(authResult.accessToken, (err, profile) => {
if (profile) {
this._setSession(authResult, profile);
this._redirect();
} else if (err) {
console.warn(`Error retrieving profile: ${err.error}`);
}
});
}
private _setSession(authResult, profile?) {
this.expiresAt = (authResult.expiresIn * 1000) + Date.now();
// Store expiration in local storage to access in constructor
localStorage.setItem('expires_at', JSON.stringify(this.expiresAt));
this.accessToken = authResult.accessToken;
this.userProfile = profile;
if (profile) {
this.isAdmin = this._checkAdmin(profile);
}
...
}
...
get tokenValid(): boolean {
// Check if current time is past access token's expiration
return Date.now() < JSON.parse(localStorage.getItem('expires_at'));
}
renewToken() {
// Check for valid Auth0 session
this._auth0.checkSession({}, (err, authResult) => {
if (authResult && authResult.accessToken) {
this._getProfile(authResult);
} else {
this._clearExpiration();
}
});
}
}
(This is from a service that is called in many places within the app, including some route guards and within some components that rely on profile information. If more of the app code would be useful, I can provide it.)
Also note: AUTH_CONFIG.SCOPE = 'openid profile email'
So, the issue appears to not have been related to my app at all. When using Social Providers, Auth0 has an explicit note in one of their tutorials that really helped me out:
The issue with social providers is that they were incorrectly configured in my Auth0 dashboard, and needed to use provider-specific app keys.
Important Note: If you are using Auth0 social connections in your app,
please make sure that you have set the connections up to use your own
client app keys. If you're using Auth0 dev keys, token renewal will
always return login_required. Each social connection's details has a
link with explicit instructions on how to acquire your own key for the
particular IdP.
Comment was found on this page: https://auth0.com/blog/real-world-angular-series-part-7/

Nuxt.js middleware redirect based on role

On login I want to redirect to different page based on role using the nuxt.js middleware.
This is my notAuthenticated middleware
export default function({ store, redirect }) {
// If the user is authenticated redirect to home page
if (store.state.auth) {
debugger
if (store.state.auth.role === 'admin') {
return redirect('/admin')
} else {
return redirect('/')
}
}
}
Problem is it does not redirect to /admin and I don't know how to debug it. Debugger is not working here.
Seems middleware didn't redirect me after login, so I had to use the router and redirect based on the role after the login has completed.
EDIT: As asked I'm adding also the code solution.
In my login function, after logging in I check the role of the user (which in my case was saved in the JWT token).
login(data) {
const self = this
this.$axios.post('/auth/login', data).then(function(response) {
const tkData = self.parseJwt(response.data.Token)
const auth = {
accessToken: response.data.Token,
email: tkData.email,
role: tkData.role
}
self.$store.commit('setAuth', auth)
Cookie.set('auth', auth)
if (tkData.role === 'admin') {
self.$router.push('/admin')
} else {
self.$router.push('/')
}
})
}
PS: You can check out my code and test it in my GitHub

Auth0 login redirect to page keeps on loading when using Firefox as browser

I use an Auth0 login that handles the login for my platform after logging in it redirects you to the platform. With chrome, this works perfectly but in Firefox it keeps reloading the redirect page. I used the standard auth0 code to implement the logic into my page. I'm not sure what is going wrong and even where to start looking for a solution? Does anyone ever experienced the same bug and can help me fix the issue and also explain what is going wrong?
auth.ts file :
export class AuthService {
// Create an observable of Auth0 instance of client
auth0Client$ = (from(
createAuth0Client({
domain: authConfig.domain,
client_id: authConfig.clientId,
redirect_uri: `${window.location.origin}`,
audience: authConfig.audience,
})
) as Observable<Auth0Client>).pipe(
shareReplay(1), // Every subscription receives the same shared value
catchError(err => throwError(err))
);
// Manage Acces Token
// Observable method to retrieve access token and make it available for use in application
getTokenSilently$(options?): Observable<string> {
return this.auth0Client$.pipe(
concatMap((client: Auth0Client) => from(client.getTokenSilently(options)))
);
}
// Define observables for SDK methods that return promises by default
// For each Auth0 SDK method, first ensure the client instance is ready
// concatMap: Using the client instance, call SDK method; SDK returns a promise
// from: Convert that resulting promise into an observable
isAuthenticated$ = this.auth0Client$.pipe(
concatMap((client: Auth0Client) => from(client.isAuthenticated())),
tap(res => (this.loggedIn = res))
);
handleRedirectCallback$ = this.auth0Client$.pipe(
concatMap((client: Auth0Client) => from(client.handleRedirectCallback()))
);
// Create subject and public observable of user profile data
private userProfileSubject$ = new BehaviorSubject<any>(null);
userProfile$ = this.userProfileSubject$.asObservable();
// Create a local property for login status
loggedIn: boolean = null;
constructor(private router: Router) {
// On initial load, check authentication state with authorization server
// Set up local auth streams if user is already authenticated
this.localAuthSetup();
// Handle redirect from Auth0 login
this.handleAuthCallback();
}
// When calling, options can be passed if desired
// https://auth0.github.io/auth0-spa-js/classes/auth0client.html#getuser
getUser$(options?): Observable<any> {
return this.auth0Client$.pipe(
concatMap((client: Auth0Client) => from(client.getUser(options))),
tap(user => this.userProfileSubject$.next(user))
);
}
private localAuthSetup() {
// This should only be called on app initialization
// Set up local authentication streams
const checkAuth$ = this.isAuthenticated$.pipe(
concatMap((loggedIn: boolean) => {
if (loggedIn) {
// If authenticated, get user and set in app
// NOTE: you could pass options here if needed
return this.getUser$();
}
// If not authenticated, return stream that emits 'false'
return of(loggedIn);
})
);
checkAuth$.subscribe();
}
login(redirectPath: string = '/') {
// A desired redirect path can be passed to login method
// (e.g., from a route guard)
// Ensure Auth0 client instance exists
this.auth0Client$.subscribe((client: Auth0Client) => {
// Call method to log in
client.loginWithRedirect({
redirect_uri: `${window.location.origin}`,
appState: { target: redirectPath },
});
});
}
private handleAuthCallback() {
// Call when app reloads after user logs in with Auth0
const params = window.location.search;
if (params.includes('code=') && params.includes('state=')) {
let targetRoute: string; // Path to redirect to after login processsed
const authComplete$ = this.handleRedirectCallback$.pipe(
// Have client, now call method to handle auth callback redirect
tap(cbRes => {
// Get and set target redirect route from callback results
targetRoute = cbRes.appState && cbRes.appState.target ? cbRes.appState.target : '/';
}),
concatMap(() => {
// Redirect callback complete; get user and login status
return combineLatest([this.getUser$(), this.isAuthenticated$]);
})
);
// Subscribe to authentication completion observable
// Response will be an array of user and login status
authComplete$.subscribe(([user, loggedIn]) => {
// Redirect to target route after callback processing
this.router.navigate([targetRoute]);
});
}
}
logout() {
// Ensure Auth0 client instance exists
this.auth0Client$.subscribe((client: Auth0Client) => {
// Call method to log out
client.logout({
client_id: authConfig.clientId,
returnTo: window.location.origin,
});
});
}
}
auth-guard.ts
export class AuthGuard implements CanActivate {
constructor(private auth: AuthService) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> | Promise<boolean | UrlTree> | boolean {
return this.auth.isAuthenticated$.pipe(
tap(loggedIn => {
if (!loggedIn) {
this.auth.login(state.url);
}
})
);
}
}
I had this issue and found that it was because my browser was blocking third party cookies.
So my app was running on my own domain (or on localhost in dev mode), but I was using an auth0.com subdomain to log in with Auth0 and the browser was blocking cookies from auth0.com, which sent the auth0 JS in my app into an infinite loop of trying to check the logged in status, failing, refreshing the page, trying to check the logged in status, failing, refreshing the page, and so on.
It could be your browser's cookie settings or an ad blocking or privacy extension.

Auth0 re-login after token expire does not display login window

I'm working with Auth0, I have a problem where after user token expire and user try to relogin, it doesn't redirect user to login window at all instead it just automatically logged in when user click on login link.
They are fine if I manually log out then re-login, then it will ask for authentication again.
I tried removing all the localstorage memory regarding the user but it still doesn't fix it.
export const expiredAtKey = 'expired_at';
export const uidKey = 'uid';
export const urlStateKey = 'urlState';
#Injectable()
export class Auth {
auth0 = new auth0.WebAuth({
clientID: environment.auth0ClientId,
domain: environment.auth0Domain,
responseType: 'token id_token',
redirectUri: `${constants.ORIGIN_URL}/auth`,
scope: 'openid email'
});
constructor(private router: Router,
public dialog: MatDialog,
private http: HttpClient) {
}
public handleAuthentication(): void {
this.auth0.parseHash(this.handleAuthResult);
}
public login() {
//I have tried to clear local storage everytime user call login to prevent this to happen, but it still skip the login window
this.clearLocalStorage();
localStorage.setItem(urlStateKey, location.pathname);
this.auth0.authorize();
};
public signUp(email, password, cb) {
this.auth0.signupAndAuthorize({
email: email,
password: password,
connection: environment.auth0Connection
}, cb);
}
public authenticated() {
const exp = localStorage.getItem(expiredAtKey);
if (!exp) {
return false;
}
const expiresAt = JSON.parse(localStorage.getItem(expiredAtKey));
return new Date().getTime() < expiresAt;
};
public logout() {
this.clearLocalStorage();
window.location.href = `https://${ environment.auth0Domain }/v2/logout?returnTo=${ constants.ORIGIN_URL }`;
};
public setSession(authResult): void {
const idToken = jwtDecode(authResult.idToken);
localStorage.setItem('idToken', authResult.idToken);
localStorage.setItem(uidKey, idToken.email);
localStorage.setItem('userId', idToken.sub);
const expiresAt = JSON.stringify(idToken.exp * 1000);
localStorage.setItem(expiredAtKey, expiresAt);
}
private handleAuthResult = (err, authResult) => {
if (err) {
if (!environment.production) {
console.log(err);
}
if(err.errorDescription === "Please verify your email before logging in."){
this.dialog.open(
ErrorDialogComponent,
{ data: "Please verify your email before logging in."}
);
this.router.navigate(['/initiatives'])
}else{
this.dialog.open(
ErrorDialogComponent,
{ data: "An error occurred while trying to authenticate. Please ensure private browsing is disabled and try again."}
);
this.router.navigate(['/initiatives'])
}
} else if (authResult && authResult.idToken && authResult.idToken !== 'undefined') {
this.setSession(authResult);
const path = localStorage.getItem(urlStateKey);
this.router.navigateByUrl(path);
}
};
clearLocalStorage() {
localStorage.removeItem(expiredAtKey);
localStorage.removeItem(uidKey);
localStorage.removeItem(urlStateKey);
localStorage.removeItem('userId')
}
}
I want user to do the authentication again after the token is expired.
This is happening due to SSO cookie set in the server to maintain the session. To clear the server-side session, you need to redirect the user to /logout endpoint when token expires. The logout method does that.
https://auth0.com/docs/sso/current/single-page-apps

Chrome extensions: issue with identity.launchWebAuthFlow

I'm tring to login via my own service. This is what I have now:
manifest.json
"background": {
"scripts": ["background.js"]
}
background.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.create({
url: 'index.html'
});
});
index.html is where all the extension's logic resides. Here I have a function that starts authentication process:
function goLogin(callback)
{
var redirectUrl = chrome.identity.getRedirectURL('receiveToken');
chrome.identity.launchWebAuthFlow({
url: 'http://todolist.dev/app_dev.php/login?response_type=token&redirect_url=' + redirectUrl,
interactive: true
}, function(redirectUrl) {
if (!redirectUrl) {
return;
}
// Get an access token from the url and save it in localStorage
var queryString = decodeURIComponent(redirectUrl.substr(redirectUrl.indexOf('?') + 1));
var params = queryString.split('&');
var accessToken = null;
for (var i = 0; i < params.length; i++) {
params[i] = params[i].split('=');
if (params[i][0] == 'access_token') {
accessToken = params[i][1];
break;
}
}
localStorage.setItem('accessToken', accessToken);
callback();
});
}
The problem is that the popup with the service's login page sometimes doesn't open or opens and closes automatically with the response that the user didn't approve access. Sometimes when the popup opens and I try to login with wrong credentials several times, the popup closes automatically as well (with the same "you didn't approve access" response). In the backend I don't have any restrictions to a number of login attempts.
In the backend I have a FOSUserBundle with overridden AuthenticationSuccessHandler (it does what the default success handler does + returns an access token).