Skip to content
This repository has been archived by the owner on May 12, 2024. It is now read-only.

This project provides a basic example of an authentication provider using JSON Web Tokens (JWT), Spring Boot, and Spring Security. It includes user registration, authentication, and refresh token functionality, with endpoints for secure access control.

License

Notifications You must be signed in to change notification settings

stdNullPtr/SpringBoot-Authentication-Service-JWT

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Spring Boot Authentication Service API (JWT)

Introduction

This project is a simple example of how you would implement an authentication provider using JSON WebTokens, Spring Boot and Spring Security.

The database used is MySQL.

I highly encourage you to use Docker to run the project

Requirements

Running the application locally

1. MySQL setup

First make sure you set up a MySQL local instance. Then, configure your chosen username and password in application.yml:

spring:
  datasource:
    url: "jdbc:mysql://${MYSQL_HOST:localhost}:3306/testdb?useSSL=false&createDatabaseIfNotExist=true&allowPublicKeyRetrieval=true"
    username: "root"
    password: ${MYSQL_PASSWORD:qaz88x}

Upon startup, the application will execute the SQL queries inside /resources/import.sql which will populate the user permissions in the database:

INSERT INTO roles(name) VALUES ('ROLE_USER');
INSERT INTO roles(name) VALUES ('ROLE_MODERATOR');
INSERT INTO roles(name) VALUES ('ROLE_ADMIN');

2. Starting the Spring Boot app

There are several ways to run a Spring Boot application on your local machine. One way is to execute the main method in the com.anto.authservice.Application class from your IDE.

Alternatively you can use the Spring Boot Maven plugin like so:

mvn spring-boot:run

Spring application yaml

spring:
  datasource:
    # MySQL connection details
    url: "jdbc:mysql://${MYSQL_HOST:localhost}:3306/testdb?useSSL=false&createDatabaseIfNotExist=true&allowPublicKeyRetrieval=true"
    username: "root"
    password: ${MYSQL_PASSWORD:qaz88x}
  jpa:
    properties:
      hibernate:
        dialect: "org.hibernate.dialect.MySQLDialect"
    hibernate:
      # Print sql requests, useful during development
      show-sql: true
      # Clear DB after each service start for easier development
      ddl-auto: "create"
app:
  jwt:
    # JWT expiration
    expirationMs: "3600000"
    # Refresh token expiration
    refreshExpirationMs: "86400000"
    # Secret for signing the JWT
    secret: "ufGJqqC94OBE8qJFigbB55Pf2mLCXUDomQKP87qaGl/Nj9b/aWOlvtJ+bBtggH9XnBHR4M7SBtGOq++XfXw0iw=="

Using the API

Endpoints

POST localhost:8080/api/auth/signup

Used for initial registration in the database. Example payload:

{
  "username": "mod",
  "email": "mod@anto.com",
  "password": "123456",
  "role": [
    "mod",
    "user"
  ]
}

Example response:

{
  "message": "User registered successfully!"
}

Database changes:

HeidiSQL-after-signup.png

This will create a new user with the specified username and password in the database

POST localhost:8080/api/auth/signin

Used to authenticate through the API, receiving a JWT and a refresh token in return.

Example payload (following previous example):

{
  "username": "mod",
  "password": "123456"
}

Example response:

{
  "type": "Bearer",
  "accessToken": "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJtb2QiLCJpYXQiOjE2OTU4MjY0NTEsImV4cCI6MTY5NTkxMjg1MX0.eFe8VtXxEXp7lDlMM9evXG-dx9oSarzJZto5I9d3D-t53mTsJ7iU3q6_vvi6dJ_BUnWzGm7YLaC6Hm1iQ3ZKJA",
  "refreshToken": "d85c5c12-363b-4a9c-8ac8-98823716ec1e",
  "id": 1,
  "username": "mod",
  "email": "mod@anto.com",
  "roles": [
    "ROLE_USER",
    "ROLE_MODERATOR"
  ]
}

The token provided in the token field can now be used alongside future API calls to other endpoints.

POST localhost:8080/api/auth/refreshtoken

Used to request a new access token.

The new token is stored in the database, and removed once you sign in again (recreated)

Example payload (The refresh token received during sign in)

{
  "refreshToken": "d85c5c12-363b-4a9c-8ac8-98823716ec1e"
}

Example response:

{
  "type": "Bearer",
  "accessToken": "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJtb2QiLCJpYXQiOjE2OTYxODMyNzEsImV4cCI6MTY5NjE4Njg3MX0.6HXkZzkDNoVi7ivl7wR2ok6PUFDKWXNeyZyCAkksawAHSLlVytSAnYLOlSzWO-irbMapWNDu3X-NJWTqk3-ixg",
  "refreshToken": "d85c5c12-363b-4a9c-8ac8-98823716ec1e"
}

Multiple endpoints: localhost:8080/api/test/*

Endpoints purely for testing purposes that the resource is protected and not accessible without a valid JWT

GET localhost:8080/api/test/mod

This endpoint is only accessible if the JWT provided has rights to access mod role protected endpoints.

Required header: Authorization: Bearer <token>

How this looks like in Postman: Request-mods-only.png

Docker

Install Docker

The docker configs are in Dockerfile and compose

Run docker compose up to start a MySQL instance and the service with a single command!

Copyright

License: BSD-4-Clause

Author

Antonio - LinkedIn

Links

Special thanks to Bezkoder

About

This project provides a basic example of an authentication provider using JSON Web Tokens (JWT), Spring Boot, and Spring Security. It includes user registration, authentication, and refresh token functionality, with endpoints for secure access control.

Topics

Resources

License

Stars

Watchers

Forks