reset user login session in angularjs - angularjs

I store user auth info and token in a cookie locally for my angular/typescript SPA. Cookie expires after a certain time I have set. How do I reset expiration while user's activity? (session on the server is reset on users requests)
I mean what would be the best way, so I don't code some stupid stuff.
Thank you

I assume you do your authentication and generation of the cookie on the server and your angular side authentication is located in a service.
One way to achieve what you are looking for is to create a method in your client side service to send a request to a known end point of the server which would refresh the cookie. This server endpoint will refresh the cookie and will return a HTTP 200 code.
Once you have this code in place, you can call it when the user interact with the application (ex navigation across views via $locationChangeStart, $routeChangeStart etc).

Related

ReactJs How to check user authenticated and sessionID generated by ExpressJs

I have a Nodejs application creating a session when the user gets authenticated.
I see that Expressjs stores the sessionID in a cookie which at the moment is HttpOnly and the session info itself is stored server side.
How to check that the user is authenticated and there is an open session from ReactJS (that is, browser side)?
I think that the only way is to try and access that sessionID? What is a good way of implementing this?
Thanks.
The register or login should respond with the necessary user information to the client side on React so that user information could be stored in the application state (Redux/Flux). The sessionId stored as HttpOnly cookie by express server is solely for the purpose of Express to uniquely distinguish a browser session.
Ideally you would need another API as well to return the user information which at the Express server side should read the sessionId cookie and return with the currentUser information back to the client. Suppose, you login and the user information is stored in the UI application state, and when you refresh the browser, this application state would get flushed off. In such a scenario, this API would help to restore the application state with the current logged in user information. Hope this helps.

How safe is it to save session locally in AngularJS?

So this is my structure:
HTML form sends authentication to nodejs.
Authenticate using passportjs > res.send the userid with jwt-simple (json web token).
The received info is saved in $localStorage.user. I use that info in any of the controllers needed and include it and send my post/get requests to nodejs.
I decode the info in nodejs and query the DB.
Is this safe? Is this how it works in real world?
Many thanks.
#Somename:
The workflow which you have mentioned is slightly correct.
The ideal way to get passport authentication done is,
User log's in entering his username and passport.
Send a post request with these form data.
Authenticate the credentials using Passport. Using the passport.authenticate will invoke the serializeUser and get you the valid user if it exists. Else we return a login error response.
A Successful login will automatically create a session in back end, save it in the sessionStorage and adds it with the response.
This cookie will be saved automatically into browser's local storage once the response is fetched at client side.
Every time we send a subsequent API request we need to include this cookie in the req headers.
This cookie should be validated each time in back end. passport.authorize will again make use of the cookie and check if the session is valid.
Logout session once the User logs out.
Hope I've made things clear for you.

angularjs client and spring backend user login and session management

