How to configure oAuth2 with password flow with Swagger ui in spring boot rest application
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
If you want Swagger UI to request tokens by OAuth2 password flow in a Spring Boot REST application, the usual job is to describe an existing token endpoint in your OpenAPI configuration. The important caveat is that the password grant is a legacy flow, so this setup is mainly for maintaining older systems rather than designing a new OAuth architecture.
Understand What Swagger UI Is Actually Doing
Swagger UI is not your authorization server. It is only a client that knows how to show an authorization dialog, send the username and password to a token endpoint, and attach the returned bearer token to protected API calls.
That means you normally need two things:
- a Spring Boot API that exposes protected endpoints
- an OAuth2 token endpoint that accepts the password grant
In many legacy systems, that token endpoint lives in the same platform, but it can also be external.
Declare the Password Flow in OpenAPI
With springdoc-openapi, you can describe the password flow directly in your OpenAPI bean.
The key setting is the password flow with a valid tokenUrl. Once Swagger UI sees that scheme, it can render the Authorize button with the fields needed for this flow.
Mark Protected Endpoints
You can then apply the scheme to your controllers or operations.
That tells the generated OpenAPI document that the endpoint expects the configured security scheme.
Configure Swagger UI Client Values
If your token endpoint expects client credentials, configure Swagger UI accordingly in application properties.
Those values are for the OAuth client that Swagger UI behaves as. They are not the resource owner username and password.
Secure the API Side Separately
Your Spring Security configuration still needs to validate bearer tokens for API requests. A simple resource server setup looks like this:
This protects the API while still leaving Swagger UI reachable.
Common Pitfalls
- Swagger UI can describe and use the password flow, but it does not implement the token endpoint for you.
- The password grant is a legacy OAuth2 flow, so treat this as maintenance guidance rather than a best-practice design for new systems.
- Mixing up client credentials with the end user's username and password is a common configuration mistake.
- Protect the API endpoints and permit only the documentation endpoints needed for Swagger UI itself.
Summary
- Configure the password OAuth2 flow in your OpenAPI security scheme with a real
tokenUrl. - Let Swagger UI act as an OAuth client for an existing token endpoint.
- Mark secured endpoints with the configured security requirement.
- Use this setup mainly for legacy password-grant systems, not as a default choice for new OAuth implementations.

