This my spring security code , can some please help me to find the mistake where the endpoints with permitall should work without username and password?
*
*
I am getting “status”: 401, if I am not giving usernam and passowrd
this is code I am attaching:
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(securedEnabled = true, jsr250Enabled = true)
public class SpringSecurity {
@Autowired
@Lazy
private UserDetailServiceImpl userDetailsService;
@Bean
public AuthenticationManager customAuthenticationManager(HttpSecurity http) throws Exception {
System.out.println("coming to here ******************1");
AuthenticationManagerBuilder authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class);
authenticationManagerBuilder.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
return authenticationManagerBuilder.build();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
System.out.println("coming to here ******************2");
// if we will not disable then put , post and delete will not work
http.csrf(customizer -> customizer.disable());
http.httpBasic(Customizer.withDefaults());
http.sessionManagement(session ->session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
http.authorizeHttpRequests(request -> request
.dispatcherTypeMatchers(FORWARD, ERROR).permitAll()
.requestMatchers("/public").permitAll()
.requestMatchers("/journal/**").authenticated()
.anyRequest().authenticated());
return http.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
@Service
public class UserDetailServiceImpl implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
System.out.println("coming to here ******************5");
User user = userRepository.findByUserName(username);
if (user != null) {
UserDetails userDetails = org.springframework.security.core.userdetails.User.builder()
.username(user.getUserName())
.password(user.getPassword())
.roles(user.getRoles().toArray(new String[0]))
.build();
return userDetails;
}
throw new UsernameNotFoundException("User not found with username"+ username);
}
}
I am getting “status”: 401, if I am not giving usernam and passowrd
New contributor
Shubham Surana is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.