Spring returning status 401 on all exceptions - spring

My SpringBoot app is returning 401 unauthorized on all failed requests.
SecurityConfig:
//JWT
http.cors().and().csrf().disable()
.authorizeRequests()
.antMatchers("/admin").hasRole("ADMIN")
.antMatchers("/usr/adm/**").hasRole("ADMIN")
.antMatchers("/adminconfig").hasRole("ADMIN")
.antMatchers("/tech").hasRole("ADMIN")
.antMatchers("/login").permitAll()
.antMatchers("/refresh_token").permitAll()
.antMatchers("/**").hasAnyRole("ADMIN", "USER")
.and()
.exceptionHandling()
.authenticationEntryPoint(jwtAuthenticationEntryPoint)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtRequestFilter,
UsernamePasswordAuthenticationFilter.class);
Anyone has any clues?

That is normal if authentication fails.
It comes 100% from
jwtAuthenticationEntryPoint
where some AuthenticationException is thrown during Authentication and inside this class is translated to 401 code.
Analyse jwtAuthenticationEntryPoint or post more details to see why authentication fails

Related

antMatchers(HttpMethod.GET, "path").permitAll() is still 401 unauthorized

I was searching a lot to find solution of my problem but nothing helps.
I am tryng to set up my Spring Security as:
#Override
public void configure(HttpSecurity http) throws Exception {
http
.httpBasic()
.and()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/shapes").hasAnyAuthority("USER")
.antMatchers(HttpMethod.PUT, "/shapes").hasAnyAuthority("USER")
.antMatchers(HttpMethod.GET, "/shapes").permitAll()
.antMatchers("/users", "/shapes/history").permitAll()
.anyRequest().authenticated()
.and()
.cors()
.and()
.csrf()
.disable();
}
and now:
every request on endpoint /users is open, is not secured
#PostMapping("/shapes") is secured and returns 401 unauthorized
#GetMapping is secured too - it returns 401 error if I not add username and password <- there is problem of that question
/shapes/history is secured too
so the problem has to be here somewhere:
.antMatchers(HttpMethod.POST, "/shapes").hasAnyAuthority("USER")
.antMatchers(HttpMethod.PUT, "/shapes").hasAnyAuthority("USER")
.antMatchers(HttpMethod.GET, "/shapes").permitAll()
I won't to change endpoints, I would like to have #GetMapping and #PostMapping on the /shapes.

Authentication with spring and web flux

I have a question concerning spring and web flux.
I have a spring project with spring security and MVC as dependencies.
This application accepts requests and check authentication using the session cookie.
For all the requests starting with "/api/" a failed authentication results in a 401 response, so that can be intercepted by the frontend as such.
For all the requests different from "/api/**" a failed authentication results in the server returning a login page so that the user can login.
This is the SecuritConfig class:
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.formLogin()
.and()
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
.exceptionHandling()
.defaultAuthenticationEntryPointFor(new
HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED),
new AntPathRequestMatcher("/api/**"))
.and()
.cors();
}
}
Now, I am trying to achieve the same thing using web flux. With web flux the SecurityConfig is different, I can setup almost all the configs that I have in the old class but there is no equivalent for:
defaultAuthenticationEntryPointFor(new
HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED),
new AntPathRequestMatcher("/api/**"))
My new security config look like:
#Configuration
#EnableWebFluxSecurity
public class SecurityConfig {
#Bean
public SecurityWebFilterChain filterChain(ServerHttpSecurity http) {
return http
.authorizeExchange()
.pathMatchers("/login/**")
.permitAll()
.anyExchange()
.authenticated()
.and()
.formLogin()
.and()
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(new
HttpStatusServerEntryPoint(HttpStatus.UNAUTHORIZED))
.and()
.build();
}
}
But in this case I only get 401 for all the requests that fail authentication.
Does anybody know how to achieve the same behavior with web flux?
Thank you

Spring security - Disable CSRF and Authentication for specific URL (Java Conf)

I know this question is old but it is not working in my case.
I have a webapp using spring security authentication and CSRF enabled.
Now I want to expose couple of URL to expose to other application without authentication.
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.antMatchers("/rest/book").permitAll()
.antMatchers("/rest/check").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login")
.successHandler(customizeAuthenticationSuccessHandler)
//.defaultSuccessUrl("/")
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/login?logout")
.permitAll();
}
I have other urls with "/rest/" which are secure. I tried csrfMatcher and with that I am able to expose "/rest/book" but then other urls are giving unexpected behavior.
Unexpected behavior like, my default login page is /login when no authentication but it stopped.

two authentication mechanism on a spring boot application (Basic & JWT)

I have a spring boot app, I have just finished implementing a stateless authentication/authorization module based on jwt.
This is how I configured my security module:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint)
.and()
.csrf()
.disable()
.headers()
.frameOptions()
.disable()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/authenticate").permitAll()
.antMatchers("/api/**").authenticated()
.and()
.apply(securityConfigurerAdapter());
}
So basically if I want to access the url /api/jobs I get a 401 error unless I send the bearer token which I get after a succesfull authentication on /api/authenticate.
What I need to know is if it's possible to access /api/jobs without supplying the bearer token, using a basic http authentication with a login and passowrd
Yes, it's possible, just make sure you have:
http.httpBasic();
in your configuration. That builder also have other methods to configure the details for basic auth.

Match everything but some specific path with Java configuration - antMatchers

Base on this Answer, I'm trying to secure everything but the login page in my spring app.
So I'm using this Java configuration files for OAuth2
The extends for the ResourceServerConfigurerAdapter:
#Override
public void configure(final HttpSecurity http) throws Exception {
http
.requestMatchers()
.antMatchers("/**")
.and()
.authorizeRequests()
.anyRequest()
.authenticated()
.antMatchers("/login")
.permitAll()
The extends for OAuth2SsoConfigurerAdapter {
#Override
public void match(RequestMatchers matchers) {
matchers.antMatchers("/login");
}
#Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest()
.authenticated()
}
So, what I looking for is to have a http 401 for every request but for /login.
If a login request is perform the #EnableOAuth2Sso annotation would be used to redirect it to the OAuth2 server.
Update 1
After changing the order of the filter ResourceServerConfigurerAdapter, the /login request is not found.
http
.requestMatchers()
.antMatchers("/**")
.and()
.authorizeRequests()
.antMatchers("/login")
.permitAll()
.anyRequest()
.authenticated()
This request would be Unauthorized because any token is provided
~/ http 401 Unauthorized (good)
~/resource http 401 Unauthorized (good)
But the login page is not found:
~/login http 404 Not Found (bad)
The correct functionality should be a http 302 redirection to the OAuth2 server when the ~/login is hit.

Resources