Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authentication with JWT and JSONAPI

I am implementing REST API using the following technologies/approaches:

  • JSONAPI

  • JWT token

I want to implement authentication endpoint, it should receive username and password in POST request in JSONAPI format and return JWT token in JSONAPI format. But I see there are some contradictions that does not allow me to be 100% RESTful:

Let's name endpoint /tokens, because it actually creates tokens. Response would be also resource of type tokens, e.g:

{
  "data": {
    "type": "tokens",
    "attributes": {
      "value": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEifQ.ivJ5P23wqVo3w31flg3aOu7er--Ijght_RrBf_MuqsU",
    }
  }
}

But how about request? username and password are properties of user, but they should be sent to /tokens endpoint. If I send users resource to /tokens endpoint it does not make much sense.

Is there a way around for this, to follow JSONAPI and keep API meaningful?

like image 849
Sergey Potapov Avatar asked Jan 15 '16 09:01

Sergey Potapov


People also ask

Can JWT be used for authentication?

To authenticate a user, a client application must send a JSON Web Token (JWT) in the authorization header of the HTTP request to your backend API. API Gateway validates the token on behalf of your API, so you don't have to add any code in your API to process the authentication.

What is difference between JWT and SAML?

SAML2: Defines structure of token (SAML Assertion) and underlying protocol (for Web App SSO). JWT: JWT defines only the token structure. OAuth2 and OpenID Connect define the protocol. SAML2: SAML2 supports Bearer Tokens, Holder of Key, and Sender Vouches.

Can I use Passport with JWT?

A Passport strategy for authenticating with a JSON Web Token. This module lets you authenticate endpoints using a JSON web token. It is intended to be used to secure RESTful endpoints without sessions.

Can JWT be used as API key?

Creating JWTs on your server Alternatively, you can fetch a JWT when Iterable's SDK calls the auth token requested callback (for which you provide the code). For a mobile app to use a JWT-enabled API key, it must provide an implementation of the auth token requested callback, which provides the JWT to the SDK.


2 Answers

If I send users resource to /tokens endpoint it does not make much sense.

Why not? REST does not impose that you only send users to a user resource. Sure, when you CRUD operations on a user resource you'll do this via the user resource endpoint.

But to generate a token, it's totally reasonable to send a user resource to the token endpoint.

like image 180
MvdD Avatar answered Oct 14 '22 16:10

MvdD


You could also supply the user credentials via an HTTP Authorization header, or as part of the toplevel meta property of the JSON payload.

like image 35
beauby Avatar answered Oct 14 '22 16:10

beauby