Sequrity in Authentication a user - express

I write toy-server on Node and i want to create system authentication a user. For that purpose i install express and express-session.
This setting exprerss-session
app.use(session({
key: 'user_sid',
secret: 'somerandomstuffs',
resave: false,
saveUnitialized: false,
cookie: {
expires: 600000 }
While new user signup or a user login, i regenerate session with the function - res.session.regenerate() and create new the req propertie
req.session.user = User.dataValues
The problem is begin if the user want to edit his account. I think do this
if(req.session.user && req.cookies.user_sid)
{ user can change his account }
else { res.redirect('/login') }
But i'm afraid this is not enough. I want not install another program, i want make this as simple as i could.

Related

OIDC-react signtOut doesn't end Cognito session

My stack: oidc-react, Amazon Cognito
When I log out on the site and call auth.signOut();, the userManager signs out the user and redirects to the login page, but when you log in again by calling auth.signIn(); makes a request to Cognito with the token it has, but won't ask for credentials and logs the user in, I guess because the user still has a running session with the same token, if I am right. It only asks for login credentials after an hour because the session expires after 60minutes.
I want Congito to ask for credentials after signing out. I've tried passing the config these options after some research, but doesn't seem to be working:
revokeTokenTypes: (["access_token", "refresh_token"]),
revokeTokensOnSignout: true,
automaticSilentRenew: false,
monitorSession: true
This is the OIDC setup I pass to the provider:
const oidcConfig: AuthProviderProps = {
onSignIn: (user: User | null) => {
console.log("onSignIn");
},
onSignOut: (options: AuthProviderSignOutProps | undefined) => {
console.log('onSignOut');
},
autoSignIn: false,
loadUserInfo: true,
postLogoutRedirectUri: "localhost:3000/",
automaticSilentRenew: false,
authority: "https://" + process.env.REACT_APP_AWS_COGNITO_DOMAIN,
clientId: process.env.REACT_APP_AWS_COGNITO_CLIENT_ID,
redirectUri: window.location.origin,
responseType: 'code',
userManager: new UserManager({
authority: "https://" + process.env.REACT_APP_AWS_COGNITO_DOMAIN,
client_id: process.env.REACT_APP_AWS_COGNITO_CLIENT_ID!,
redirect_uri: window.location.origin,
revokeTokenTypes: (["access_token", "refresh_token"]),
revokeTokensOnSignout: true,
automaticSilentRenew: false,
monitorSession: true
})
};
AWS Cognito does not yet implement the RP Initiated Logout specification or return an end_session_endpoint from its OpenID Connect discovery endpoint. I expect this is your problem, since the library is probably implemented in terms of these standards.
Instead, AWS Cognito uses these parameters and a /logout endpoint. In my apps I have implemented Cognito logout by forming a URL like this, then redirecting to it by setting location.href to the URL value:
public buildLogoutUrl(): string {
const logoutReturnUri = encodeURIComponent(this._configuration.postLogoutRedirectUri);
const clientId = encodeURIComponent(this._configuration.clientId);
return `${this._configuration.logoutEndpoint}?client_id=${clientId}&logout_uri=${logoutReturnUri}`;
}
This will enable you to end the Cognito session and force the user to sign in again. It will also enable you to return to a specific location within your app, such as a /loggedout view.

not able delete session in passport github strategy

I am using passport js to access the Github API. My versions are
passport#0.4.0,passport-github2#0.1.11,express-session#1.17.0,express#4.17.1.
Am able to get access token and access github api successfully but not able to log out properly. I am using the following code.
app.use(session({ secret: 'secret key', resave: true, saveUninitialized: true ,cookie: { maxAge: 100000 } }));
app.use(passport.initialize());
app.use(passport.session());
app.get('/logout',function(req,res){
req.logout();
req.session.destroy(function (err) {
if (err) { return next(err); }
res.redirect('/login');
});
})
when i click log out button in my app, it was logged out and not able to access authenticated URL. My problem is when i access https://github.com/ in another tab the user session is still active. How to revoke the access token?. I don't want to use OAuth Authorizations API, its going to be removed on November, 13, 2020.

How to include TOTP MFA in AWS Cognito authentication process

I'm using Cognito user pools to authenticate my web application. I've got it all working right now but now I need to enable MFA for it. This is how I do it right now (all the code provided are server-side code):
Signing up the user:
const cognito = new AWS.CognitoIdentityServiceProvider();
cognito.signUp({
ClientId,
Username: email,
Password,
}).promise();
An email is sent to the user's address (mentioned as username in the previous function call) with a code inside.
The user reads the code and provides the code to the next function call:
cognito.confirmSignUp({
ClientId,
ConfirmationCode,
Username: email,
ForceAliasCreation: false,
}).promise();
The user logs in:
const tokens = await cognito.adminInitiateAuth({
AuthFlow: 'ADMIN_NO_SRP_AUTH',
ClientId,
UserPoolId,
AuthParameters: {
'USERNAME': email,
'PASSWORD': password,
},
}).promise();
I'm pretty happy with this process. But now I need to add the TOTP MFA functionality to this. Can someone tell me how these steps will be changed if I want to do so? BTW, I know that TOTP MFA needs to be enabled for the user pool while creating it. I'm just asking about how it affects my sign-up/log-in process.
Alright, I found a way to do this myself. I must say, I couldn't find any documentation on this so, use it at your own risk!
Of course, this process assumes you have a user pool with MFA enabled (I used the TOTP MFA).
Signing up the user:
const cognito = new AWS.CognitoIdentityServiceProvider();
cognito.signUp({
ClientId,
Username: email,
Password,
}).promise();
An email is sent to the user's address (mentioned as username in the previous function call) with a code inside.
The user reads the code and provides the code to the next function call:
cognito.confirmSignUp({
ClientId,
ConfirmationCode: code,
Username: email,
ForceAliasCreation: false,
}).promise();
The first log in:
await cognito.adminInitiateAuth({
AuthFlow: 'ADMIN_NO_SRP_AUTH',
ClientId,
UserPoolId,
AuthParameters: {
'USERNAME': email,
'PASSWORD': password,
},
}).promise();
At this point, the return value will be different (compared to what you'll get if the MFA is not enforced). The return value will be something like:
{
"ChallengeName": "MFA_SETUP",
"Session": "...",
"ChallengeParameters": {
"MFAS_CAN_SETUP": "[\"SOFTWARE_TOKEN_MFA\"]",
"USER_ID_FOR_SRP": "..."
}
}
The returned object is saying that the user needs to follow the MFA_SETUP challenge before they can log in (this happens once per user registration).
Enable the TOTP MFA for the user:
cognito.associateSoftwareToken({
Session,
}).promise();
The previous call is needed because there are two options and by issuing the given call, you are telling Cognito that you want your user to enable TOTP MFA (instead of SMS MFA). The Session input is the one return by the previous function call. Now, this time it will return this value:
{
"SecretCode": "...",
"Session": "..."
}
The user must take the given SecretCode and enter it into an app like "Google Authenticator". Once added, the app will start showing a 6 digit number which is refreshed every minute.
Verify the authenticator app:
cognito.verifySoftwareToken({
UserCode: '123456',
Session,
}).promise()
The Session input will be the string returned in step 5 and UserCode is the 6 digits shown on the authenticator app at the moment. If this is done successfully, you'll get this return value:
{
"Status": "SUCCESS",
"Session": "..."
}
I didn't find any use for the session returned by this object. Now, the sign-up process is completed and the user can log in.
The actual log in (which happens every time the users want to authenticate themselves):
await cognito.adminInitiateAuth({
AuthFlow: 'ADMIN_NO_SRP_AUTH',
ClientId,
UserPoolId,
AuthParameters: {
'USERNAME': email,
'PASSWORD': password,
},
}).promise();
Of course, this was identical to step 4. But its returned value is different:
{
"ChallengeName": "SOFTWARE_TOKEN_MFA",
"Session": "...",
"ChallengeParameters": {
"USER_ID_FOR_SRP": "..."
}
}
This is telling you that in order to complete the login process, you need to follow the SOFTWARE_TOKEN_MFA challenge process.
Complete the login process by providing the MFA:
cognito.adminRespondToAuthChallenge({
ChallengeName: "SOFTWARE_TOKEN_MFA",
ClientId,
UserPoolId,
ChallengeResponses: {
"USERNAME": config.username,
"SOFTWARE_TOKEN_MFA_CODE": mfa,
},
Session,
}).promise()
The Session input is the one returned by step 8 and mfa is the 6 digits that need be read from the authenticator app. Once you call the function, it will return the tokens:
{
"ChallengeParameters": {},
"AuthenticationResult": {
"AccessToken": "...",
"ExpiresIn": 3600,
"TokenType": "Bearer",
"RefreshToken": "...",
"IdToken": "..."
}
}

Authentification with ldap without user's password

I am trying to create login authentication with ldap js. I set up all Credentials and everything is working fine, but the problem is I can bind a user just with his Uid (user id aka username), it didn't ask for a password and I don't know how to fix this it must ask for Uid and userPAssword to connect
I tried to connect to with the same credentials including userPassword but it didn't work for me
ldapConfig.js
in this file i set up all ldap config
'url': 'ldap://*************',
'port': '***',
'timeout': '',
'connectTimeout': '',
'secret': '**********',
'reconnect': true,
'filtre': '(&(ObjectClass=*******)',
'search_dn': 'ou=******,dc=****,dc=****',
'domain': 'cn=******,dc=****,dc=****'
login.js
in this file i tried to connect to ldap server and it work realy fine and then i want to get user by uid
const server = ldapConfig.url
const ldapDomain = ldapConfig.domain
const password = ldapConfig.secret
const searchDomain = ldapConfig.search_dn
const client = ldap.createClient({
url: server
})
client.bind(ldapDomain, password, err => {
assert.ifError(err)
})
const opts = {
scope: 'sub',
filter: ldapConfig.filtre + `(mail=${request.body.mail}))`
}
client.search(searchDomain, opts, (err, res) => {
assert.ifError(err)
res.on('searchEntry', entry => {
console.log(entry.object)
} )
I hope it's clear . Thanks
Unauthenticated bind (a seemingly successful bind when you supply a userID and null password) may be enabled in your directory. If you are using OpenLDAP, as the quesstion tags indicate, check slapd.conf for allow bind_anon_cred.
Unless there is a specific need for unauthenticated bind, I disable it on the directory servers. In the rare cases where unauthenticated bind is required, all applications authenticating against the directory need to validate user input before attempting to bind -- that is, verify that the input username and password values are not null.

how do I can generate sessions in server for logged in users only , with Express, Express-session, Passport and Connect-mongo?

I'm using express-session, passport, connect-mongo and mongodb-atlas last versions, for create sessions and save them on the server, the
problem is when app.use(passport.session()), this session is created even if the user is not logged in.
app.use(session({
// key: "id",
secret: process.env.SESSION_SECRET,
cookie: {
httpOnly: true,
sameSite: true,
// secure: process.env.IN_PROD,
maxAge: 10800000,
}, // three hours in miliseconds
store: new MongoStore({
mongooseConnection: mongoose.connection,
autoReconnect: true,
collection: "admin.mySessions",
serialize: serialize
}),
resave: false,
saveUninitialized: false,
name: 'Id'
}));
this causes that when passport is initialized and the passport session
the cookie is saved with session id and the session is saved in the
mongodb
mi question is how save session only for users logged in
Hello mate I am not aware of mongo-session, but from your explanation I understand that you are creating token for users even if they don't login. I suggest you create a new token each time a user hits login API and expire the token once he logs out.By following this token is generated only for active users.