﻿authAndAuth@openK - Backend REST-Service documentation
======================================================
:Author: Frank Dietrich
:Email: frank.dietrich@pta.de
:Date: 2017-07-12
:Revision: 1
:icons:
:source-highlighter: highlightjs
:highlightjs-theme: solarized_dark


== Base-URL

----
http://<host>:<port>/<name-of-war>/rest/beservice
----

== Common Features
All services may return the following http status codes:

.Http-Status-Codes
[options="header,footer"]
|=========================================================
|Code|Description|Usage within the application
|200|OK|-
|400|Bad Request|The structure of the request (for example a JSON within a post request) is not correct
|401|Unauthorized|Login-credentials are wrong or there is an invalid session token
|500|Internal Server Error|An unexpected error occurred
|=========================================================

If there is a special service behavior regarding the returned http status code, then it will be explained within the service description.

== Protection

The protection of services is implemented by a security token following the JWT (JSON Web Token) specification:
https://jwt.io/

The *“login”*-service provides a JWT, when called with valid user-credentials.
The security token (access token) (which is part of the JWT) has always to be provided with the
HTTP-Header-Parameter "Authorization", in order to access a secured services later on.


=== JSON Web Token

The token has several purposes. A typical client of the Auth&Auth-Service needs to use
the following features:

. *access token* to access functions of a secured service
. *user-information* to get extended information about the own user
. *user-roles* of the own user.

Even though JWT is a defined standard, we only will describe those features inside this document,
which are directly used by the Auth&Auth-Service.

Generally JWT uses *base64-encoding*. The data, that is stored in a token is always
encoded with *base64*.

[IMPORTANT]
====
The data in the examples has been shortened. Real examples would be very long and hard to read.
====

==== Access token
The *access token* can be directly found in the field "access_token" within the JWT.



Example:
[source,json]
----
{
    "access_token":"eyJhbGciOiJSUzI1NiIsInR5cCIgOiAixxxIn0.eyBBB.eydkk",
    "expires_in":300,
    "refresh_expires_in":1800,
    "refresh_token":"eyJhbGciOiJSUzI1NiIsInR5cCIgOiAixxxIn0.eyJqdGwLTQyMTYtOD.eydkk",
    "token_type":"bearer",
    "id_token":"eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2l.eyJqdGkLTRjZTItYT.oUkke",
    "not-before-policy":1502453751,
    "session_state":"8b4e6979-1d51-4086-9db5-d296f70b4b65"
}

----


==== User-Information/UserRoles

The 2nd part (between the first and the second period *"."* - in this example "'eyBBB'") of the access-token is called the *"access-token-payload"*. When decoded from Base64 it could
look like this:

[source,json]
----
{
    "jti":"a3d15ccf-c0e3-4534-a05a-f18b3a7c778b",
    "exp":1505736257,
    "nbf":0,
    "iat":1505735957,
    "iss":"http://authserver:8080/auth/realms/elogbook",
    "aud":"elogbook-backend",
    "sub":"c4b78aa7-91d2-45d7-8ca3-163156d9ee40",
    "typ":"Bearer",
    "azp":"elogbook-backend",
    "auth_time":0,
    "session_state":"59ae4a68-595b-4345-873d-aadf0a3efc94",
    "acr":"1",
    "allowed-origins":["*"],
    "realm_access":{"roles":["elogbook-normaluser","uma_authorization"]},
    "resource_access":{"account":{"roles":["manage-account","manage-account-links","view-profile"]}},
    "name":"Hugo Boss",
    "preferred_username":"hugo",
    "given_name":"Hugo",
    "family_name":"Boss"
}
----

The configured roles of the user can be determined from the json array:

 * *realm_access"*

Extended
user information can be found in the fields:

 * *"name"*
 * *"perferred_username"*
 * *"given_name"*
 * *"family_name"*.


== Services
=== Receive Version Information
This service returns the current version of the backend implementation and the version of the database structure.

*URL:* /versionInfo

*Method:* GET

*Request-Headers*:

*Produces*: application/json

*Response*:
[source,json]
----
{
    "backendVersion": "0.1.1-Snapshot"
}
----

*Protection*: none

*Remarks*:

=== Login
This service receives login credentials in order to perform the authentication. If the login succeeds,
it provides a valid JWT, used for accessing other services later on.

*URL:* /login

*Method:* POST

