This boilerplate provides a basic template for securing a Spring REST API using Spring Security OAuth2 resource server.
for more information Check my article You need to ditch your JWT authentication filter
- Authentication and authorization using Spring Security
- Token-based authentication using JWT
- Role-based access control
- Permission-based access control (There is examples using annotation-based authorization and configuration-based authorization)
- Example API endpoints for demonstration purposes
- Clone the repository and import it into your preferred IDE
- Create a new file named
env.propertiesin the root directory of your project - Copy the contents of
env.properties.exampleintoenv.properties - Update the properties in
env.propertieswith your own values:DB_URL: your Postgresql database URL (e.g.jdbc:postgresql://localhost:5432/mydb)DB_USERNAME: your Postgresql database usernameDB_PASSWORD: your Postgresql database password
- Generate the private and public keys
app.private.keyandapp.public.keyusing the following commands:openssl genrsa -out app.private.key 2048openssl rsa -in app.private.key -pubout -out app.public.key- Move the generated keys to the
src/main/resourcesdirectory
- Run the application using your preferred method (e.g.
mvn spring-boot:run)
- Use the
POST /loginendpoint to authenticate and obtain a token - Use the obtained token to access protected API endpoints
- Use the
@PreAuthorize("hasRole('ROLE_ADMIN')")and@PreAuthorize("hasPermission('PERMISSION_ADMIN')")annotations to secure your endpoints
If you'd like to contribute to this boilerplate, please submit a pull request with your proposed changes. All contributions are welcome!