Haytam95
Haytam95

Reputation: 307

Spring security default configuration always throws 401

I'm creating a new Spring REST application with some basic services and entities.

I added Spring Security and without overriding any class, i just added to application.properties a user and password.

So far so good, i opened Postman to try out a endpoint and it always return 401 to my requests.

I tried in postman set the authorization via "Basic Auth" (is what header WWW-Authenticate asks), tried "Digest auth" using the "Realm" value from the header. But none of it works.


Here is what i have in my application.properties

spring.security.user.name=root
spring.security.user.password=root

This is my request

https://i.sstatic.net/8ezND.jpg

(Sorry i can't embbed the image because of my reputation)

And here is the endpoint

@PostMapping("saveUsuario")
public Usuario saveUsuario(Usuario usuario) {
        return usuarioRepository.save(usuario);
}

(If possible) i don't want to override any Spring Security class, just "use as it".

Thank you!

Upvotes: 2

Views: 2281

Answers (2)

Julio C Villalta III
Julio C Villalta III

Reputation: 134

Per https://docs.spring.io/spring-boot/docs/1.5.0.RELEASE/reference/htmlsingle/#boot-features-security

you should change your password with

security.user.password=root

instead of spring.security.user.password=root

similar security properties that are overridable are in the @ConfigurationProperties class: SecurityProperties.java

See https://github.com/spring-projects/spring-boot/blob/v1.5.0.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SecurityProperties.java

Upvotes: -1

Haytam95
Haytam95

Reputation: 307

So here is what i found.

Thanks to @jzheaux we discover that the problem was with the csrf configuration (Using POST request).

So i was forced to override the class WebSecurityConfigurerAdapter to disable it.

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
    }
}

But then, the endpoints could be called without authentication!

So, this is the final code:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.cors();
        http.authorizeRequests().anyRequest().fullyAuthenticated();
        http.httpBasic();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
    }
}
  • First disable the CSRF.
  • Then enable Cors.
  • I set that i want any request to be fully authenticated
  • The challenge type is HTTP basic
  • I disable the creation of cookies so it'll always ask for credentials.

So far so good, it's working!

Upvotes: 3

Related Questions