Implementing GitHub and QQ OAuth2 Login with Spring Boot
This article provides a step‑by‑step guide to integrating GitHub and QQ third‑party OAuth2 login in a Spring Boot backend, covering app registration, required URLs, state handling to prevent CSRF, and complete Java code for authorization, token exchange, and user info retrieval.
This article demonstrates how to integrate third‑party OAuth2 login for GitHub and QQ in a Spring Boot application, covering application registration, required URLs, and the complete authorization code flow.
GitHub login
1. Register an OAuth app on GitHub (Developer settings → New OAuth App) and obtain the Client ID, Client Secret and set the redirect URL.
2. Create a simple HTML page with two links pointing to /githubLogin and /qqLogin .
3. Implement githubLogin(HttpServletResponse response) which builds the authorization URL with response_type=code , client_id , state and redirect_uri , stores a generated state (e.g., in Redis) and redirects the user.
4. In githubCallback(String code, String state, HttpServletResponse response) verify the state , exchange the code for an access_token via a POST request to https://github.com/login/oauth/access_token , then request the user profile from https://api.github.com/user and write the result.
QQ login
1. Register an application on the QQ Open Platform, obtain APP ID, APP Key and configure the callback URL.
2. Implement qqLogin(HttpServletResponse response) similar to the GitHub method, using QQ’s authorization endpoint https://graph.qq.com/oauth2.0/authorize .
3. In qqCallback(String code, String state, HttpServletResponse response) verify state , obtain an access_token from https://graph.qq.com/oauth2.0/token , retrieve the OpenID via https://graph.qq.com/oauth2.0/me , then fetch user info from https://graph.qq.com/user/get_user_info and output it.
The article also discusses the importance of the state parameter to prevent CSRF attacks and suggests storing it in Redis or a HashMap.
All code examples are written in Java with Spring MVC annotations and rely on utility classes for HTTP requests and JSON handling.
Java Architect Essentials
Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.
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.