Skip to content

Instantly share code, notes, and snippets.

@itzg
Last active April 6, 2025 22:11
Show Gist options
  • Save itzg/ab9cdfca4b51e161ef4a21154ae83943 to your computer and use it in GitHub Desktop.
Save itzg/ab9cdfca4b51e161ef4a21154ae83943 to your computer and use it in GitHub Desktop.
Example of using Spring Security @AuthenticationPrincipal with OAuth2 Log In
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
) {
}
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;
}
}