Expose a REST API to different kinds of users with Api-Platform [Part 4/4]

Benoit POLASZEK
2 min readJun 3, 2019

--

In the previous part, we learnt to expose an Api to different users with restrictions on content, as well as properties. Now, how can we integrate this Api in an Ajax context, without needing to log the user in again?

Expose the JWT in Twig templates

The point is to expose a JWT of the current user (which can be a Customer, an Employee, or null) in Twig templates, along with the Api Entrypoint to make our front-end agnostic about URIs.

Now we can use these variables globally inside data-attributes:

{# templates/base.html.twig #}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{% block title %}Welcome!{% endblock %}</title>
{% block stylesheets %}{% endblock %}
</head>
<body data-jwt="{{ jwt | e('html_attr') }}" data-entrypoint="{{ entrypoint | e('html_attr') }}">
{% block body %}{% endblock %}
{% block javascripts %}{% endblock %}
</body>
</html>

This implementation has the drawback of generating a JWT on each request. This can be optimized by adding some cache, but this won’t be covered by this tutorial.

Install Webpack Encore

Assuming you have Yarn installed globally, run the following command:

composer req encore && yarn install && yarn add axios regenerator-runtime && yarn build

It will create an assets/js/app.js file and compile it to public/build/app.js.
Require it in your Twig base file:

{# templates/base.html.twig #}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{% block title %}Welcome!{% endblock %}</title>
{% block stylesheets %}{% endblock %}
</head>
<body data-jwt="{{ jwt | e('html_attr') }}" data-entrypoint="{{ entrypoint | e('html_attr') }}">
{% block body %}{% endblock %}
{% block javascripts %}
{{ encore_entry_script_tags('
app') }}
{% endblock %}

</body>
</html>

Open /shop or /admin, you should see this in your browser’s console:

Hello Webpack Encore! Edit me in assets/js/app.js

Create the authenticated client

Edit assets/js/app.js:

Run the build command again (or stick to yarn watch):

yarn build

Open /admin and /shop in 2 tabs of your favorite browser and look at the console; you should see:

  • All orders with all information in the /admin tab
  • Only the current customer’s order without the fraudulent information in the /shop tab.

Conclusion

I hope you enjoyed this tutorial as well as I enjoyed writing it.
As possible next steps, you could add some cache upon the JWT generation to avoid doing it at each request. You could also handle JWT refreshment in the case of your user interacts with the current page for a long moment.

Previous

--

--