I have a mobile website written in angularjs, with my backend in Spring Boot. Right now, I have my own login page and can login a user without any trouble. However, if the user ever clicks "back", "refresh", etc., the client loses the user's id and login info (obtained from server on login). I need to make sure that this info is maintained and clicking "back" or "refresh" doesn't break everything.
Secondly, a user that knows the url's after login can type those url's in the browser and access them without logging in. I can stop them accessing anything on the server, but not sure what I can do on the client to redirect them to a login page in this case.
Any help would be greatly appreciated!
You should keep in mind that everything running in browser is stateless, there's no way to keep trace of the previous state.
Right now, if the user performs a refresh (or another similar action), Angular loses everything (AuthData included).
You have many way to work around that limit:
Perform an http request after the application bootstrap (have a look at the angular.module().run method
Save a cookie and use the server to print initial data layer directly on the dom via json
Save on local/session storage
Personally, I prefer cookies because that lets the server to work decoupled from the client.
In reference to your comment..."if the user ever clicks "back", "refresh", etc., the client loses the user's id and login info (obtained from server on login)."
Is there any reason you need to maintain the user id or login info after a successful authentication?
If Spring Security is setup for basic authentication, after a successful login, a Session Cookie will be sent back on the response to the client. On all subsequent requests to the server, the same Session Cookie will be sent on the request and the previously authenticated session will be re-established. You just need to ensure that your Angular client is passing cookies when issuing requests.
Take a look at this sample on how this is done.

How to stop Web API getting 401 when using OWIN Cookie authentication

I have a web app which is MVC 5 using OWIN cookie authentication. It also uses AngularJS from which web api calls are made. The Angular code is only invoked after the user has successfully logged in and been authenticated and everything works as you would expect.
However, can someone please explain what component (Chrome, OWIN, IIS, ...) is responsible for eventually issuing a 401 if the user has been idle for 20 or so minutes. In MVC this is not a problem because the redirect automatically re-authenticates but with web api my only option is to get the user to log back in again.
Ok so thats the first thing, who is responsible for timing the session out and giving the 401 (and can i alter it) but ALSO is there any way to get web api calls to keep the session alive so that even if the user is idle the api calls stop it timing out?
Specifically, I have implemented SignalR in a way that the signal to the client results in the client issuing an api call to refresh its data. I realise i could push the refresh but at the moment thats a bit tricky. So whats happening is the updates are occuring nicely but eventually this results in a 401 which i want to avoid.
below is an ideal flow
server logs in => creates cookie sets expiration time, passes it to client
client saves cookies & passes it with each request
server checks the cookies for validity including expiration time
if invalid or expired, server responds with 401
the cookie expiration time can be configured in the CookieAuthenticationOptions. See file ~/App_Start/Startup.Auth.cs
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
ExpireTimeSpan=TimeSpan.FromDays(365),
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
Set your ExpireTimeSpan to the desired TimeSpan.
For web api calls that fail authentication you could catch 401's and send back a response that tells the browser it's logged out - you could pop up a login dialog or redirect to login url.

Google OAuth2 flow and id_token refresh

I am having troubles in implementing OAuth in the right way.
I use a client/API architecture (Angular for front and Node.js for back) and I would like user to sign in using Google OAuth authentication only.
Here is what I think is the right way for the moment (tell me if I misunderstood something) :
Angular open a Google popup asking user's consent.
Once the user agree, Google Authorization server sends back to angular a verification code.
This verification code is forwarded to an API endpoint.
Then, the API asks Google Authorization server to exchange this code for an access_token, an id_token and a refresh_token.
Google sends those 3 tokens.
The API uses access_token to retrieve user from Google API
The API persists the user
Here is the little dillema, in my opinion, the access_token and refresh_token should be stored into the database and the id_token should be sent back to Angular client.
This way, it would allow the API to ask for resource in Google API and if the token expires it can still ask for a new token thanks to the refresh_token.
Client-side, the id_token is embedded in all requests thus allowing the API to identify the client and verify his authentication with Google certs from https://www.googleapis.com/oauth2/v3/certs.
Supposing this is right way to use tokens, how could I deal with id_token expiration since client does not have any refresh token ?
Thanks !
I do it slightly different (I have the same basic architecture though).
Angular decides the user needs to log in and displays a login popup.
The url in the login popup is not serviced by angular, but is instead directly run off of the backend server: /auth/google . (I use hapijs and bell, personally).
/auth/google is serviced by a bell plugin and initiates the OAUTH dance.
the end of the OAUTH dance results in my node server generating a local token (I just generate random bytes and store them in redis mapped to user ids)
because the initial login popup was created by window.open, the success page (generated on the api side rather than in angular) can use window.opener.postMessage to communicate the token back to the angular runtime.
This way, all my sensitive google credentials (the user's oauth token, refresh token if needed, and my application's api ID and secret) are only on the server, except for during the OAUTH dance relay when they're in a URL string during the client redirects. This is reasonably secure.
Then for all the actual user interactions with the api, I use the token I generated in step four to authenticate. This could be a JWT if you wanted, but I don't do it that way; I just use redis to map from 'longrandostring' -> userId. That lets me (for example) force everyone to re-login if I wipe the redis database that has all the tokens stored, or I can write a lua script to delete all the entries that map to a certain userid.
If you need a refresh token, you can set access_type=offline in the initial request to oauth2/auth, and you'll get a refresh token as part of the response, unless you've previously gotten a refresh token. You can then persist it on the server side and get new access tokens as needed. If you set approval_prompt=force as well, you'll force a new consent screen and be guaranteed a refresh token (but after some small number of refresh tokens granted to a user, older ones expire on the same application so it's best to only request them if really needed).

Resources