简体   繁体   中英

Node.js RESTFUL service self built auth

I'm creating a REST service on my Node.js app over HTTPS. I don't want to allow anyone to use these REST services unless they're an authenticated user so I need a method of authentication when making request to these services.

I've read online and it seems OAuth2 with passport is a good solution... However I came up with what I think is a simpler solution that does not require persistence of the tokens, and I was wondering, are there are any large vulnerabilities with my solution?

My solution is to keep a secret stored on the server. When a user logs in and I authenticate them (or signs up), I hash the users username, add a timestamp to it, and encode it with my secret to create an "access token". Due to the timestamp this token will always expire after an hour (or a day or however long....).

Once the user has this access token, they just need to pass this token inside the request query, along with their username, and they will be able to use the server's REST APIs. Given that when I decode the token with my server secret, it equals the username.

This method also does not require me to persist any tokens information (refresh token, expiration time etc..). I also do not need additional modules such as passport and oauth modules to implement my solution, it seems very compact.

My question is (I am VERY new to security), is this solution good enough for a server meant to provide services to Mobile apps (still reachable via REST clients) assuming that the server secret will never be uncovered?

Welcome to SO!

The default answer to any question about security: don't try to do it yourself :)

It sounds like you're re-inventing the signed access token scheme, which is becoming codified as JSON Web Tokens (JWTs). I highly suggest that you use this scheme instead.

Don't pass the data in GET params, as it's likely to get cached or logged somewhere (opening yourself up to man-in-the-middle attacks). You should store the token in HttpOnly; Secure HttpOnly; Secure cookies to prevent the cookie from being exposed to non-secure channels.

I've written some in-depth articles on JWTs and how to use them in web browsers:

Create and Verify JWTs With Node.js

Build Secure User Interfaces Using JSON Web Tokens (JWTs)

Disclaimer: I work at Stormpath . We are a user authentication service and we can offload all these concerns for you. It sounds like you're using Node, for which we have great libraries that can get you running with all your user needs in minutes :)

I'm also the author of nJwt , a Node.js library that makes it really easy to use JWTs the right way.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM