0
0
SpringbootDebug / FixBeginner · 4 min read

How to Fix 401 Unauthorized Error in Spring Applications

A 401 Unauthorized error in Spring usually means the user is not authenticated or the credentials are missing or wrong. Fix it by ensuring your 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.

java
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();
    }
}
Output
HTTP Status 401 – Unauthorized Full authentication is required to access this resource
🔧

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.

java
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);
    }
}
Output
Access granted when client sends correct username 'user' and password 'password' with HTTP Basic authentication
🛡️

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.

Key Takeaways

401 Unauthorized means missing or invalid authentication in Spring Security.
Configure authentication properly using SecurityFilterChain and UserDetailsService beans.
Ensure clients send correct credentials, like HTTP Basic auth headers.
Test security settings early to catch authentication issues.
Use clear authentication methods and document them for API users.