Skip to content

A full-stack authentication API with Spring Security and JWT for secure user registration, login, and role-based access control.

License

Notifications You must be signed in to change notification settings

aashif-sajah/spring-security-jwt

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

35 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Spring Security JWT API πŸ”

License: MIT Java 17 Spring Boot 3

A production-ready JWT authentication system with role-based access control, built with Spring Boot and Angular.

Features ✨

  • βœ… JWT Authentication & Authorization
  • βœ… Role-Based Access Control (Admin/User)
  • βœ… Secure Password Storage with BCrypt
  • βœ… PostgreSQL Integration
  • βœ… CORS Configuration
  • βœ… Angular Frontend Demo
  • βœ… API Rate Limiting
  • βœ… Refresh Token Support

Tech Stack πŸ› οΈ

Backend

  • Java 17
  • Spring Boot 3.2
  • Spring Security
  • JJWT 0.12.5
  • PostgreSQL
  • Maven

Frontend

  • Angular 19
  • RxJS 7.8
  • Angular Material
  • JWT Interceptors

Installation πŸ’»

1. Clone Repository

git clone https://github.com/yourusername/spring-security-jwt.git
cd spring-security-jwt

2. Database Setup (PostgreSQL)

CREATE DATABASE security_db;
CREATE USER api_user WITH PASSWORD 'your_strong_password';
GRANT ALL PRIVILEGES ON DATABASE security_db TO api_user;

3. Configure Application

# src/main/resources/application.properties
spring.datasource.url=jdbc:postgresql://localhost:5432/security_db
spring.datasource.username=api_user
spring.datasource.password=your_strong_password
jwt.secret=your-512-bit-secret-key # Generate using: openssl rand -base64 512
jwt.expiration=86400000 # 24 hours

4. Run Backend

mvn spring-boot:run

5. Run Angular Frontend

cd frontend
npm install
ng serve --open

API Endpoints 🌐

Method Endpoint Description Auth Required
POST /authenticate Get JWT Token Public
POST /registerNewUser Register new user Public
GET /forAdmin Admin-only endpoint ADMIN
GET /forUser User-specific endpoint USER

Usage Examples πŸ“

Authentication Request

POST /authenticate HTTP/1.1
Content-Type: application/json

{
  "userName": "admin",
  "userPassword": "admin"
}

Successful Response

{
  "jwtToken": "eyJhbGciOiJIUzUxMiJ9...",
  "user": {
    "userName": "admin",
    "roles": ["ROLE_ADMIN"]
  }
}

Secure Request

GET /forAdmin HTTP/1.1
Authorization: Bearer eyJhbGciOiJIUzUxMiJ9...

Security Implementation πŸ”’

JWT Flow

sequenceDiagram
    Client->>Server: POST /authenticate
    Server->>Client: JWT Token
    Client->>Server: Requests with JWT
    Server->>Server: Validate Token & Roles
    Server->>Client: Secure Data
Loading

Role Hierarchy

ADMIN > USER

Frontend Integration πŸ–₯️

Angular Interceptor

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    const token = localStorage.getItem('jwtToken');
    
    if (token) {
      req = req.clone({
        setHeaders: {
          Authorization: `Bearer ${token}`
        }
      });
    }
    return next.handle(req);
  }
}

Auth Guard

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
  constructor(private authService: UserAuthService) {}

  canActivate(route: ActivatedRouteSnapshot): boolean {
    const requiredRoles = route.data['roles'];
    return this.authService.hasRoles(requiredRoles);
  }
}

Contributing 🀝

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

License πŸ“„

Distributed under the MIT License. See LICENSE for more information.


Made with ❀️ by [Aashif Sajah] - @cliff.adventurer_

About

A full-stack authentication API with Spring Security and JWT for secure user registration, login, and role-based access control.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published