My hive game, Devlog #3 - Creating a Log In [EN/ES]

in OCD4 years ago (edited)

[English]

Hello hive, this time I want to tell you about the login I added to be able to use it in my game.

image.png

We are custom to seeing logins in the vast majority of applications we use every day, without realizing all the work behind this valuable component, which has the purpose that only those who have the correct credentials (username and password) are authorized to login to the application.

image.png
https://hive.blog/ - login

How a login works in broad strokes


Basically the flow of user authorization and authentication through login happens in the following sequence.

  1. The user enters their username and password and sends it from the login form to the application server.

  2. The server receives the request, if the user and passwords are valid then it will generate a session, a token or some other authentication method.

  3. The server returns a message or token to the client indicating whether or not the operation was successful, if not successful, it will indicate the reasons and what should be done in such a case.

  4. Now each request made by the client to the server would be checked to verify that it is secure, and therefore, the server would authorize access to the requested resource.

image.png

Example token base authentication


Authentication of applications is a very important issue, because it is the first layer of security that your application will have and the way you build it will determine how secure it will be.

I also want to mention that I am actually making a website that will contain the game I am making, which means the login is not only for a single game, but all web site and the futures games.

Choosing an Authentication type for REST API


There are various authentication methods out there such as session based authentication, Oauth 2.0, OpenID Connect etc. I had to choose the most suitable one for my REST API, in my case I chose a token-based authentication, because it is easier to implement in my application, although it is not less secure in its execution.

Also known bearer authentication can be understood as giving the bearer access to this token. The token or key is a chain of encrypted characters that allow access to a certain resource or URL. The client should send this token in the authorization header every time he makes a request to protected resources in the server, which will validate the access.

Some of the advantages of token-based authentication are


  • Stateless, scalable, and decoupled.

The server does not store any type of token data, however, in every request between the client and the server, communication is never lost.

  • Performance

Not storing any customer authentication data reduces the load on the server considerably.

  • Multi-platform

A well configured REST API with token-based authentication can serve any type of application, be it mobile, web or desktop.

All this was pure theory so far. Was it very confusing? 😅 The truth is that it is a very complex but interesting topic, there is a lot of information on the internet, if you are interested do not stop investigating about it or comment your doubts and we can discuss it.

My implementation


In my experience, there is no one way to implement something, it all depends on what the project needs.

In my case I my Backend or API that resolves requests from my website. I use JWT to generate and decode the client tokens and mongodb to store the registered users.

image.png

On my website or Frontend I use Angular Framework, there I have some components as interceptors to catch http requests and add them the token header and JWT on the client side, to decode the token received by the server and know what information to show to each user who accessed the site.

image.png

The result


I Forget say that even before you can do a login you need to do a user registration on the website, for that we need a sign up page, once the user with their encrypted password are registered in the database already the login will be the next step.

login.gif

Conclusion


It was necessary to do the login module in the application before even making the game, in order to be able to store data from the game itself, even if it was in test mode in a database, it would hepl a lot of the game development.

There were many challenges and problems I had to face and I did not mention in this post, but in the end it could be solved without major problem.

All this had to be done just like that in order to request a login at the start of the game. 😁

image.png

Thanks for stopping by.


263-2635299_art-art-deco-divider-png-clipart.png


[Español]


Hola hive, esta vez quiero contarles acerca del inicio de sesión que añadí para poder utilizarlo en mi juego.

image.png

Estamos acostumbrados a ver inicios de sesión en la gran mayoría de aplicaciones que usamos cada día, sin percatarnos de todo el trabajo que hay detrás de este valioso componente, el cual tiene como propósito que solo quien tiene las credenciales (usuario y contraseña) correctas estén autorizados a entrar a la aplicación en cuestión.

image.png
https://hive.blog/ - login

Como funciona un inicio de sesión a grandes rasgos.


Básicamente el flujo del autorización y autenticación del usuario a través del inicio de sesión sucede en la siguiente secuencia.

  1. El usuario escribe su usuario y contraseña y lo envía desde el formulario del inicio de sesión al servidor de la aplicación.

  2. El servidor recibe la solicitud, si el usuario y contraseñas son válidos entonces generará una sesión, un token o algún otro método de autenticación.

  3. El servidor devuelve un mensaje o un token al cliente indicando si fue o no exitosa la operación, de no ser exitosa, indicara los motivos y que debe hacerse en tal caso.

  4. A partir de aquí cada petición que haga el cliente al servidor se comprobaría para verificar que es segura, y, por tanto, el servidor autorizaría el acceso al recurso solicitado.

image.png

Ejemplo de autenticación por token


La autenticación de las aplicaciones es una cuestión muy importante, porque es la primer capa de seguridad que tendrá tu aplicación y la manera que la construyes determinara que tan segura será.

Quiero mencionar tambien que en realidad estoy haciendo un sitio web que contendrá el juego que estoy haciendo, y posteriormente otros juegos, lo que significa que el inicio de sesión no es únicamente para este juego.

Escogiendo un tipo de Autenticación para REST API


Hay varios métodos de autenticación ahi afuera como lo son; Autenticación por secciones Oauth 2.0, OpenID Connect etc. Tenía que elegir el más adecuado para un mi API REST, en mi caso elegí una autenticación basada en tokens, porque es mas fácil de implementar en mi aplicación, aunque no por eso es menos segura en su ejecución.

También conocida autenticación de portador puede entenderse como dar acceso al portador de este token. El token o llave es una cadena de carácteres encriptados que permiten el acceso a un determinado recurso o URL. El cliente debe enviar este token en el encabezado de autorización cada vez que realicé solicitudes a recursos protegidos al servidor, el cual validará el acceso.

Algunas ventajas de la autenticación por token son:


  • Sin estado, escalable y desacoplado.

El servidor no guarda ningún tipo de dato del token, sin en cambio en cada petición entre el cliente y el servidor nunca se pierde la comunicación.

  • El rendimiento

Al no almacenar ningun dato de autenicación del cliente disminuye la carga en el sevidor considerablemente.

  • Multiplataforma

Una API REST bien configurada con la autenticación basada en tokens puede servir a cualquier tipo aplicación, ya sea móviles, web o escritorio.

Bien todo esto fue pura teoría hasta aquí. Fue muy confuso? 😅 La verdad es que es un tema muy complejo pero interesante, hay mucha información en internet, si les interesa no dejen de investigar al respecto o comentar sus dudas y podemos discutirlo.

Mi implementación


En mi experiencia, no hay una única manera de implementar algo, todo depende de lo que el proyecto necesite.

En mi caso en mi Backend o API resuelve las peticiones de mi sitio web. Utilizo JWT para generar y decodificar los tokens del cliente y mongodb para almacenar a los usuarios que se vallan registrando al sitio.

image.png

En mi sitio web o Frontend uso Angular Framework, ahi tengo algunos componentes como interceptores para atrapar las peticiones http y agregarles a la cabecera el token y JWT del lado del cliente, para decodificar el token recibido por el servidor y saber que información mostrar a cada usuario que accedió al sitio.

image.png

El resultado


Olvide mencionar que incluso antes de de poder hacer un inicio de sesión se necesita hacer un registro de usuario en el sitio web, para eso necesitamos una pagina de registro, una vez que el usuario con su contraseña encriptada estén registrados en la base de datos ya se podrá hacer el inicio de sesión correctamente.

login.gif

Conclusión


Era necesario hacer el módulo de inicio de sesión en la aplicación antes de hacer incluso el juego, para poder ir almacenando datos del juego mismo, aunque fuese en modo de prueba en una base de datos, eso ayudaría mucho al desarrollo del juego.

Hubo muchos retos y problemas que tuve que enfrentar que no menciono en esta publicación, pero al final se pudieron resolver sin mayor problema.

Todo esto tuvo que hacerse así solo para poder pedir un inicio de sesión al inicio del juego. 😁

image.png

Gracias por visitar mi blog.


Glossary


References

https://blog.restcase.com/4-most-used-rest-api-authentication-methods/
https://www.google.com/amp/s/openwebinars.net/amp/blog/que-es-json-web-token-y-como-funciona/

Older post

Added full screen mode and other features

All graphics resources of the game was taken from


https://opengameart.org/

Tools, Libraries, Frameworks


https://www.phaser.io/phaser3
https://socket.io/
https://nodejs.org/en/
https://angular.io/
https://tailwindcss.com/
https://www.mongodb.com/

I appreciate the constant support from users 🙏


@ritch
@gustavmahler
@yangyanje
@hivemexico

intro sz games.gif

Sort:  

Congratulations @shimozurdogames! You have completed the following achievement on the Hive blockchain and have been rewarded with new badge(s) :

You published more than 10 posts. Your next target is to reach 20 posts.

You can view your badges on your board And compare to others on the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Support the HiveBuzz project. Vote for our proposal!