title: Registration Issue with Spring Security 401 with Postman
body: <p>I had problem in spring security when I try to register a new user and tested it in the postman it keep giving me a 401 unauthorized response.</p>
  <p>I checked all the filters, control, service repository and everything I already checked all the issues here and even searched a lot about it in google but no answer I hope some one had the answer.</p>
  <p>this is the code below:</p>
  <p>this is the Security Configuration:</p>
  <pre><code>package app.gym.v1.Utility.Config;
  
  import app.gym.v1.Utility.Filter.JwtAccessDeniedHandler;
  import app.gym.v1.Utility.Filter.JwtAuthenticationEntryPoint;
  import app.gym.v1.Utility.Filter.JwtAuthorizationFilter;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.beans.factory.annotation.Qualifier;
  import org.springframework.context.annotation.Bean;
  import org.springframework.security.authentication.AuthenticationManager;
  import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  import org.springframework.security.core.userdetails.UserDetailsService;
  import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
  
  import static app.gym.v1.Utility.Constant.SecurityConstant.*;
  import static org.springframework.security.config.http.SessionCreationPolicy.*;
  
  public class SecurityConfig extends WebSecurityConfigurerAdapter {
      private JwtAuthorizationFilter jwtAuthorizationFilter;
      private JwtAccessDeniedHandler jwtAccessDeniedHandler;
      private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
      private UserDetailsService userDetailsService;
      private BCryptPasswordEncoder bCryptPasswordEncoder;
  
      @Autowired
      public SecurityConfig(
              JwtAuthorizationFilter jwtAuthorizationFilter,
              JwtAccessDeniedHandler jwtAccessDeniedHandler,
              JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint,
              @Qualifier(&quot;userDetailsService&quot;)UserDetailsService userDetailsService,
              BCryptPasswordEncoder bCryptPasswordEncoder) {
          this.jwtAuthorizationFilter = jwtAuthorizationFilter;
          this.jwtAccessDeniedHandler = jwtAccessDeniedHandler;
          this.jwtAuthenticationEntryPoint = jwtAuthenticationEntryPoint;
          this.userDetailsService = userDetailsService;
          this.bCryptPasswordEncoder = bCryptPasswordEncoder;
      }
  
      @Override
      protected void configure(AuthenticationManagerBuilder auth) throws Exception {
          auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
      }
  
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http.csrf().disable().cors().and()
                  .sessionManagement().sessionCreationPolicy(STATELESS)
                  .and().authorizeRequests().antMatchers(PUBLIC_URLS).permitAll()
                  .anyRequest().authenticated()
                  .and()
                  .exceptionHandling().accessDeniedHandler(jwtAccessDeniedHandler)
                  .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                  .and()
                  .addFilterBefore(jwtAuthorizationFilter, UsernamePasswordAuthenticationFilter.class);
      }
  
      @Bean
      @Override
      public AuthenticationManager authenticationManager() throws Exception {
          return super.authenticationManagerBean();
      }
  }
  </code></pre>
  <p>this is the Resource code:</p>
  <pre><code>package app.gym.v1.Resource;
  
  import app.gym.v1.Model.User;
  import app.gym.v1.Service.UserService;
  import app.gym.v1.Utility.Exception.Domain.*;
  import app.gym.v1.Utility.Exception.ExceptionHandling;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.http.ResponseEntity;
  import org.springframework.web.bind.annotation.PostMapping;
  import org.springframework.web.bind.annotation.RequestBody;
  import org.springframework.web.bind.annotation.RequestMapping;
  import org.springframework.web.bind.annotation.RestController;
  
  import java.io.IOException;
  
  import static org.springframework.http.HttpStatus.OK;
  
  @RestController
  @RequestMapping(path = {&quot;/&quot;,&quot;/user&quot;})
  public class UserControl extends ExceptionHandling {
      private UserService userService;
  
      @Autowired
      public UserControl(UserService userService) {
          this.userService = userService;
      }
  
      @PostMapping(&quot;/register&quot;)
      public ResponseEntity&lt;User&gt; register(@RequestBody User user) throws UserNotFoundException, UsernameExistException, EmailExistException, IOException {
          User newUser = userService.register(user.getUsername(), user.getEmail(), user.getPassword(), user.getRole());
          return new ResponseEntity&lt;&gt;(newUser,  OK);
      }
  }
  
  </code></pre>
  <p>this is the user implementation service:</p>
  <pre><code>package app.gym.v1.Utility.Impl;
  
  import app.gym.v1.Model.User;
  import app.gym.v1.Model.UserPrincipal;
  import app.gym.v1.Repo.UserRepo;
  import app.gym.v1.Service.UserService;
  import app.gym.v1.Utility.Exception.Domain.*;
  import org.apache.commons.lang3.RandomStringUtils;
  import org.slf4j.Logger;
  import org.slf4j.LoggerFactory;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.beans.factory.annotation.Qualifier;
  import org.springframework.security.core.userdetails.UserDetails;
  import org.springframework.security.core.userdetails.UserDetailsService;
  import org.springframework.security.core.userdetails.UsernameNotFoundException;
  import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  import org.springframework.stereotype.Service;
  
  import javax.mail.MessagingException;
  import javax.transaction.Transactional;
  import java.io.IOException;
  import java.util.Date;
  import java.util.List;
  
  import static app.gym.v1.Utility.Constant.UserImplConstant.*;
  import static app.gym.v1.Utility.Enums.Role.*;
  import static org.apache.commons.lang3.StringUtils.*;
  
  @Service
  @Transactional
  @Qualifier(&quot;UserDetailsService&quot;)
  public class UserServiceImpl implements UserService, UserDetailsService {
      private Logger LOGGER = LoggerFactory.getLogger(getClass());
      private UserRepo userRepo;
      private BCryptPasswordEncoder passwordEncoder;
  
      @Autowired
      public UserServiceImpl(UserRepo userRepo, BCryptPasswordEncoder passwordEncoder) {
          this.userRepo = userRepo;
          this.passwordEncoder = passwordEncoder;
      }
  
      @Override
      public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
          User user = userRepo.findUserByUsername(username);
          if (user == null) {
              LOGGER.error(&quot;User with this phone number does not exist: &quot; + username);
              throw new UsernameNotFoundException(&quot;User with this phone number does not exist: &quot; + username);
          }else {
              user.setLastLoginDateDisplay(user.getLastLoginDate());
              user.setLastLoginDate(new Date());
              userRepo.save(user);
              UserPrincipal userPrincipal = new UserPrincipal(user);
              LOGGER.info(&quot;Retrieving user with this phone number&quot; + username);
              return userPrincipal;
          }
      }
  
      @Override
      public User register(String username, String email, String password, String role) throws UserNotFoundException, UsernameExistException, EmailExistException {
          validateNewUsernameAndEmail(EMPTY, username, email);
          User user = new User();
          user.setUserId(generateUserId());
          user.setUsername(username);
          user.setEmail(email);
          user.setPassword(encodePassword(password));
          user.setRole(USER.name());
          user.setAuthorities(USER.getAuthorities());
          user.setJoinDate(new Date());
          user.setActive(true);
          user.setNotLocked(true);
          userRepo.save(user);
          return user;
      }
  
      private String encodePassword(String password) {
          return passwordEncoder.encode(password);
      }
  
      private String generateUserId() {
          return RandomStringUtils.randomNumeric(20);
      }
  
  
      private String generatePassword() {
          return RandomStringUtils.randomAlphanumeric(20);
      }
  
      private User validateNewUsernameAndEmail(String currentUsername, String newUsername, String newEmail) throws UserNotFoundException, UsernameExistException, EmailExistException {
          User userByNewUsername = findUserByUsername(newUsername);
          User userByNewEmail = findUserByEmail(newEmail);
          if(isNotBlank(currentUsername)) {
              User currentUser = findUserByUsername(currentUsername);
              if(currentUser == null) {
                  throw new UserNotFoundException(NO_USER_FOUND_BY_USERNAME + currentUsername);
              }
              if(userByNewUsername != null &amp;&amp; !currentUser.getId().equals(userByNewUsername.getId())) {
                  throw new UsernameExistException(USERNAME_ALREADY_EXISTS);
              }
              if(userByNewEmail != null &amp;&amp; !currentUser.getId().equals(userByNewEmail.getId())) {
                  throw new EmailExistException(EMAIL_ALREADY_EXISTS);
              }
              return currentUser;
          } else {
              if(userByNewUsername != null) {
                  throw new UsernameExistException(USERNAME_ALREADY_EXISTS);
              }
              if(userByNewEmail != null) {
                  throw new EmailExistException(EMAIL_ALREADY_EXISTS);
              }
              return null;
          }
      }
  }
  
  </code></pre>
  <p>the problem is with the registration my route is that(localhost:8080/user/register) or (localhost:8080/register).</p>
  <p>I put a constant for them to make a public urls.</p>