Skip to content

A simple RESTful API built with ASP.NET Core that provides JWT-based authentication with access tokens and refresh tokens.

Notifications You must be signed in to change notification settings

jger/c-sharp-auth-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

AuthAPI - RESTful Authentication API

A simple RESTful API built with ASP.NET Core that provides JWT-based authentication with access tokens and refresh tokens.

Features

  • JWT Authentication: Secure token-based authentication
  • Access Tokens: Short-lived tokens (15 minutes) for API access
  • Refresh Tokens: Long-lived tokens for token renewal
  • User Management: Simple user authentication with dummy data
  • Comprehensive Logging: Structured logging with Serilog
  • Swagger Documentation: API documentation and testing interface
  • Unit Tests: Comprehensive test coverage

Prerequisites

  • .NET 9.0 SDK
  • macOS, Windows, or Linux

Installation

  1. Clone the repository:
git clone <repository-url>
cd AuthAPI
  1. Restore dependencies:
dotnet restore
  1. Run the application:
dotnet run

The API will be available at:

API Endpoints

Authentication

POST /api/auth/login

Authenticate a user and receive access and refresh tokens.

Request Body:

{
  "email": "admin@example.com",
  "password": "admin123"
}

Response:

{
  "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "refreshToken": "base64-encoded-refresh-token",
  "expiresAt": "2024-01-15T10:30:00Z",
  "tokenType": "Bearer"
}

POST /api/auth/refresh

Refresh an access token using a refresh token.

Request Body:

{
  "refreshToken": "base64-encoded-refresh-token"
}

User Information

GET /api/user/whoami

Get current user information (requires authentication).

Headers:

Authorization: Bearer <access-token>

Response:

{
  "id": "1",
  "email": "admin@example.com",
  "createdAt": "2024-01-01T00:00:00Z"
}

Test Users

The API includes two test users:

Email Password
admin@example.com admin123
user@example.com user123

Configuration

The application uses appsettings.json for configuration:

{
  "Jwt": {
    "SecretKey": "your-super-secret-key-with-at-least-32-characters-for-production",
    "Issuer": "AuthAPI",
    "Audience": "AuthAPI"
  }
}

Important: Change the SecretKey in production to a secure, randomly generated key.

Running Tests

Run the test suite:

dotnet test

Run tests with coverage:

dotnet test --collect:"XPlat Code Coverage"

Project Structure

AuthAPI/
├── Controllers/
│   ├── AuthController.cs      # Authentication endpoints
│   └── UserController.cs      # User information endpoints
├── Models/
│   ├── LoginRequest.cs        # Login request model
│   ├── LoginResponse.cs       # Login response model
│   └── User.cs               # User model
├── Services/
│   ├── ITokenService.cs      # Token service interface
│   ├── TokenService.cs       # JWT token implementation
│   ├── IUserService.cs       # User service interface
│   └── UserService.cs        # User management implementation
├── AuthAPI.Tests/
│   ├── AuthControllerTests.cs # Authentication controller tests
│   ├── UserControllerTests.cs # User controller tests
│   └── TokenServiceTests.cs   # Token service tests
├── Program.cs                # Application entry point
├── appsettings.json          # Configuration
└── README.md                 # This file

Security Features

  • Password Hashing: SHA256 hashing for password storage
  • JWT Security: Signed tokens with configurable expiration
  • Token Validation: Comprehensive token validation
  • Secure Headers: HTTPS redirection and security headers

Logging

The application uses Serilog for structured logging:

  • Console Output: Real-time logging during development
  • File Logging: Daily rolling log files in logs/ directory
  • Structured Logs: JSON-formatted logs with correlation IDs

Development

Building the Project

dotnet build

Running in Development Mode

dotnet run --environment Development

Running in Production Mode

dotnet run --environment Production

Docker Support

Build the Docker image:

docker build -t authapi .

Run the container:

docker run -p 7001:7001 authapi

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass
  6. Submit a pull request

License

This project is licensed under the MIT License.

Notes

  • This is a demo application with dummy user data
  • In production, implement proper user storage (database)
  • Add refresh token storage and validation
  • Implement proper password hashing (bcrypt, Argon2)
  • Add rate limiting and additional security measures
  • Configure CORS policies for your frontend applications

About

A simple RESTful API built with ASP.NET Core that provides JWT-based authentication with access tokens and refresh tokens.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages