0

i'm having a trouble with spring security's authenticationManager. currently my project has a signup and a login endpoint. login endpoint works fine and i get jwt token after logging in. but i want user to get logged in automatically after signing up. the problem is after sending dto, user gets created but it doesn't get authenticated and it stucks at below code in signup controller with no exception thrown back.

authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));

i just get a 401 Unauthorized in postman. here are the neccessary codes for figuring out the problem:

SecurityConfiguration.java

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration {

    @Autowired
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
    
    @Autowired
    private JwtRequestFilter jwtRequestFilter;
    
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }
    
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        
        http.csrf()
            .disable()
            .authorizeRequests()
            .antMatchers("/", "index", "/css/*", "/js/*")
            .permitAll()
            .antMatchers("/flightBooking", "/flightBooking/signup", "/flightBooking/login")
            .permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)
            .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
        
        return http.build();
    }
    
}

LoginController.java

@RestController
@RequestMapping("/flightBooking/login")
public class LoginController {
    
    @Autowired
    private AuthenticationManager authenticationManager;
    
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    
    @Autowired
    private FlightBookingUserDetailsService flightBookingUserDetailsService;
    
    @PostMapping
    public ResponseEntity<?> createAuthenticationToken(@RequestBody AuthReq authReq) throws Exception {
        this.authenticate(authReq.getUsername(), authReq.getPassword());
        final UserDetails userDetails = flightBookingUserDetailsService.loadUserByUsername(authReq.getUsername());
        final String token = jwtTokenUtil.generateToken(userDetails);
        return ResponseEntity.ok(new AuthRes(token));
    }
    
    private void authenticate(String username, String password) throws Exception {
        try {
            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (DisabledException e) {
            throw new Exception("USER_DISABLED", e);
        } catch (BadCredentialsException e) {
            throw new Exception("INVALID_EXCEPTION", e);
        }
    }
    
}

SignupController.java

@RestController
@RequestMapping("/flightBooking/signup")
public class SignupController {
    
    @Autowired
    private AuthenticationManager authenticationManager;
    
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    
    @Autowired
    private FlightBookingUserDetailsService flightBookingUserDetailsService;
    
    @Autowired
    private IUserService iUserService;
    
    @Autowired
    private UserMapper mapper;
    

    @PostMapping
    public ResponseEntity<?> signUp(@RequestBody UserDto userDto) throws Exception {
        userDto.setRoleId(2L);
        Long userId = this.iUserService.saveEntity(this.mapper.map(userDto));
        if (userId > 0) {
            this.authenticate(userDto.getUsername(), userDto.getUserPass());
            final UserDetails userDetails = flightBookingUserDetailsService.loadUserByUsername(userDto.getUsername());
            final String token = jwtTokenUtil.generateToken(userDetails);
            AuthRes res = new AuthRes(token);
            res.setId(userId);
            return ResponseEntity.ok(res);
        }
        return null;
    }
    
    private void authenticate(String username, String password) throws Exception {
        try {
            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (DisabledException e) {
            throw new Exception("USER_DISABLED", e);
        } catch (BadCredentialsException e) {
            throw new Exception("INVALID_EXCEPTION", e);
        }
    }
    
}

any help would be appreciated. thanks!

  • In which line does the code gets stuck? Does this [post](https://stackoverflow.com/questions/3813028/auto-login-after-successful-registration) help? – aglamp Jun 24 '22 at 14:49
  • @aglamp the code get stuck in SignupController in authenticate method at this line: authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password)); – hossein frkh Jun 24 '22 at 17:40

0 Answers0