Angularjs + RESTful API exposed registration - angularjs

We started developing a RESTful app for registrations, signing in and posting some simple stuff. We're using AngularJS for the frontend which handles users registering, logging in, signing out etc.
The backend accepts the following paths:
POST /register (params: email, password)
POST /login (params: email, password)
POST /logout
After the user logs in, a JSON token is generated. This token is then used for each and every subsequent request - like GET /items or DELETE /items/5. Without that token every request is denied with a 401. This part works perfectly because I can use the API in a browser through AngularJS, in an iPhone/Android App and even for 3rd parties.
The only publicly exposed paths are /register and /login. While doing a POST on /login from the outside is natural and makes sense I'm worried that anyone can do a POST /register from the outside and just flood the server with registrations.
I found somebody doing a similar app, I just launched POSTMAN and did a POST query on /signup which worked.
http://www.mircozeiss.com/github-like-signup-form-with-angularjs-and-bootstrap-v3/
I can't help but think that this is not a best practice scenario when it comes to registering users. Registering users with Google+ or Facebook is not an optimal solution. Any ideas on how to prevent bogus/flood registrations from outside? Is there a way to secure this part of the API (/register)? Should I just rate limit the number of requests?

If it's free for all app, better X-Rate-Limit the register api endpoint like Github and all, otherwise just process register requests if it has a auth token with admin privileges (allowed to create credentials for other app-user).

The backend accepts the following paths:
POST /register (params: email, password)
POST /login (params: email,
password)
POST /logout
First of all, this is not a REST API, because it violates the stateless constraint of REST. Use encrypted connection and send the username and password in the HTTP basic auth header with every request. That is stateless.
Any ideas on how to prevent bogus/flood registrations from outside? Is
there a way to secure this part of the API (/register)? Should I just
rate limit the number of requests?
This does not depend on REST. You can do just the same with every web application which allows registration. Typical solutions to use a captcha or send a verification link in email. You can limit the rate, but that is not an effective solution.

Related

how to integrate regular username/password login with 3rd party social login for a Spring Boot + Angular single page web app?

I have a Angular + Spring boot single page web app. The server also acts as an Auth Server which issues tokens for the angular app to use to make Restful API calls.
My old login flow uses a grant_type=password POST call to the /oauth/token endpoint to get a Bearer token. And all further API calls on behalf of the user will include the Bearer token as the "Authorization" http header.
Now I need to integrate social login (facebook, twitter, etc.), which means I don't have username/password to generate tokens so I'm not sure how to make it work.
I have been using the following two tutorials as my template:
Spring Security and Angular JS
Spring Boot and OAuth
In the first tutorial's oauth-vanilla example, the username passwork login flow brings up the authorization page. But I'd like to have the traditional username/password form login experience (log user in directly instead of showing the Authorization page).
In the second tutorial, after facebook login, I'd like to use the facebook id to look up my internal user database and create a new user if not exist and logs him in as the user. And use the internal db user's identity and authorities to authorize future API calls to my API server.
I have a stripped down sample at at
https://github.com/dingquan/spring-angular-oauth
I can make POST calls to /oauth/token endpoint and use the returned token to make further api calls to my protected /api/blogs endpoint. But I haven't figure out how to make the following things work:
Username/password login that will create a session cookie so I don't need to send the Authorization bearer token for future API calls to the resource endpoint
After facebook login (the facebook login link is under the username/password login form), calls to my endpoint still fails with 401 error (I have a "test" button that makes a get call to /api/blogs, you can click on it to see the behavior). So what am I missing to make the API call succeed?
=== UPDATE ===
Just to clarify. Here are the goals I'm trying to achieve:
multiple ways of authentication (traditional username/password, third party oauth login such as facebook, possibly cellphone number + SMS code in the future)
we do need our own user model backed by DB to store other user attributes, pure social login is not enough
social login needs to be implicit. Meaning user should not be required to create a user account in our system manually once they login through a 3rd party (facebook, etc.). We're not just grabbing users' social profile data to pre-populate the registration form. We want to create new DB users automatically behind the scene if no existing db user is associated with the given external social account. i.e. if user is logged in through facebook, they don't need to enter username/password. Authentication through facebook will automatically log the user into our system as well and user should be able to access restricted resources after facebook login.
There's some confusion that I might be asking people to put their facebook username/password in a login form hosted by my app and I'll login facebook on behalf of the user. That's not what I was asking for.
You don't need such a complicated configuration. Add #EnableOAuth2Sso to your MainConfiguration and set appropriate application properties.
Here is what I have done in order to use Facebook as a authorization server.
a) Remove clientId and authServer from UserServiceImpl. Otherwise you'll be forced to configure an authorization server that is not needed.
b) Remove AuthorizationServerConfiguration completely.
c) Add #EnableWebSecurity and #EnableOAuth2Sso to your MainConfiguration.
d) Change MainConfiguration::configure to
http
.logout().logoutSuccessUrl("/").permitAll().and()
.authorizeRequests().antMatchers("/", "/login", "/home.html").permitAll()
.anyRequest().authenticated()
.and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
e) Delete everything else except nested class AuthenticationSecurity from MainConfiguration.
f) Change ResourceServerConfiguration::configure(HttpSecurity) to
http.antMatcher("/api/**").authorizeRequests().anyRequest().authenticated();
f) Remove attribute tokenStore and method ResourceServerConfiguration::configure(ResourceServerSecurityConfigurer) from ResourceServerConfiguration.
g) Remove configuration block security and facebook from application.yml. Instead add this
security:
oauth2:
client:
client-id: <CLIENT_ID>
token-name: oauth_token
authentication-scheme: query
client-authentication-scheme: form
access-token-uri: https://graph.facebook.com/oauth/access_token
user-authorization-uri: https://www.facebook.com/dialog/oauth
resource:
user-info-uri: https://graph.facebook.com/me
client-id: <CLIENT_ID>
client-secret: <CLIENT_SECRET>
token-type: code
h) In index.html change login to login.
i) Replace the content of hello.js with this one.
But I'd like to have the traditional username/password form login experience (log user in directly instead of showing the Authorization page).
I would never use a site that requires my credentials without redirecting me to the origin! I don't know you and you are under suspicion being a phishing site.
You should really reconsider your decision.
Btw, I created a pull request with these changes.

