Reputation: 73
I have such a web config in Spring Boot App:
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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;
import org.springframework.security.config.http.SessionCreationPolicy;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests().anyRequest().permitAll()
.and()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.httpBasic();
}
}
when trying to reach one of the urls (localhost:8080/test), I get Unauthorized. What am I doing wrong?
Upvotes: 2
Views: 1944
Reputation: 118
In my case, I need to remove the context path from the properties file. I removed this:
server.servlet.context-path=/api
after I removed that value, then everything went right. But, I still don't know why it won't work with the context-path.
Upvotes: 0
Reputation: 422
If you are getting an Unauthorize (401) it means that the authentication failed, regardless of whether you have access to access the resource or not. You are using basic auth, and the spring flow has two parts, authentication and authorization, first it authenticates, to know if a user is valid and then it is seen if they have authorization to access the resource. In this case the error is given because it does not have authentication, better known as 401, in case you had authentication and no authorization, you would receive a 403 forbiden
Upvotes: 0
Reputation: 2458
My shot is that your WebConfig
is not placed in the right package.
If your @SpringBootApplication
annotated class is in com.example.demo
then your WebConfig
class should be placed under the com.example.demo
package (or other sub-package, e.g: com.example.demo.config
).
package com.example.demo.config; // <-- move it to the (not-default) package
// skipped imports
// ...
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// config same as in the question's snippet
// ...
}
}
Upvotes: 2
Reputation: 379
My shot it's related to " .httpBasic();", looks like you're expecting a basic authentication when you set this in your properties.
Upvotes: 0