2
\$\begingroup\$

I am new to spring boot and wanted to make a simple application with JWT authentication. There is one problem with the response having 401 status when it should have 403 but otherwise everything seems to work as expected.

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
@EnableMethodSecurity
public class SecurityConfiguration {
    private final JwtAuthFilter jwtFilter;
    private final UserDao userDao;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests(
                        auth -> auth.requestMatchers("/**/auth/**").permitAll()
                                .anyRequest().authenticated())
                .httpBasic(Customizer.withDefaults())
                .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
                .authenticationProvider(authenticationProvider())
                .sessionManagement(conf -> conf.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
        return http.build();
    }

    @Bean
    public AuthenticationProvider authenticationProvider() {
        final DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userDetailsService());
        authenticationProvider.setPasswordEncoder(passwordEncoder());
        return authenticationProvider;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        return new UserDetailsService() {
            @Override
            public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
                return userDao.findUserByEmail(email);
            }
        };
    }
}

Any tips on how I can improve this or what mistakes I have made not noticed?

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Do you have control over the status code, or are there parameters/configuration options that can affect it? Otherwise is it controlled by an external system? Are you okay with the 401 status or asking how to fix it? \$\endgroup\$ Commented Aug 17, 2023 at 16:35
  • \$\begingroup\$ I am not really ok with it but it doesn't bother me much now (would be nice to fix though). I have no external error handling or other mean that effects the status codes in response. I use @PreAuthorize on endpoints to specify the necessary authority \$\endgroup\$
    – Newbee
    Commented Aug 17, 2023 at 20:35

1 Answer 1

2
\$\begingroup\$

Suggestion of improvements ...

  1. instead of define the UserDetailsService as this @Bean and anonymous class
@Bean
    public UserDetailsService userDetailsService() {
        return new UserDetailsService() {
            @Override
            public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
                return userDao.findUserByEmail(email);
            }
        };
    }

I suggest define UserDetailsService as this

@Service
public class UserDataServiceImpl implements UserDetailsService {
    private final UserDao userDao;

    @Autowired
    public UserDataServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public UserDetails loadUserByUsername(String email) {
         try{
        return userDao.findUserByEmail(email);
      }catch(){
           log.debug("Can't find user by the email {}, email);
           throw new UsernameNotFoundException("some message");
      }
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ Thank you, will do that. Btw I don't think you need the @Autowired annotation above constrictor in newer versions of spring boot \$\endgroup\$
    – Newbee
    Commented Aug 18, 2023 at 6:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.