Angular routing after authentication - javascript

Actually I am struggling for correct routing after successful login authentication in complex web app on Angular js 2. I am following following link:
https://github.com/auth0-blog/angular2-authentication-sample
I make understand code but the issue is after successful login if I again change url to /login in again takes me to login screen where I have login form, but my concern is why I have been redirected to login screen although I know current code do so but how can I resolve this and achieve navigation in correct way.
Please help that what is the correct way to achieve the same.

Inside login add a condition to check if id_token is present in localstorage and it is not undefined. If it is present navigate the user to home by using this.router.navigate(['home']);

Assuming you are using a token (like jwt) and localstorage, you can do something like this:
//This could be different, but you must save somewhere the token.
// It will depend on your startegy
// For example, when loggin in, you may save it on localstorage:
localStorage.setItem('currentUser', JSON.stringify(user)); // just an example.
//THEN, you can redirect using the router
this.router.navigate(['yourRoute']);
Hope that can help you! Please, tell me if you want a more detail example.

Related

How to build "Selectable Keep Login" function by Cookie/JWT

I'm using Node(axios,pinia)+Vue3 as frontEnd,and node(express,bcrypt,jsonwebtoken)+MongoDB as BackEnd to build a SPA web.
I use JWT for login authentication and save at localstorage.
Now it only can keep login.
Hoping have Selectable "Keep Login" function like some forum usually have.
(After closing browser/shotdown will need to login again.)
I don't use sessionStorage for this website user often open new tab.Some cross tab problem bother me and I thought cookie might got better solution.
I can imagine only "Always login"/"temp login" can be done likes. But with selectable I can't thought a simple way to apply it.
Like now I'm thought still use LocalStorage(LS) for Vue to run,but also have Session Cookie(as Cookie)(Not sure the name but the cookiewill be deleted when all webs closed).
Keep login need no change for me.If set to temp login, then the setting will be save to JWT,all front/back could know.
Use cache as signal for closing browser,if (temp login)&&(no cookie){clear LS}.
However I wonder the localStorage can be extract so the func will not safty enough? Then a school computer will be disaster
I'm new to cookie/session,and want to know any better way for safty/efficent. I will prevent XSS.
It would be wonderful to have your experienct/Idea!
Poor language and consult at here first,If any describe not clear/too detail please tell me,I will try to edit it, thanks!
The use of JWT is below:
BackEnd use bcrypt verify user password and response a JWT(with userID for db to find,also save to user login record DB) and other basic user info.
Some response data like JWT,basic userinfo will be save in localstorage to let Vue decide display login/admin/different page.
When user send a request(some login-action), JWT will also be send as BearToken to bo verified by backEnd that JWT was record in that user login record.
So JWT is the only security key,the user's login record should have same JWT.
Because it save in localstorage,user must logout!(Despite I can set some limit time.)

redirect to different pages during login and registration in react native

I use context Api for login and logout , but I faced a situation where when login from login page it got page A but when user login direct after registration go to page B , using react navigation please help me, I am new to react native, I think it should change the Initial Route Name depending upon certain condition and how? please help.
Does the user need to enter his credentials to login after registration?
If yes: then you can provide a param to the route indicating that it's a new user and use that param to navigate to a different screen.
If not: then the function that does the login can be reused by both login and registration screen. But it can receive a param indicating the source where that function is being called. Based on the source you can conditionally navigate to one screen or the other.
If you provide code I can translate the above to code.

In react how can redirect to user from one domain to another domain without entering user credentials?

I am new to reactjs, My question is How can I redirect user from one domain to another domain without entering the user credentials.
I have one application where user logged in with his credentials. Then there is some actions list. In that when user click on the link it redirect to new application. But again user has to enter his credentials to sign in the application. To avoid the agin sign in into the application what I have did is while click on the link I have attached the token parameter with href after redirecting to the new domain I get that token from URL by using
queryString.parse(this.props.location.search) then I hit the rest API to check whether token is valid or not, if valid then it redirect to the welcome page instead to show login page again.
Below is my code where I have achieved it but I dont think its a right approach to achieve this may be it will breaking the security.
This is my first application code:
<a className="dropdown-item"
href=`http://localhost:3001/?token=${localStorage.getItem('my_token')}
&userName=${item.name}` target="_blank">
View Job
</a>
and this one is my second application code where I am getting token from url:
constructor(props) {
super(props);
let myToken = queryString.parse(this.props.location.search)
if (myToken.token) {
localStorage.setItem('access_token', myToken.token);
}
}
I know this is not a right way to do the things. cause of that I am here to know how can I achieve that result.If anyone know what is the right way to do that things please guide me or give some example link where someone has done this thing.
If anyone still not understood the question please do the comment so that I can explain it in better way.
any help will be appreciated thanks in advance.

