IMS94 / spring-boot-jwt-authentication

JWT Authentication with Spring Boot’s inbuilt OAuth2 Resource Server
https://loneidealist.medium.com/stateless-jwt-authentication-with-spring-boot-a-better-approach-1f5dbae6c30f
37 stars 23 forks source link

login rest endpoint clarification #1

Closed fabioportieri closed 2 years ago

fabioportieri commented 3 years ago

hello

i'm trying to implement a stateless oauth2 with spring boot and otka as IAM / idp with authorization code flow and angular front end

i'm struggling with a way to get the access token in jwt format for my SPA front end application

in your demo you provide a /login rest endpoint which accept username and password but i don't understand how am i supposed to call that endpoint, because i don't have username and password

so far i get to the point where i succesfully authenticate with okta, but i want my SPA to retrieve the access token in order to store it in local storage ( i have an additional basic auth method setup that already does that)

i thought of adding:

                .oauth2Login().defaultSuccessUrl("/landing-oidc")

and then in the page to call a rest api that would provide me the token

    @GetMapping(path = "auth")
    public ResponseEntity<JWTToken> authOidc() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

but for some reason authentication there results as anonymous

could you provide some insights about that?

thank you in advance

IMS94 commented 3 years ago

@fabioportieri just saw your issue. You have to implement a success handler as well to redirect the user to a given path in your SPA.

public class OAuth2SuccessHandler implements AuthenticationSuccessHandler {

    @Value("${app.oauth2.redirectUrl}")
    private String redirectUrl;

    @Override
    public void onAuthenticationSuccess(
            HttpServletRequest request,
            HttpServletResponse response,
            Authentication authentication) throws IOException, ServletException {
        OAuth2AuthenticationToken authenticationToken = (OAuth2AuthenticationToken) authentication;
        OAuth2User oAuth2User = authenticationToken.getPrincipal();

        // Get required attributes
        Map<String, Object> attributes = oAuth2User.getAttributes();

        // 1. Name
        String name = String.valueOf(attributes.get("name"));
        List<String> names = Stream.of(name.split(" "))
                .filter(s -> !s.trim().isEmpty())
                .collect(Collectors.toList());
        String firstName = names.size() > 0 ? names.get(0) : "";
        String lastName = names.size() > 1 ? names.get(1) : "";

        // 2. Email
        String email = String.valueOf(attributes.get("email"));

        // 3. ID
        String externalId = String.valueOf(attributes.get("id"));
        log.info("Authenticating user: {} -> Attributes: {}", email, attributes);

        log.info("Authenticated user: {}", authentication);
                // Add a cookie to the response with authentication information
        response.sendRedirect(redirectUrl);
    }
}
IMS94 commented 2 years ago

Closing this due to inactivity.