*Request-Body*:
[source,json]
----
{
  "userName": "Mustermann",
  "password": "clearpassword"
}
----

*Produces*: application/json

*Response*:

JWT (JSON Web Token)

*Remarks*: See chapter "*JWT*" for detailed informations about the features of the returned token.


=== Logout
This services kills the server session belonging to the the given session token.

*URL:* /logout

*Method:* POST

*Request-Headers*:

* Authorization – Existing access token


*Produces*: application/json

*Response*:

*Remarks*:

=== CheckAuthorization
This services receives a JWT in the "Authorization" Http header and checks, if its still valid.
If it is valid, it resets the inactivity time for that token.

*URL:* /checkAuth

*Method:* GET

*Request-Headers*:

* Authorization – Existing access token


*Produces*: application/json

*Response*:
[source,json]
----
{
  "ret": "OK"
}
----

*Remarks*: This service return OK when the provided token is still valid. Otherwise it returns a 401 - "Unauthorized" Http Code.

=== Get user modules for the current user
This service returns the modules for which the user is authorized.

*URL:* /userModulesForUser

*Method:* GET

*Request-Headers*:

* Authorization – Existing access token


*Produces*: application/json

*Response*:
[source,json]
----
[
    {
        "name":"Betriebstagebuch",
        "cols":1,
        "rows":1,
        "color":"#ffffff",
        "link":"http://172.18.22.160:8880/elogbookFE",
        "pictureLink":"https://www.openkonsequenz.de/xxxelogbuch_2443636.jpg",
        "requiredRole":"elogbook_access"
    }
    ,
    {
        "name":"Bereitschaftsplanung",
        "cols":1,
        "rows":1,
        "color":"#ffffff",
        "link":"https://www.openkonsequenz.de/anwender/xxxx/94-bereitschaftsplan",
        "pictureLink":"https://www.openkonsequenz.de/medien/xxx/l_bereitschaftsplan_57882047.jpg",
        "requiredRole":"planning_access"
    }
    ,
    {
    ...
    }
]
----

*Remarks*: This service checks if the currently logged in user has the role "requiredRole" in its JWT and
returns the modules he is authorized for.


=== Get all users for a specific role
This service returns all users belonging to the specified role.

*URL:* /usersForRole/{userRole}

*Method:* GET

*Path-Parameter*: userRole

* The role name like it is defined in Keycloak

*Request-Headers*:

* Authorization – Existing access token


*Produces*: application/json

*Response*:
[source,json]
----
[
    {
        "id": "359ef9c9-77df-4a3d-a9c9-f96d837d2d57",
        "createdTimestamp": 1501594173784,
        "username": "admin",
        "enabled": true,
        "totp": false,
        "emailVerified": false,
        "firstName": "Administrator",
        "lastName": "Administratowich",
        "realmRoles": [
            "elogbook-superuser",
            "elogbook_access",
            "uma_authorization",
            "elogbook-normaluser"
        ],
        "disableableCredentialTypes": [
            "password"
        ],
        "requiredActions": [],
        "access": {
            "manageGroupMembership": false,
            "view": true,
            "mapRoles": false,
            "impersonate": false,
            "manage": false
        }
    },
    {
        "id": "c4b78aa7-91d2-45d7-8ca3-163156d9ee40",
        "createdTimestamp": 1501594239066,
        "username": "hugo",
        "enabled": true,
        "totp": false,
        "emailVerified": false,
        "firstName": "Hugo",
        "lastName": "Boss",
        "realmRoles": [
            "elogbook_access",
            "elogbook-normaluser"
        ],
        "disableableCredentialTypes": [
            "password"
        ],
        "requiredActions": [],
        "access": {
            "manageGroupMembership": false,
            "view": true,
            "mapRoles": false,
            "impersonate": false,
            "manage": false
        }
    },
    {
      ...
    }
]
----

*Remarks*:

=== Get health state
This service returns the health state of this module.

*URL:* /healthcheck/pretty=true

*Method:* GET



*Request-Headers*:

* Authorization – none


*Produces*: application/json

*Response*:

If the module is healthy then...
[source,json]
----
{"Keycloak present":{"healthy":true}}
----

If the module is *not* healthy...
[source,json]
----
{
    "Keycloak present":
    {
        "healthy":false,
        "message":"<Error message>"
    }
}
----


*Remarks*:



