I am using the Auth0-js package v9.1 to connect to my React app to a Hosted Page, which internally using Auth0Lock to customize user signup parameters.
What I would like to do is have a link to go to the login tab, and a separate button to connect directly to the Sign Up tab. Is this kind of control possible?
I have a AuthService wrapper class which I'm using to launch the Auth0 Lock client currently.
export class AuthService() {
constructor() {
this.auth0 = new auth0.WebAuth(
{
domain: AUTH0_DOMAIN,
clientID: AUTH0_CLIENT_ID,
redirectUri: AUTH0_REDIRECT_URL,
audience: AUTH0_AUDIENCE_URL,
responseType: 'token id_token',
scope: 'openid profile email'
}
)
}
isAuthenticated() {
// Check whether the session has past the
// access token's expiry time
return ( ! this.isSessionExpired() )
}
// display the Auth0 lock modal and allow the user to log in
login() {
this.auth0.authorize()
}
...
}
export default new AuthService
What I would like to have is a method which links directly to the Sign Up tab, so I can call it from a specialize component
....
signup() {
this.auth0.authorize('signup')
- or alternatively -
this.auth0.signup()
}
....
Is something like this possible? How would I go about linking directly to that Sign Up tab?
Thx
Related
I'm using MSAL JS in order to authenticate users in react application developed using REACT. Sometimes login works perfectly, redirecting users to the home page of the app. Other times login popup opens, users insert their login but then login procedure fails with this error:
hash_empty_error: Hash value cannot be processed because it is empty.
Please verify that your redirectUri is not clearing the hash.
I know this issue was raised before but never seen proper solution how to overcome this error
What worked for me was to set the redirectUri to a blank page or a page that does not implement MSAL. If your application is only using popup and silent APIs you can set this on the PublicClientApplication config like below:
export const msalConfig = {
auth: {
clientId: process.env.REACT_APP_CLIENTID,
authority: `https://login.microsoftonline.com/${process.env.REACT_APP_TENANTID}`,
redirectUri: 'http://localhost:3000/blank.html'
},
cache: {
cacheLocation: "localStorage"
}
}
If your application also needs to support redirect APIs you can set the redirectUri on a per request basis:
msalInstance.loginPopup({
redirectUri: "http://localhost:3000/blank.html"
})
I have an identity server 4 implementation very simple and I'm using the oidc-client on my angular APP to carry on all the security management. In my auth service I have the following:
#Injectable()
export class AuthService {
private manager: UserManager;
private user: User = null;
constructor() {
if (!environment.production) {
Log.logger = console;
}
this.manager = new UserManager(getClientSettings());
this.manager.getUser()
.then(user => {
this.user = user;
});
this.manager.events.addUserSignedOut(() => {
this.user = null;
this.signOut();
});
}
signOut(): Promise<void> {
return this.manager.signoutRedirect()
.then(() => {
this.manager.clearStaleState();
});
}
...more
}
export function getClientSettings(): UserManagerSettings {
return {
authority: environment.authorityUrl,
client_id: 'myclient',
redirect_uri: `${environment.baseUrl}/auth-callback`,
post_logout_redirect_uri: environment.baseUrl,
response_type: 'id_token token',
scope: 'openid profile myapi',
filterProtocolClaims: true,
loadUserInfo: true,
automaticSilentRenew: true,
revokeAccessTokenOnSignout : true,
silent_redirect_uri: `${environment.baseUrl}/silent-renew-callback`,
};
}
Everything works like a charm so I can log in/out without any issues, the token renewal works as expected and so far so good. However I decided to implement a "custom" behavior when a user open the application in multiple tabs on the same browser and one of them logs out. Then the event UserSignedOut is triggered and I sign out the rest of the tabs that may be open. The problem I have is that when the user comes back in, the FIRST login attempt is performed correctly, however any subsequent login request from any other tab results in a 400 - BAD REQUEST (removing the Antiforgery token attribute from the login method in my IS4 it then works but I don't want to do so).
If you did refresh the tab then you get logged in therefore to me it seems something wrong with the actual state itself?
I'm not sure if I should invoke any other method in my AuthService prior logging out or whether I should re-implement the ValidateAntiForgeryToken with a custom behavior for this.
Any help is much appreciated, thanks!
I handle authentication in my Ionic app with a Service. I would like to have View separated from Service. I have a function in auth service to fetch user. If user is not available in memory or database, I want the user to be redirected to Login page. This getUser function is used in different components.
getUser(){
if (this.user) {
return Promise.resolve(this.user) ;
} else {
return this.storage.get('user').then( (user) => {
if (user){
this.user = user;
return user
} else {
\\ way to prompt login page here.
}
})
.catch( this.handleError )
}
}
I would like to have something like a base component to handle login page push when user is not available. As far as I know angular doesn't support component inheritance. How can I achieve the functionality ? What I was thinking was a Subject emitted when no user is available. And the base component subscribe to this subject . How can I achieve this in Ionic ?
I have an angular 2 app with JWT authentication (Auth0) that after user login stores the profile and token id in the localStorage, the profile contains a "role" attribute to check if the user can access an especific page.
Everything works like a charm but if the user change the role property in the localStorage to "admin" for example and reload the app he can access pages that he is not authorized. How can I handle that?
auth.service.ts:
declare var Auth0Lock: any;
#Injectable()
export Class AuthService {
lock = new Auth0Lock(ID, domain);
user: Object;
constructor() {
this.user = JSON.parse(localStorage.getItem('profile'));
}
public login() {
// Auth0 method
this.lock.show({}, (err: string, profile: Object, token: string) => {
if (err) { console.log(err); return; }
localStorage.setItem('profile', JSON.stringify(profile));
localStorage.setItem('id_token', token);
});
}
public logout() {
localStorage.removeItem('profile');
localStorage.removeItem('id_token');
}
public loggedIn() {
return tokenNotExpired();
}
public isAdmin() {
if (this.user['role'] == 'admin') {
return true;
} else {
return false;
}
}
}
app.component.ts:
// imports, etc
export Class AppComponent {
constructor(private auth: AuthService) {}
}
app.component.html:
<nav>
<ul>
<li><a [routerLink]="['Customers']" *ngIf="auth.loggedIn()">Customers</a></li>
<li><a [routerLink]="['Admin']" *ngIf="auth.loggedIn() && auth.isAdmin()">Admin</a></li>
</ul>
</nav>
Any ideas to handle that would be appreciated
In my opinion, it's impossible to create fully secured pages/forms, when you have JavaScript front-end framework. I mean, there is always possibility to open any form, when all application is downloaded to and constructed at client side.
For me, it's important to secure back-end api, and leave "hacking" opportunities to junior developers.
If you have such requirements, try to use server side generated framework: php, asp.net mvc, jsp & etc.
UPDATE
As it came up, Angular2 has directive #CanActivate, which gives more accurate way to cancel navigaition. BUT server side authorization is CRITICAL in javascript front-end based applications.
This will help how to deal with JWT in express back-end: express-jwt
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.