JWT with Frontity

Do Frontity have JWT Feature, so we can build out Login forms and protected routes?

2 Likes

Not yet.

Which plugin are you planning to use? https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/ or https://github.com/WP-API/jwt-auth?

Maybe we could add a method in source to add an Authorization: Bearer header to all requests, once the user has logged in.

2 Likes

The first one,… but the developer is not very often updating the Plugin and also wp-plugin and git repo are not on the same version. Maybe a good idea would be for the Frontity Team to maybe fork this plugin and build out an own version of it and maintain it.

My ideas for Frontity - Currently Frontity is presented as Framework to build themes in React for WordPress, this is nice but now I will explain why I don’t like the way Frontity is currently built

In first place what Developers want to achieve with the Apps they build? Help others and make Money with the App. So to be able to make Money your App needs to have Authentication where Users can LogIn and use the App.

I think Frontity should take this path, To build an official Frontity Plugin for WodPress that is maintained by the Developer of Frontity and guarantees compatibility.
What this plugin should have?

  1. JWT-Authentication and build out functions to use it easy in Frontity Framework
  2. Maybe make Plugin Actions work on Frontend by creating some connection between Plugin > Frontity Plugin > React Frontend
  3. A way to interact with the MySQL database so our Node logic can create data for the db.

Their are a few more things I had in my mind but I forgot it now, in my opinion, the most important thing would be to have a Plugin by Frontity where Developers can rely on because currently Frontity is built less for Developers more for beginners and. Frontity should become more solution for creating apps where WordPress is used as the backend, and not see Frontity only as Theme framework, that would be cool. Thanks

Thanks for your comments. I’ve added JWT-Authentication to our roadmap and if more people start requesting it, we’ll push it up. Please bear in mind that right now we still working on some other core features and we have a lot of items in our roadmap so it may take a while.

But Frontity is open source, so if you cannot wait and want to work on an integration with the JWT Authentication for WP REST API plugin and create a Frontity package for that we will be more than glad to give you instructions on how to proceed and make the necessary changes to wp-source in our code. I’ve taken a look and it doesn’t seem difficult.

If you want to collaborate let me know and I’ll explain you the next steps.

4 Likes

+1 for jwt integration (bearer auth)

I am using JWT Authentication for WP REST API

2 Likes

+1

:pleading_face:

1 Like

+1

Hey @joel @gab.zambrano @afatoga thanks for the upvotes!

It would be really useful for us to understand what are you trying to build. Could you share with us your use case? At what point in the development are you right now?

Thanks in advance :blush:

1 Like

@Pablo, I’m building a web app that allows drivers to request transport jobs. I need them to be able to log in and select a job and request it.

I have a pure react set up with log in with JWT and I’d love to have it available with Frontity.

1 Like

@Pablo I’m building an app for requesting travel offers to travel agency(es).

Ideally, people can login (maybe Auth0 or other type of social login) and they’ll be able to manage their account (personal info, personal preferences, favorite agencies, CRUD of requests, etc)

The project just started. I have more experience developing Themes using Roots Sage. but I wanted to try Wordpress headless, using react more than PHP. I still need to learn a lot of notions of react and js ES6

1 Like

Hi
I could verify that this plugin can be useful for your customers to authenticate to your React App, using JWT Authentication

1 Like

Could you explain to me how to get the server token?
Thanks !

Look in the USAGE section of their documentation: https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/

It looks like you have to use the '/jwt-auth/v1/token' with a POST request that contains the username and password.

You can use fetch to do the request. Import it from frontity.

I think I would fetch the token into beforeSSR, right?

const before = async ({ libraries, actions }) => {
  libraries.source.handlers.push(tokenHandler);
  await actions.source.fetch('/fetch-token/')
};
...
actions: {
  theme: {
    beforeSSR: before,
...

that configuration is correct?

Should I be aware of problems with CORS?

Yes, beforeSSR seems a good place to do so.

I don’t know if that plugin takes care of CORS so take a look at it and at the configuration of your WordPress.

Are there any special considerations to take into account if the handler is in beforeSSR?
This is my handler:

import { fetch } from "frontity";

export const tokenHandler = {
  pattern: '/fetch-token/',
  func: async ({ state }) => {  
    const response = await fetch ( urlToFetch, {
      method: 'POST',
      headers: new Headers({
        'Content-Type': 'application/json'
      }),
      body: JSON.stringify({
        username: xxxxxxxxxxxxx,
        password: xxxxxxxxxxxxx
      })
    }
  );

  const data = await response.json();

  Object.assign(state.theme.token, { data });
  }
  }

I’m getting an error:

EventSource's response has a MIME type ("application/json") that is not "text/event-stream". Aborting the connection.

I’m sorry, I told you that beforeSSR was right but this has to be client-side, so this would need to go on afterCSR. CSR stands for client-side rendering.

That seems like a problem not related with Frontity.


By the way, you don’t have to use a handler if you don’t want to. Handlers are only to match a URL with some data in the REST API and the URL /fetch-token/ doesn’t exist. You can just create an action that does the fetch and modifies the state by itself.

I’m not able to find an example on how to do this in the documentation. I need to authenticate in order to see private posts. I’m trying to do a knowledge base with public and private articles and would appreciate any help in a good way to achieve that.

2 Likes

Hi @victorcarvalhosp, below is a function to get the token from the server.
With that token you can do restricted operations, such as viewing private posts.

I hope you find it useful :sunglasses:

fetchToken = () => {
    this.setState({
      isLoading: true,
    })
    fetch(Constants.apiUrl + 'jwt-auth/v1/token', {
      method: 'post',
      headers: new Headers({
        'Content-Type': 'application/json'
      }), 
      body: JSON.stringify({
        username: this.state.username,
        password: this.state.password
      })
    })
    .then(res => res.json())
    .then(data => this.setState({
        token: data.token,
        isLoading: false,
    }))
    .then( console.log('Done!') )
    
    .catch(error => console.log(error))
  }
2 Likes

Can we get the JWT token beforeSSR?