Skip to main content

Overview

VidaPlus API uses JWT (JSON Web Tokens) for secure authentication. All protected endpoints require a valid access token in the Authorization header.

Authentication Flow

1

Login with Credentials

Send your email and password to the /auth/token endpoint to receive an access token.
2

Store the Token

Save the access token securely in your application.
3

Include Token in Requests

Add the token to the Authorization header for all protected API calls.
4

Refresh When Needed

Use the /auth/refresh_token endpoint to get a new token before expiration.

Getting an Access Token

Request

curl -X POST "https://api.vidaplus.com/auth/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "[email protected]&password=yourpassword"

Response

{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "bearer"
}
The username field should contain the user’s email address, not a traditional username.

Token Structure

Tokens are created using the create_access_token function from vidaplus/security.py:20:
def create_access_token(data: dict):
    to_encode = data.copy()
    expire = datetime.now(tz=ZoneInfo('UTC')) + timedelta(
        minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES
    )
    to_encode.update({'exp': expire})
    encoded_jwt = encode(
        to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM
    )
    return encoded_jwt

Token Payload

The JWT payload contains:
  • sub: User’s email address (subject)
  • exp: Token expiration timestamp

Using the Access Token

Include the token in the Authorization header with the Bearer scheme:
curl -X GET "https://api.vidaplus.com/pacientes/" \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

Token Validation

The API validates tokens using the get_current_user function from vidaplus/security.py:43:
def get_current_user(
    session: Session = Depends(get_session),
    token: str = Depends(oauth2_scheme),
):
    credentials_exception = HTTPException(
        status_code=HTTPStatus.UNAUTHORIZED,
        detail='Could not validate credentials',
        headers={'WWW-Authenticate': 'Bearer'},
    )

    try:
        payload = decode(
            token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]
        )
        subject_email = payload.get('sub')

        if not subject_email:
            raise credentials_exception

    except DecodeError:
        raise credentials_exception

    user = session.scalar(
        select(BaseUser).where(BaseUser.email == subject_email)
    )

    if not user:
        raise credentials_exception

    return user

Refreshing Tokens

To refresh an access token before it expires, use the refresh endpoint:

Request

curl -X POST "https://api.vidaplus.com/auth/refresh_token" \
  -H "Authorization: Bearer your_current_token"

Response

{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "bearer"
}
The refresh endpoint implementation from vidaplus/api/endpoints/auth.py:50:
@router.post('/refresh_token', response_model=Token)
async def refresh_access_token(user: CurrentUser):
    new_access_token = create_access_token(data={'sub': user.email})
    return {'access_token': new_access_token, 'token_type': 'bearer'}
Tokens expire after the duration specified in ACCESS_TOKEN_EXPIRE_MINUTES (configured in settings). Always implement token refresh logic in your application.

Password Security

VidaPlus uses pwdlib for secure password hashing with recommended settings:
from pwdlib import PasswordHash

pwd_context = PasswordHash.recommended()

def get_password_hash(password: str):
    return pwd_context.hash(password)

def verify_password(plain_password: str, hashed_password: str):
    return pwd_context.verify(plain_password, hashed_password)

Configuration

Authentication settings are defined in vidaplus/settings.py:
class Settings(BaseSettings):
    DATABASE_URL: str
    SECRET_KEY: str              # JWT signing key
    ALGORITHM: str                # JWT algorithm (e.g., HS256)
    ACCESS_TOKEN_EXPIRE_MINUTES: int  # Token lifetime
Set these environment variables in your .env file. Never commit the SECRET_KEY to version control.

Common Authentication Errors

Status CodeDescriptionSolution
401 UnauthorizedInvalid credentialsVerify email and password
401 UnauthorizedToken expiredRefresh or obtain new token
401 UnauthorizedInvalid token formatCheck Authorization header
403 ForbiddenValid token, insufficient permissionsCheck user role and permissions

Best Practices

Secure Storage

Store tokens securely using httpOnly cookies or secure storage APIs. Never store in localStorage for production apps.

Token Refresh

Implement automatic token refresh before expiration to maintain seamless user experience.

HTTPS Only

Always use HTTPS in production to prevent token interception.

Logout

Clear tokens from storage when users log out.

Next Steps

Authorization

Learn about role-based access control

Error Handling

Handle authentication errors properly

Build docs developers (and LLMs) love