Comprehensive Guide to OAuth2.0: Principles, Four Grant Types, and Implementation with Spring Security
This article explains why OAuth2.0 is needed, clarifies the differences between tokens and passwords, describes the OAuth2.0 protocol and its four grant types, and provides a step‑by‑step Spring Boot + Spring Cloud Alibaba implementation of an authorization server and a resource server with full code examples.
This article introduces OAuth2.0, explains why it is needed using a real‑world analogy, distinguishes tokens from passwords, and details the four OAuth2.0 grant types. It then walks through building an authorization server and a resource server with Spring Boot, Spring Cloud Alibaba, and Spring Security, providing complete configuration and code snippets.
Why OAuth2.0 Is Needed
OAuth2 solves the problem of granting limited access without exposing user credentials, similar to a temporary door‑code for a delivery person that expires after a set time.
Token vs. Password
Different expiration : tokens expire, passwords are permanent unless changed.
Different permissions : tokens can be scoped to specific resources.
Revocable : tokens can be revoked, passwords cannot.
What Is OAuth2?
OAuth2 is an open standard that allows third‑party applications to access a user's protected resources (e.g., photos, videos) without sharing the username and password. It does this by issuing a token that represents the delegated permission.
OAuth2 is especially useful for front‑end/back‑end separated architectures where traditional session‑based authentication is inconvenient.
OAuth2.0 Four Grant Types
Authorization Code : Most common, highest security, suitable for server‑side web apps.
Implicit : Token is returned directly to the front end; used for pure static sites with low security requirements.
Password : Client collects username/password and exchanges them for a token; requires high trust.
Client Credentials : Client obtains a token on its own behalf, not on behalf of a user.
1. Authorization Code Flow
The client redirects the user to the authorization server to obtain an authorization code, then exchanges the code for an access token.
/oauth/authorize?client_id=&response_type=code&scope=&redirect_uri=Key parameters: client_id: Unique identifier issued by the authorization server. response_type: Fixed value code. scope: Requested permissions. redirect_uri: URL to which the server redirects with the code parameter.
/oauth/token?client_id=&client_secret=&grant_type=authorization_code&code=NMoj5y&redirect_uri=The response contains a JSON payload with access_token, refresh_token, expiration, etc.
2. Implicit Flow
The client directly requests a token without an intermediate code.
/oauth/authorize?response_type=token&client_id=CLIENT_ID&redirect_uri=CALLBACK_URL&scope=The token is returned in the fragment part of the redirect URL (e.g., #token=NPmdj5).
3. Password Flow
The client sends the user's username and password to obtain a token.
/oauth/token?grant_type=password&username=&password=&client_id=&client_secret=The server returns the same JSON structure as the authorization code flow.
4. Client Credentials Flow
Used by machine‑to‑machine applications.
/oauth/token?grant_type=client_credentials&client_id=&client_secret=The response contains an access_token scoped to the client.
Building the Authorization Server
The project uses Spring Boot + Spring Cloud Alibaba. The module oauth2-auth-server-in-memory contains the server configuration.
Key configuration steps:
Add spring-boot-starter-security and spring-cloud-starter-oauth2 dependencies.
Configure SecurityConfig with BCrypt password encoder, in‑memory users, and an AuthenticationManager.
Set token storage (in‑memory for demo, can be Redis or JWT).
Create an OAuth2 configuration class extending AuthorizationServerConfigurerAdapter and annotated with @EnableAuthorizationServer.
Define client details (client_id, secret, scopes, grant types, redirect URIs) in memory.
Configure token services, authorization code services, and endpoint security.
Building the Resource Server
The module oauth2-auth-resource-in-memory acts as the protected resource.
Key steps:
Annotate with @EnableResourceServer and extend ResourceServerConfigurerAdapter.
Configure token validation by calling /oauth/check_token on the authorization server.
Define security rules (e.g., .access("#oauth2.hasScope('all')")).
Create test endpoints /hello (any authenticated user) and /admin (requires ROLE_admin).
Testing the Four Grant Types
Start both the authorization server and resource server, then use a browser or Postman to exercise each flow.
Authorization Code
1) Request an authorization code via GET /oauth/authorize?...&response_type=code → login → approve → receive code. 2) Exchange the code for a token via POST /oauth/token. 3) Access /hello with Authorization: Bearer <access_token>.
Password
Directly request a token with username/password via POST /oauth/token?grant_type=password and then call the protected APIs.
Implicit
Request a token directly with response_type=token; after login and approval the token appears in the redirect fragment.
Client Credentials
Obtain a token for the client itself via POST /oauth/token?grant_type=client_credentials.
Other Endpoints
Refresh token: /oauth/token?grant_type=refresh_token&refresh_token=... Check token:
/oauth/check_token?token=...Summary
The article covered OAuth2.0 fundamentals, the four grant types, and provided a complete Spring Security‑based implementation of both an authorization server and a resource server, including configuration, code snippets, and testing instructions.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Code Ape Tech Column
Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
