Java demos for my blog posts

API Auth example with Spring Boot

Installation instructions

The application wants to connect to a MySQL Database running on the localhost, with username root and no password.

In src/main/resources/application.properties changes can be made to the default configuration.

To initialize the database run the queries from demo.sql

The following JavaScript code logs you in and out.

POST requests require a csrf token, all routes except /api/csrf and /api/login require being logged in. The session is stored in a cookie, this does not require additional code.

async function logout() {
    const response = await fetch('/api/logout', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': await getCsrfToken(),
        },
        body: 'null',
    })
    return await response.json()
}

async function login(username, password) {
    const response = await fetch('/api/login', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': await getCsrfToken(),
        },
        body: JSON.stringify({ username, password }),
    })
    return await response.json()
}

async function getCsrfToken() {
    const response = await fetch('/api/csrf')
    const payload = await response.json()
    return payload.token
}

login("admin","888888");

logout();