#Spring Security :(
1 messages · Page 1 of 1 (latest)
<@&1004656351647117403> please have a look, thanks.
@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 🙏
Try removing anyRequest.hasRole(admin)
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
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
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
@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
might be an oversight, but this does not match
https://i.imgur.com/SdDhqwU.png
It's a registration, so I don't think it matters
shoudlnt those credentials match ?
nope
they can be anything
@broken sapphire are u available rn
i can get on and try to send u the logs
Yeah, you can
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
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?
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
yes
I've had a similar issue with postman
u want me to do with curl?
Go to your postman headers and show me what they say
pl
FU
my custom header from last key is still there
nvm that wont throw any errors
just extra info
@still cradle Try annotating the Login controller with @RequestMapping("/")
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.
Yeah, not the same issue i had so nvm
This didn't work?
wait i think i forgot to initialize a hashset and am storing something in it
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
Yeah, you have LoginController with @RestController, but there is not @RequestMapping
So Spring does not know how to reach it
Yeah, the default is /, but you need the annotation
It's the annotation I'm talking about not really the '/'
HOLY
Yeah, so that's it
it isnt mandatory anymore
Alright
@white leaf so it was defualting to 401 if an error was thrown
That's very stupid default behaviour
😂
Yeah, no problem
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
It should throw Internal Server Error, it doesn't need to include the error imo
yeah that would be more helpfull instead of messing my head around with 401
But oh well
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