OAuth2 Login and Security Best Practices
Harry
· 14 Sep 2026
· 2 views
Advertisement
Social login with OAuth2
Instead of managing passwords yourself, you can let users sign in with an existing account (Google, GitHub) via OAuth2. Spring Security has first-class support through a starter:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
spring.security.oauth2.client.registration.google.client-id=YOUR_ID
spring.security.oauth2.client.registration.google.client-secret=YOUR_SECRET
http.oauth2Login(Customizer.withDefaults());
Spring redirects users to the provider, handles the callback, and hands you an authenticated principal. Important: if you enable OAuth2 login you must supply a real client id and secret, or the application context fails to start.
CSRF and CORS
- CSRF protection is on by default and should stay on for browser sessions with cookies. For a stateless JWT API it is safe to disable, since there is no session cookie to forge.
- CORS controls which browser origins may call your API. Configure it explicitly for your front-end’s domain rather than allowing everything.
Everyday best practices
- Always hash passwords (BCrypt) and enforce a sensible minimum strength.
- Serve everything over HTTPS so tokens and credentials are never sent in the clear.
- Give tokens short lifetimes and use refresh tokens for longer sessions.
- Grant the least privilege necessary; default to denying access.
- Keep client secrets and signing keys out of source control – use environment variables.
Key points
- The OAuth2 client starter enables social login; a valid client id/secret is required.
- Keep CSRF on for cookie sessions; disabling it is acceptable for stateless JWT APIs.
- Configure CORS for your specific front-end origin, not a wildcard.
- HTTPS, short-lived tokens, least privilege and secret hygiene are the essentials.