#Spring Security :(

1 messages · Page 1 of 1 (latest)

white leaf
#

I have spent some hours trying to debug why this 401 is not going away for such a simple project... I give up.

wraith pollenBOT
#

<@&1004656351647117403> please have a look, thanks.

white leaf
#
@EnableWebSecurity
@AllArgsConstructor
public class SecurityConfig {

    private final JpaUserDetailService userDetailService;

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

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .csrf(csrf -> csrf.disable())
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers(HttpMethod.GET, "/demo").permitAll()
                        .requestMatchers(HttpMethod.POST, "/register").permitAll()
                        .anyRequest().hasRole("ADMIN")
                )
                .httpBasic(withDefaults())
                .sessionManagement(session ->
                        session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                );
        return http.build();
    }

    @Bean
    public AuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(userDetailService);
        return provider;
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }
}```
#
@AllArgsConstructor
public class JpaUserDetailService implements UserDetailsService {
    private final UserRepository userRepository;

    public UserDetails loadUserByUsername(String email){
        var u = userRepository.findByEmail(email);
        return u.map(SecurityUser::new)
                .orElseThrow(()-> new UsernameNotFoundException("User with email "+email+" not found"));
    }
}```
#
@Getter
@Setter
public class RegisterUserRequest {
    @NotBlank
    private String name;

    @Email(message = "Invalid email address")
    @NotBlank(message = "Email is required")
    private String email;

    @Pattern(regexp = "^[0-9]{10}$", message = "Phone must be exactly 10 digits")
    private String phoneNumber;

    @NotBlank(message = "Password is required")
    private String password;

    private String preferredLanguage;
}```
#
@RestController
@AllArgsConstructor
public class LoginController {

    private final UserService userService;

    @PostMapping("/register")
    public String register(@RequestBody RegisterUserRequest registerUserRequest) {
        User user = new User();
        user.setName(registerUserRequest.getName());
        user.setEmail(registerUserRequest.getEmail());
        user.setPassword(registerUserRequest.getPhoneNumber());
        user.setPassword(registerUserRequest.getPassword());
        userService.createUser(user);
        return "User registered successfully";
    }
}
#
@AllArgsConstructor
public class SecurityUser implements UserDetails {

    private final User user;

    @Override
    public String getUsername() {
        return user.getName();
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return user.getAuthorities()
                .stream()
                .map(SecurityAuthority::new)
                .collect(Collectors.toList());
    }
}
@AllArgsConstructor
public class SecurityAuthority implements GrantedAuthority {

    private final Authority authority;

    @Override
    public String getAuthority() {
        return authority.getName();
    }
}
#

These are some snippets, its supposed to be a very small prototype for a bigger project.

#
  "name": "Example",
  "email": "[email protected]",
  "phoneNumber": "1234567890",
  "password": "StrongPassword123"
}```

The test json payload
#

@lime blaze save me 🙏

faint cairn
white leaf
#

but .requestMatchers(HttpMethod.GET, "/demo").permitAll() .requestMatchers(HttpMethod.POST, "/register").permitAll() has permit all , so not being able to send it to register dosent make sense

faint cairn
#

Try

#

Let me know what happens after you try my suggestion

white leaf
#

yep same

#

this is some very minor b.s thats causing it i just dont know what

faint cairn
#

Yeah, I don't use spring security that much. I don't think I'm going to be able to help more with this

#

I'll take a second look when i get home

white leaf
#

ill dive into it again too m just tired atp, the new spring update changed so much stuff its tiring to go through all of it for this prototype bruh

broken sapphire
#

@Bean Try putting this in your application.yaml:

logging:
level:
org.springframework.security: DEBUG
org.springframework.security.web.FilterChainProxy: TRACE

#

If you're using .properties, you'd need:

logging.level.org.springframework.security=DEBUG
logging.level.org.springframework.security.web.FilterChainProxy=TRACE

