Last active
April 6, 2025 22:11
-
-
Save itzg/ab9cdfca4b51e161ef4a21154ae83943 to your computer and use it in GitHub Desktop.
Example of using Spring Security @AuthenticationPrincipal with OAuth2 Log In
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package me.itzg.tryspringbootoauthlogin.security; | |
public record AppUserProfile( | |
String oauthId, | |
java.net.URL issuer, | |
String name, | |
String givenName, | |
String familyName, | |
String pictureUrl, | |
String profileUrl, | |
String email | |
) { | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import me.itzg.tryspringbootoauthlogin.security.AppUserProfile; | |
import me.itzg.tryspringbootoauthlogin.security.CurrentAppUserProfile; | |
import org.springframework.web.bind.annotation.GetMapping; | |
import org.springframework.web.bind.annotation.RequestMapping; | |
import org.springframework.web.bind.annotation.RestController; | |
@RestController | |
@RequestMapping("/api") | |
public class ApiController { | |
/** | |
* | |
* @param user for OAuth2 login it's an {@link org.springframework.security.oauth2.core.oidc.user.OidcUser}, | |
* which extends {@link DefaultOAuth2User} (which implements {@link OAuth2User}), implements {@link OidcUser} | |
* @return the logged-in user's name | |
*/ | |
@GetMapping("/profile") | |
public AppUserProfile profileName(@AuthenticationPrincipal OidcUser user) { | |
return user != null ? | |
new AppUserProfile( | |
user.getName(), | |
user.getIssuer(), | |
user.getFullName(), | |
user.getGivenName(), | |
user.getFamilyName(), | |
user.getPicture(), | |
user.getProfile(), | |
user.getEmail() | |
) | |
: null; | |
} | |
} |
Author
itzg
commented
Apr 6, 2025
- https://docs.spring.io/spring-security/reference/servlet/oauth2/login/index.html
- https://docs.spring.io/spring-security/reference/servlet/integrations/mvc.html#mvc-authentication-principal
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment