Auto redirect to home/login page at session timeout in mean.js application - angularjs

I am working on a mean.js application, and using the following code for session timeout:
app.use(session({
saveUninitialized: true,
resave: true,
secret: config.sessionSecret,
store: new mongoStore({
db: db.connection.db,
collection: config.sessionCollection
}),
cookie: { maxAge : 1800000 },
rolling: true
}));
It is working perfect. The issue is that when the session expires the page remains in the same state and if the user clicks on any of the links it redirects to the login page.
I need to implement that instead of user click if the session is expired the page should auto redirect to the login page.
Thanks in advance.

mean.js use angular on the client, so your question is the same like
How to redirect to login page after cookie expires in Angular JS?

Finally i got exactly what was required here:
http://hackedbychinese.github.io/ng-idle/

Related

Intermittent problem using loginPopup MSAL JS in a REACT

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"
})

How to reload localStorage saved aws-amplify auth?

I am successfully using AWS Amplify and AWS Cognito for my spa authorization.
The only issue is that when I refresh the page, the auth seems to be lost, even if I see amplify and cognito items in LocalStorage.
This is my configuration section:
Amplify.configure({
Auth: {
oauth: {
domain: 'xxxxx.auth.eu-west-1.amazoncognito.com',
scope: ['phone', 'email', 'profile', 'openid'],
responseType: 'code',
oauth.redirectSignIn: 'http://localhost:3000/',
oauth.redirectSignOut: 'http://localhost:3000/',
},
region: process.env.REACT_APP_REGION,
userPoolId: process.env.REACT_APP_USER_POOL_ID,
userPoolWebClientId: process.env.REACT_APP_USER_POOL_WEB_CLIENT_ID,
storage: localStorage,
},
});
In practice, I don't know how to ask amplify to use localStorage when user is authenticated and app restarts (page reload).
Possibly I should use Auth.currentAuthenticatedUser(), but I suppose I can't call it instead of Auth.configure()...
You can fetch the user from storage by calling Auth.currentAuthenticatedUser().
It isn't properly documented but you can refer to the implementation to see the behavior (amplify team must believe in self-documenting code).

Cookie handling in react and expressjs

I'm trying to send cookie from the server to the react app and use this cookie as auth in the middleware. With the postman, everything is working, but in the browser, it is not.
As I have read some tutorials I need to set up cors and here is the snippet of my server-side app.
app.use(cors({ origin: "http://localhost:3000/", credentials: true }));
res.status(200).cookie("login_auth", token, { httpOnly: true, domain: "http://localhost:3000" }).json({ user });
Then I'm sending the post request
axios.post("http://localhost:5000/user/login", { email, password }, { withCredentials: true })
but when I check the cookie storage for my app there is no cookie and further, I have no idea how to send the cookie back to the server to fulfill the middleware. In postman it is all done so easily.
I can save the cookie with the "js-cookie", but I don't think it is the right way to do it.
Cookies.set("login_auth", response.data.token);
Somebody help?

login and authentication in nextjs with httponly cookies

Hi i am building an application on the react with nextjs
I am calling login API from my client side on that I get a token I want to send to nextjs server and set httponly cookie of that auth token so no client side script has access to that token on logout I want to destroy that cookie
my question is that how to achieve this practically
or do you have any other suggestion of login and authorization with react and nextjs
Practically it looks like in the following steps:
You need create api endpoint in your nextjs app in pages folder.
For login it could be like this pages/api/login/index.js
In this file you need create logic for requesting data from external api
On client side make request to your next api endpoint ...fetch('http://localhost:3000/api/login', options)
When this request came from the client your code in pages/api/login/index.js fetch login data from external api and after success set cookie with httpOnly flag:
import { setCookie } from 'nookies' ... setCookie({ res }, 'name', 'value', { secure: process.env.NODE_ENV === 'production', maxAge: 72576000, httpOnly: true, path: '/' })

Session timeout using SPA and oidc-js

I am using angular 5 with oidc-client and identity server 4. Is session timeout supported in oidc-client or i need to implement it manually ?
By Session Timeout i mean, the user will be logged out after sometime of inactivity
for your SPA applications you can use the implicit flow, refresh token is not possible automatically but oidc-client.js can make it easy for you. you can use the silent refresh, oidc-client will send the active cookie session to get a new access_token just before the expiration of the new one. you need only to configure it
const config = {
authority: xxxxx,
client_id: xxxxx,
popup_redirect_uri: `${OidcConfig.clientRoot}/assets/html/popup-login-redirect.html`,
scope: 'openid profile',
response_type: 'id_token token',
post_logout_redirect_uri: `${OidcConfig.clientRoot}?postLogout=true`, // delet all stored tokens after logout
userStore: new WebStorageStateStore({ store: window.localStorage }),
automaticSilentRenew: true, // enable silent refresh
silent_redirect_uri: `${OidcConfig.clientRoot}/assets/html/silent-refresh-redirect.html` // here when you can get the new tokens
};
here is the content of silent-refresh-redirect.html
<script src="https://cdnjs.cloudflare.com/ajax/libs/oidc-client/1.5.1/oidc-client.min.js"></script>
<script>
var config = {
userStore: new Oidc.WebStorageStateStore({ store: window.localStorage })
};
new Oidc.UserManager(config).signinSilentCallback()
.catch((err) => {
console.log(err);
});
</script>

Resources