Separate User / Admin API?

I'm building a multi tenant app using Angular and Node.js, is it wise to have the same API for both Front End users (Public) and Admin Area users (Tenants)?
The Admin Area will require authentication for viewing and modifying sensitive data but I don't see why the rest of the API can't be left open for the front end which is only querying data?
Is this a good idea? Will it cause problems further down the line?
I'm looking to go for the following application structure:
Front end: tenant-name.domain.com (Open to public)
Admin area: domain.com/admin (with login and token auth)
API: api.domain.com
Would it be a good idea to have the client's front end authenticate with the API?
I would suggest that the admin area API calls require an auth token to be passed on all API calls. You can inject the token into the headers with http request interceptors in Angular. A user who does not already have an auth token should have to log in to get one. The injected auth token should be all the security you need.
I'll suggest you to create a token when an anonymous user requests your API. Reason for that is that you can always identify who requested what.

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).

Restricting API Calls to a Certain Domain

My app uses JS Facebook API to use Facebook as a login/pass. Here what happens when you try to login.
User click on the Facebook Login Button
Facebook Authenticates
If Success. I grab the Facebook ID and Name of the user
Calls on my REST API on my APP to check and see if the that FBID is registered in my system.
If Registered, I write the session to verify that the user is authenticated.
This is great since I don't have to store usernames and password. But I am worried that someone will just use a REST API debugger like POSTMAN in chrome and just send a Facebook ID and the name of the user and they will be authenticated.
My question is what is the best way to secure my end that will prevent apps like POSTMAN to just input the fields needed to authenticate? Am I missing something? Can anyone recommend a strategy for this?
Or is using CSRF token the only way to combat this? I am using FuelPHP as a backend and doing a single page app using AngularJS with NgRoutes. But every time I enabled the CSRF on fuel, the token passed does not match what it was in the back-end.
I am under the impression that this is due to that the javascript token function is in the main page, where the ng-view. I know this might have something to do with the ngRoutes.
http://fuelphp.com/docs/classes/security.html
Use Fuel's Auth package. It has Opauth integration which does all the above, and for an entire list of social media platforms, not only facebook.
Always try not to reinvent the wheel, assume someone else has had the same challenge, solved at, and shared the solution with the community.

Handling Page Reloads With OAuth Access Code In URI

I've run into an issue when using OAuth 2 authorization codes in an web app's URL, such as is returned by Google's OAuth method (https://developers.google.com/accounts/docs/OAuth2Login).
I've been using the google redirect method; where you redirect the user to a Google URL, passing in client_id and redirect_uri. The user authenticates and the authorization code is passed to the redirect_uri as a
The issue is that the access code stays in the page URL, so if the user bookmarks or posts the URL, they are sending an invalid Authorization Code.
Eg:
http://myapp.com/?code=kACASDSDdAS81J5B8M_owCyUNgV46XdZaqBBMh4T8OJFEKPRrgN7gtiFOcMW5Fv3gk
What is the best way to handle this case? Ideally, I would like to send the authorization code in a POST body as it isn't visible to the player?
I've spent a bit of time looking at Google App Engine (the platform I'm using) to redirect the user, but can't seem to send a POST body in a redirect.
After the user is directed to your app with the authorization code in the URL query parameter, you should:
1) Exchange the authorization code for an access token by making a HTTPs POST to Google's OAuth 2.0 token endpoint and save that access token as appropriate (datastore, memcache, etc)
2) Redirect the user to a URL without the ?code. You can't send a POST body in a redirect (HTTP doesn't allow it), but that shouldn't be necessary if you store the access token server-side for making API calls.
If you must make the token accessible client-side, you can:
a) Send it back as a cookie along with the redirect (which exposes it to the client, though you could encrypt it) OR
b) Generate a HTML form, with JavaScript for auto-submitting it instead of doing the redirect. Kind of ugly, but common.

Resources