I have to deploy a login page with profile with node js, mongodb and angularjs. Can you suggest me an example of MEAN in mongoDB and not in mongoose? I have to store credentials user's with mongodb and I have to send user's data to the client, not in json.
Thanks
Mongoose is a interface to connect to mongo databases in NodeJs environment. To perform login and send data to client, you can follow these steps:
Send a login request to server.
Verify the user credentials and send a token back to user for proceed with further requests for client data. For this, you can use JWT.
Put an interceptor in angularjs which will automatically associate the token in header with each request corresponds to valid user.
At server end, you can check whether requests consist of token or not. If not, you can send unauthorized in response (401).
Related
So I would like to add SSO using Azure AD.
My stack consists of a React app as frontend and a NestJS API as backend(decoupled). The scenario looks like the following
User clicks login button
I create a new window (popup) which leads the user to the Azure AD login page (step 3 in the diagram)
After the user logs in to Azure AD successfully Azure AD will POST the SAML response to a redirect URL I have provided them (let's say http://myapp.com/saml) (step 5 in the diagram) (This redirect URL, to my understanding, has to be an endpoint in the NestJS api since React frontend can't handle post request.)
NestJS will handle the post request get the info it needs, validates etc etc and then NestJS has to return a Token to the frontend somehow in order for the frontend to store that token in a cookie and be able use it in subsequent requests to the NestJS api so that NestJS will be able to know that this user is logged in. (Step 6)
My issue with this approach is that I don't know how will the client get the token when the the validation is completed from NestJS. If this was a coupled application this would not be an issue since the backend would handle the post request set a cookie and redirect the user. But in this case NestJS can't redirect the user since react handles the routing.
What is the correct approach to handle this?
I thought maybe this could work by using websockets...so that when NestJS handles the post request it can send a message to the user which message will contain the token and then the frontend can add it to a cookie and redirect the user to a protected page.
(1) Does the frontend really need to store a token to send to the backend on subsequent requests? What if the backend set a cookie at Step 7 in your diagram? Then the cookie would be sent to the backend on subsequent requests. The cookie would be scoped to the backend’s domain name and path. Keeping tokens away from the frontend has the advantage that you can keep them safe from being accessed via a Cross-Site Scripting attack on your frontend, if your backend’s cookie has the HttpOnly attribute set.
(2) If you still need to communicate info from the backend to the frontend in Step 7, then send an HTTP 301 response with the Location header set to your frontend’s URL with the info you want to communicate included in the query or hash portion of the URL. For example, after validating in Step 6, in Step 7 your backend’s HTTP 301 response could have the Location header set to https://my-frontend-domain.com?user=bob or set to https://my-frontend-domain.com#user=bob. With ?user=bob, user=bob would get sent over the network again when the browser requests https://my-frontend-domain.com/?user=bob, whereas with #user=bob it would not. Then the frontend’s JavaScript can read user=bob from the URL.
I am using NextAuth to sign in users using Facebook or Twitter. This works fine and I get the AccessToken along with basic user info. On the server I am using the socialId of the logged in user to map to the corresponding local user in the database. Azure Functions has a social login feature called EasyAuth but I am not sure if I need it since I am using NextAuth. I was thinking of two ways:
Send the loggedin user object with every request? This is probably not save?
Send the access token with every request and the server calls the corresponding social api to get the user info again?
What would be a good practice security vice when sending the information to the server?
The client should not be aware of who is currently logged-in. On the client, you just save the access token, and then you send it to the server on every request. The server will figure out who made the request based on the access token and return the appropriate response.
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.
Can anyone how look general flow of authentication in spring security, where frontend (so also login panel) is provieded by angularJS and node server ?
How should be these modules connected ?
I have been involved in three angularjs apps and in each of them we handled the whole user authentication/authorization in following way:
we defined a currentUser service which holds the information of current user of our application, things like user roles, email, name and ..., and this service have a very important method named isLoggedIn which based on this service values determine if user is logged in or not.
on the server side we have some sort of api which returns a token to a user after user have provided valid credentials, we post username/pass to the api and in response we receive a token and store it in a cookie or local sotrage. there are various ways of returning a token on would be using JWT(Json Web Token).
Tokens are sent in each request by help of $http interceptors, token may expire after 30 minutes which result in an unauthorized response from server.
for JWT refer to this link.
for client side authentication/authorization you can take a look at ng-book or this link.
I have two applications:
server ( REST API Server)
node js
Express
jsonwebtokens
express-jwt
mongoose
client (Portable Front-end)
bootstrap
Angular JS
local-storage
angular-facebook
angular-jwt
Lateron, the client app will be ported for android, iphone and other platforms using phonegap. For OAuth, I am using Facebook as the provider. Now, I just realized JSON Web Tokens are the way to go for this kind of set up. My question is an architectural one rather than syntactical one - how to manage a secret key when signing the facebook access token and user id with JWT in nodejs?
So this is how the flow works in my app:
Angular client has a Login button
User Clicks the button > Facebook Auth starts
Client receives user_id and FB Access Token
Client sends[POST json body] both user_id and Access Token to Node+Express Server at 'http://server.com/auth/login'
Node Server has applied express-jwt to all routes except /auth/login with a
var expressJwt = require('express-jwt');
var jwt = require('jsonwebtoken');
app.use(expressjwt({ secret: ''}).unless({path: ['/auth/login']}));
Node server receives data from req.body, fetches all profile details from facebook using the JavascriptSDK, and signs it using
var token=expressjwt.sign({profile}, );
Node Server stores(updates, if user_id exists) the new token in db and sends it as response to client
client stores the new token it received as json data in local-storage
client uses angular-jwt to fetch profile data from the new token and automatically attach the new token in Authorization header for all requests it sends to the server
Now, my questions are:
Do I really need to store the JWT tokens in database? I am certainly not comparing the tokens in request headers with database
Do I need to generate random secret keys for security, each time a person logs in? If yes then how would that fit in both client and server?
When and where do I need to check for token expiration? and How do I refresh it?
I am kind of lost about the design flow and mechanism.
Ad 1. You do not have to store the JWT in the database. User ID can be part of the payload, therefore there's no need for it.
Ad 2. It's a common practice for the server side app to use one secret key for generating all JWT.
Ad 3. Check if token has expired on each request to your API and disallow access if the token has expired, return 401 status code. Client app should prompt user for credentials and request new JWT. If you want to avoid users re-submitting the credentials you can issue a refresh token that later can be used to generate new JWT.
JWT refresh token flow
http://bitoftech.net/2014/07/16/enable-oauth-refresh-tokens-angularjs-app-using-asp-net-web-api-2-owin/