How to handle failure login with out form login() in spring boot

Viewed 22

this is in my Auth controller

@PostMapping("/signin")
public Map<?,?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest,
                                 HttpServletRequest request) {
    Map<String, String> test = new HashMap<>();
    Authentication authentication = authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), 
     loginRequest.getPassword()));

    if(authentication.isAuthenticated()) {

  SecurityContextHolder.getContext().setAuthentication(authentication);      

(String)session.getAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME );

        // userRepository.findByUsername()
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        // Boolean checkOUt = userRepository.existsByUsername(userDetails.getUsername());

        this.session = request.getSession(false);
        String sessionId = null;
        if (this.session == null) {
            // this.session = request.getSession(true);

            //store user in session
            JSONObject userDetailsJSON = SessionController.prepare(userDetails);
            //create ONE session
            this.session = request.getSession(true);

            //store user in session
            SessionController.logUser(userDetailsJSON, this.session);

            List<String> roles = userDetails.getAuthorities().stream()
                    .map(item -> item.getAuthority())
                    .collect(Collectors.toList());
            sessionId = this.session.getId();
        } else {
            sessionId = this.session.getId();
            //System.out.println(userDetails.getEmail());
            test.put("ID", String.valueOf(userDetails.getId()));
            test.put("SessionID", sessionId);
        }
    }else{
        test.put("SessionID", "sessionId");

    }

    return test;

}

In configuration, new version of spring security

 @Bean
  public SecurityFilterChain SessionfilterChain(HttpSecurity http) throws Exception{
    http.cors().and().csrf().disable()
    .sessionManagement(session -> session
               .maximumSessions(1))
           
        
      //.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
     // .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
      .authorizeRequests()
      .antMatchers("/").permitAll()
              .antMatchers("/session/api/auth/**").permitAll()
       return http.build();
  }

}

If I pass the valid credential, able to get valid response, in case of invalid credentials, instead of throwing Badcredentails its throwing forbidden state { "timestamp": "2022-09-18T11:14:19.635+00:00", "status": 403, "error": "Forbidden", "path": "/session/api/auth/signin" }

Actually I am new to Springboot, could someone guide where actually going wrong and how to handle this. Any reference link to learn spring security

0 Answers
Related