ReactJS - how to setup login pattern?

I'm sorry if this question is a bit vague, but I'm tackling this problem for the first time and any pointer would be useful.
I am building a web app using ReactJS and I need a login system - first page with two fields username / password and submit button. The server returns a token (1234) and this needs to be used in an auth header (Authorization: Bearer 1234) in order to access the protected area.
How should I handle the login and make the browser update itself with the new content available after login?
As the others have pointed out, it is a good idea to use React-Router.
I think you can use pattern like this: You get user inputs and send them via AJAX (with JQuery, Superagent, whatever you want). If the input is valid and user authenticated, the server sends back token with some user info, which can include his roles or permissions. Based on these received data, you can use React-Router to render other component, e.g. welcome page (by calling replaceState on React-Router history object - in flux action for example).
Additionally, you should save this token in a cookie or into a session/local storage (in order to be able to use it on every subsequent request), and the user info could be stored in a Flux store. After saving this user the store emits change event, which should lead to rerender of your root component with the user information you got.
Then, based on the new user roles or permissions in your store, you can have for example ES7 decorator on some of your components deciding, if it displays the actual component or not.
Hope it helps you a bit.

Why the conflicting variables?

I'm getting conflicting results between the facebook javascript SDK and the python requesthandler variables. The Javascript SDK says my user is not logged in, which is correct, while my template variable that comes from the base request handler says that my user is logged in and displays the name of the user. Is there enough info to tell what is wrong or should I paste the code I think is relevant here? A link to the login page that has the error is here. The example I used is called the runwithfriends demo app from facebook and everything with that app worked except using the logic from the app just from a website without requiring the user to be in the iframe of the app.
Plus I can't seem to get the real-time API working. I can only save userID and not refresh user data - why? I have the code but I'm not sure what's most relevant but here's some of the request handler, the relevant code is basically exactly the same as the one from the demo app:
def render(self, name, **data):
logging.debug('render')
"""Render a template"""
if not data:
logging.debug('no data')
data = {}
data[u'js_conf'] = json.dumps({
u'appId': facebookconf.FACEBOOK_APP_ID,
u'canvasName': facebookconf.FACEBOOK_CANVAS_NAME,
u'userIdOnServer': self.user.id if self.user else None,
})
data[u'logged_in_user'] = self.user #variable that is the problem
data[u'message'] = self.get_message()
data[u'csrf_token'] = self.csrf_token
data[u'canvas_name'] = facebookconf.FACEBOOK_CANVAS_NAME
self.response.out.write(template.render(
os.path.join(
os.path.dirname(__file__), 'templates', name + '.html'),
data))
And even more strange, I can also get the application in a state where the javascript SDK says the user is logged in and the template variable logged_in_user says otherwise. Why are the variables conflicting?
Update: Here are screenshots from the strange login flow. I can go to my page and my name from facebook appears:
Then when I go to next page it also looks alright and has my name
But if I log out then I gets in impossible state: my name + logged out
How can I resolve this strange conflict between js and back-end?
Update: Since I only have this problem for one of my apps I can take what works from my other app and integrate. This page seems to work from my other app: http://cyberfaze.appspot.com/file/20985
Your 'user' is probably referring to the Django user not the Facebook user. Make sure you synchronize the two accounts correctly using a custom authentication backend. It's possible that the accounts get out of sync i.e. if the user switches browsers.
Keep in mind that the Facebook Python SDK will stop working after October 1st unless they update it to Oauth2.0 which is unlikely.
I just updated django-facebook-graph to work with the new authentication flow.

Categories