Search code examples
spring-bootspring-security

How to get login and pass from rest request in spring boot?


I'm writing REST app with spring boot and spring security with JWT.

I created registration end point which just creates an account.

I wanted to implement authentication througn basic auth with login and password which would returns a jwt token. Other requests would authenticate by token.

But I can't implement security by login and password and JWT both, so I tried to perform basic auth manually and leave spring security by token.

How can I get login and password from rest request in controller to check if the account exists in the database manyally?

The example of basic auth: enter image description here


Solution

  • JWT token is an string joined by points. It has three pieces and these are encoded in base64. The second piece has the information of the user. You can pass this information to the security context and get wherever you want.

    Decode the token, set the information in UserDetails (you can extend this class) and pass it to the UsernamePasswordAuthenticationToken. Pass this object to the security context and get the information in your controllers using SecurityContextHolder.getContext().getAuthentication();

    More info here: https://www.toptal.com/spring/spring-security-tutorial

    // Get user identity and set it on the spring security context
            UserDetails userDetails = userRepo
                .findByUsername(jwtTokenUtil.getUsername(token))
                .orElse(null);
    
            UsernamePasswordAuthenticationToken
                authentication = new UsernamePasswordAuthenticationToken(
                    userDetails, null,
                    userDetails == null ?
                        List.of() : userDetails.getAuthorities()
                );
    
            authentication.setDetails(
                new WebAuthenticationDetailsSource().buildDetails(request)
            );
    
            SecurityContextHolder.getContext().setAuthentication(authentication);