1

I want to make a rest API where some endpoints are protected by an authentication base on users roles. I also would like to use JWT token and to check roles of user. Furthermore, I have seen countless confusing things in internet that are either depreciating or not working in my case.

My goal with this question is to get a better understanding of how spring work to generate JWT, how to generate one if user is login and how to make endpoint inaccessible if you don't have right. And most importantly, how to do that with last and best security standards and best code quality for the last version of spring (3.0.1).

I have tried to use spring security module with SecurityConfig class that has @EnableWebSecurity and I have tried to define a simple filter chain, but It seems to return me 401 error even if I'm on authorized endpoint.

Here is my conf :

@EnableWebSecurity
@Configuration
public class SecurityConfig {
    @Autowired
    DataSource dataSource;

    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    public AuthenticationManager authenticationManager(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
        return auth.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.authorizeHttpRequests().requestMatchers("/api/auth/login").permitAll();
        http.authorizeHttpRequests().requestMatchers("/api/auth/register").permitAll();
        http.authorizeHttpRequests().anyRequest().authenticated();
        return http.build();
    }
}

As you can see I provide a bean that provide UserDetailsService that I think can be used to check if user as a correct password. So here is my Service implementation :


@Service
public class MyUserDetailsService implements UserDetailsService {
    private final UserAuthService userAuthService;
    public GroMedUserDetailsService(UserAuthService userAuthService){
        this.userAuthService = userAuthService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional<User> user = this.userAuthService.findUserByUsername(username);
        if(user.isEmpty()){
            throw  new UsernameNotFoundException("User not found");
        }
        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority(user.get().getGroMedRole().toString()));
        return new org.springframework.security.core.userdetails.User(user.get().getUsername(),user.get().getPassword(),authorities);
    }
}

So I know I don't have all of component needed for authentification. But I'm here to learn how to correctly create it and use it. So if you know some good tutorial or you have a complete awnser for me I will be please to read it.

MrSolarius
  • 599
  • 11
  • 28

0 Answers0