How to Fix 401 Unauthorized Error in Spring Applications
SecurityConfig properly configures authentication and that your client sends valid credentials with requests.Why This Happens
A 401 Unauthorized error happens when Spring Security blocks access because it does not recognize the user as logged in or authorized. This often occurs if authentication is not set up correctly or if the client does not send the required credentials.
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .httpBasic(); } }
The Fix
To fix the 401 error, make sure your Spring Security configuration allows authentication and that your client sends valid credentials. For example, enable httpBasic() or form login and configure an in-memory user or user details service with a username and password.
import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.provisioning.InMemoryUserDetailsManager; @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth.anyRequest().authenticated()) .httpBasic(); return http.build(); } @Bean public UserDetailsService users() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }
Prevention
To avoid 401 errors in the future, always configure authentication properly in Spring Security and test your endpoints with valid credentials. Use secure password storage and consider token-based authentication for APIs. Also, document authentication requirements clearly for API clients.
Related Errors
Other common errors include:
- 403 Forbidden: User is authenticated but lacks permission.
- 400 Bad Request: Malformed authentication headers.
- 404 Not Found: Endpoint does not exist or is blocked.
Fix these by checking authorization rules, request format, and endpoint mappings.