springspring-bootspring-securityhttp-status-code-401unauthorized

Spring boot 401 Unauthorized on Post Request for authentication


i'm using spring boot as an api and i'm testing with postman , i tried to implement spring security authentication with roles using the following configuration :

public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception{
        httpSecurity.
                csrf(csrf->csrf.ignoringRequestMatchers("/Register"))
                .authorizeHttpRequests(
                (auth) -> {
                    auth.requestMatchers("/Register" , "/api/PostJob").permitAll();
                    auth.requestMatchers("/api/candidate/**").hasRole("candidate");
                    auth.requestMatchers("/api/Recruiters/**" ).hasRole("recruiter");
                    auth.requestMatchers("/api/job/**").hasRole("admin");
                    auth.anyRequest().authenticated();
                }

        ).formLogin(AbstractAuthenticationFilterConfigurer::permitAll).
                httpBasic(withDefaults());
         return httpSecurity.build();
    }

and i'm sending the authentication demand using this function to ("Register") route :

@PostMapping
    public ResponseEntity<Person> createPerson(@RequestBody Person person){
        System.out.println(person);
        person.password = passwordEncoder.encode(person.password);
        Person person1 = personDetailService.createPerson(person);
       return ResponseEntity.status(HttpStatus.CREATED).body(person1);
    }

when i try to get either the Register or the PostJob they work fine , but when i try to post i get the 401 code (Unauthorized) , i tried either disabling the csrf token or ignoring it its always the same result , i tried also to insert manually come credentials in the database and try to connect using them but i got a 500 code . for the logs this what i got :

2024-05-10T00:19:21.958+01:00 DEBUG 4295 --- [jobquest] [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : Securing POST /error
2024-05-10T00:19:21.958+01:00 DEBUG 4295 --- [jobquest] [nio-8080-exec-7] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
2024-05-10T00:19:21.958+01:00 DEBUG 4295 --- [jobquest] [nio-8080-exec-7] s.w.a.DelegatingAuthenticationEntryPoint : Trying to match using And [Not [RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expectedHeaderValue=XMLHttpRequest]], MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@706c2726, matchingMediaTypes=[application/xhtml+xml, image/*, text/html, text/plain], useEquals=false, ignoredMediaTypes=[*/*]]]
2024-05-10T00:19:21.958+01:00 DEBUG 4295 --- [jobquest] [nio-8080-exec-7] s.w.a.DelegatingAuthenticationEntryPoint : Trying to match using Or [RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expectedHeaderValue=XMLHttpRequest], And [Not [MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@706c2726, matchingMediaTypes=[text/html], useEquals=false, ignoredMediaTypes=[]]], MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@706c2726, matchingMediaTypes=[application/atom+xml, application/x-www-form-urlencoded, application/json, application/octet-stream, application/xml, multipart/form-data, text/xml], useEquals=false, ignoredMediaTypes=[*/*]]], MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@706c2726, matchingMediaTypes=[*/*], useEquals=true, ignoredMediaTypes=[]]]
2024-05-10T00:19:21.958+01:00 DEBUG 4295 --- [jobquest] [nio-8080-exec-7] s.w.a.DelegatingAuthenticationEntryPoint : Match found! Executing org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint@1ae2028d
2024-05-10T00:19:21.958+01:00 DEBUG 4295 --- [jobquest] [nio-8080-exec-7] s.w.a.DelegatingAuthenticationEntryPoint : Trying to match using RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expectedHeaderValue=XMLHttpRequest]
2024-05-10T00:19:21.958+01:00 DEBUG 4295 --- [jobquest] [nio-8080-exec-7] s.w.a.DelegatingAuthenticationEntryPoint : No match found. Using default entry point org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint@2b63fdbc

i didn't understand exactly what the error is about , i tried looking for different solutions but nothing really works


Solution

    1. I think the ** doesn't work anymore so try putting the whole path instead.

    2. Also if there is a token being generated try insearting it in postman under the Request URL bar you go to Authorization and then you choose your token type in the dropdown menu that appeared

      If you don't know how to access your token:

      • Right-click anywhere on the webpage and select Inspect or Inspect Element from the context menu. This will open the Developer Tools panel.
      • In the Developer Tools panel, find and click on the Application tab. If you don’t see it, you might need to click on the >> button to reveal more tabs.
      • In the Application tab, you’ll see a sidebar on the left with several sections like Storage, Cache, etc.
      • Look for the Cookies or Local Storage or Session Storage section in this sidebar (the location of the token can vary based on how the website is set up).
      • Click on the section where your token is stored. You should now see a table on the right that lists all the stored items.
      • Look for your token in this table. It might be under a name like auth_token, access_token, jwt, etc. (the exact name can vary).
    3. Also try adding this method in your Spring Security file

          @Override
      public void configure(WebSecurity web) {
          web.ignoring().antMatchers("/your/URL/here", "/your/second/URL/here", "/etc");
      }
      

      This code is a part of a Spring Security configuration. It’s overriding the configure(WebSecurity web) method to instruct Spring Security to ignore security checks for certain URL patterns. Don't forget to replace your URL