What authentication strategy should I use for my API?

I have an angular -js client application. And I have a server side nodejs API. The client side and the server application are located in different domains. Client API for receiving or publishing some data. Also, the client side needs to receive images from the server side and display them in a browser.

I use the module of the passport node for authentication. I don’t know which authentication strategy is better for me. I think there are two types of authentication strategies: token-based and cookie-based. And I think both types are useless in my case:

  • If I use token-based strategies, then I have to send an authentication header with a token in every API request. I can send headers in AJAX requests, but if I want to show an image that is on the server side, I have a problem. Since the browser does not send headers in the <img> .

  • If I use cookies, then I have no problems with images. But I have problems with AJAX requests. Because the session cookie is stored in the server side application domain. And if I send AJAX requests from the client domain, I have to send cookies with every request. I am using XmlHttpRequest for AJAX and I have to use the withCredentials option to send cookies. But in crossdomain requests, browsers send an OPTION request before each AJAX request. And browsers will not send cookies requesting OPTION. This is a problem for me, because the server-side API cannot make the correct answer to the OPTION request if it is not allowed.

What is a decision?

+4
authentication api authorization
Dec 04 '15 at 21:47
source share
1 answer

It is important to understand the difference between web applications and web services. The web application supports markup, JavaScript, CSS, and image files and often uses cookie-based authentication (but can use any other implicit authentication mechanism). Any request that the browser makes is automatically authenticated.

Web services, on the other hand, often use bearer token authentication. When a client communicates with the API in a browser, a thick client, or on a mobile device, it sends a token in the Authorization header of the HTTP request. The header must be explicitly bound to the request in JavaScript or native code that executes the HTTP request.

One-page applications (SPAs) do not have a web application, and markup, JavaScript, CSS, and images are served in a browser without authentication. Only requests to web services are authenticated, usually using a JWT token.

In your case, if you want only authorized users to upload images and other files, you should consider creating a web application. Use a security protocol such as OpenID Connect to authenticate your users. Select an authorization server that supports both OpenID Connect for your web application and OAuth2 for your web service.

+5
Dec 05 '15 at 23:54 on
source share
— -



All Articles