Unable to authenticate with UsernameAndPasswordToken and set Cookie with Spring Security

132 Views Asked by At

I am building Spring Boot/ReactJS app and i have following issue in authenticating the user and generating JSSESSIONID.

My SecurityConfig class looks like this:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(bCryptPasswordEncoder());
    }

    @Override
    @Bean(BeanIds.AUTHENTICATION_MANAGER)
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/login").permitAll()
                .anyRequest().authenticated()

                .and()
                .logout().deleteCookies("JSESSIONID")

                .and()
                .rememberMe().key("uniqueAndSecret").tokenValiditySeconds(86400)

                .and()
                .csrf().disable();
    }

    @Bean
    BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder();}

}

And my LoginController:

@RestController
@RequestMapping(path="/",produces = "application/json")
@CrossOrigin(origins="*")
public class LoginController {

    private final AuthenticationManager authenticationManager;

    public LoginController(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @PostMapping("/login")
    @ResponseStatus(HttpStatus.OK)
    public void login(HttpServletRequest req, @RequestBody LoginRequest loginRequest) {
        UsernamePasswordAuthenticationToken authReq
                = new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword());
        Authentication auth = authenticationManager.authenticate(authReq);

        SecurityContext sc = SecurityContextHolder.getContext();
        sc.setAuthentication(auth);
        HttpSession session = req.getSession(true);
        session.setAttribute(SPRING_SECURITY_CONTEXT_KEY, sc);
    }

}

And when i call request, i have a BadCredentials exception thrown when calling authenticationManager.authenticate(authReq) because the authReq's content log is org.springframework.security.authentication.UsernamePasswordAuthenticationToken@6582813: Principal: pavel; Credentials: [PROTECTED]; Authenticated: false; Details: null; Not granted any authorities

Am i missing some part of configuration here?

0

There are 0 best solutions below