It's obvious that a Filter is throwing the error, it could be the AuthenticationFilter, ExceptionTranslationFilter or a custom one(If you have one), let's see the filter throwing the error

little parrot
broken sapphire
little parrot
#

shoudlnt those credentials match ?

white leaf
#

nope

#

they can be anything

#

@broken sapphire are u available rn

#

i can get on and try to send u the logs

broken sapphire
white leaf
#

2025-09-05T22:34:03.739+05:30 DEBUG 616 --- [AquaSentinel] [nio-8080-exec-3] o.s.s.w.s.HttpSessionRequestCache : Saved request http://localhost:8080/error?continue to session
2025-09-05T22:34:03.739+05:30 DEBUG 616 --- [AquaSentinel] [nio-8080-exec-3] s.w.a.DelegatingAuthenticationEntryPoint : Trying to match using RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expectedHeaderValue=XMLHttpRequest]
2025-09-05T22:34:03.739+05:30 DEBUG 616 --- [AquaSentinel] [nio-8080-exec-3] s.w.a.DelegatingAuthenticationEntryPoint : No match found. Using default entry point org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint@4a395e98

#

its delegating to the right filter

#

but..

#

/register has permit all

#
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .csrf(csrf -> csrf.disable())
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers(HttpMethod.GET, "/demo").permitAll()
                        .requestMatchers(HttpMethod.POST, "/register").permitAll()
                );
        return http.httpBasic()
                .and().build();
    }
#

i tried it by having everything inside httpBasic, and outside, idk why it aint fixxing

broken sapphire
#

You don't need to send the whole thing, just check if you'd see any call referring to the route you called as 401?

white leaf
#

hmm i dont see a specific 401

#

2025-09-05T22:35:09.486+05:30 TRACE 616 --- [AquaSentinel] [nio-8080-exec-5] estMatcherDelegatingAuthorizationManager : Denying request since did not find matching RequestMatcher

faint cairn
#

@white leaf ok

#

Hear me out

white leaf
#

yes

faint cairn
#

I've had a similar issue with postman

white leaf
#

u want me to do with curl?

faint cairn
#

Go to your postman headers and show me what they say

white leaf
#

pl

#

FU

#

my custom header from last key is still there

#

nvm that wont throw any errors

#

just extra info

broken sapphire
#

@still cradle Try annotating the Login controller with @RequestMapping("/")

white leaf
#

wrong guy

#

😭

#

waittt

#

i think its a nullpointer in my service

#

hold up.

#

401 will happen by spring on its own if an internal error is thrown right>

#

m in debug and nothing is reaching in the place where m assigning values to a set.

faint cairn
white leaf
#

wait i think i forgot to initialize a hashset and am storing something in it

white leaf
# broken sapphire This didn't work?

I didnt try because i was in debug and found something bigger, but I dont think this will fix it, never had an issue with "/" before not being there

#

give me a minute

#

ill try your thing too

broken sapphire
#

So Spring does not know how to reach it

white leaf
#

the default mapping is "/"

#

I am pretty sure

#

you dont need to explicitly state it

broken sapphire
#

It's the annotation I'm talking about not really the '/'

white leaf
broken sapphire
white leaf
white leaf
#

💀

broken sapphire
white leaf
#

but thank you so much

#

@faint cairn I am very stupid.

faint cairn
#

@white leaf so it was defualting to 401 if an error was thrown

white leaf
#

yep

#

i forgot that happens

faint cairn
#

That's very stupid default behaviour

faint cairn
broken sapphire
white leaf
#

its for security purposes, to not expose internal errors unless wanting specifically that

#

because idh my own handelling in place rn

#

as i stated, its a prototype for my college hackathon, and well, just gotta show bare minimum working

faint cairn
white leaf
faint cairn
#

But oh well

white leaf
#

I think i read somewhere that spring security does all that, because all default settings are complete security , and then we customize the limited access.

#

well, I am glad that its working now, i was down to call it quits for today before yall decided to bring me back to work

#

so thanks very much :)

#

SOLVED