405 Method Not Allowed for POST - spring

I have a very simple spring boot application, which is secured by the following code:
http.authorizeRequests()
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
.and()
.formLogin().loginPage("/login").failureUrl("/login?error")
.usernameParameter("username").passwordParameter("password")
.and()
.logout().logoutSuccessUrl("/login?logout")
.and()
.exceptionHandling().accessDeniedPage("/403");
the idea is to secure "admin" portion. It exposes a REST API.
The problem is all the POSTS returns
405 Method Not Allowed
If I remove the security starter from the application, it works. This makes me believe that the security configuration is the problem. But I cannot find out how.

This should be easy.
POSTs and PUT requests would not be allowed if CSRF is enabled,and spring boot enables those by default.
Just add this to your configuration code :
.csrf().disable()
that is :
http.
.csrf().disable().
authorizeRequests()
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
.and()
.formLogin().loginPage("/login").failureUrl("/login?error")
.usernameParameter("username").passwordParameter("password")
.and()
.logout().logoutSuccessUrl("/login?logout")
.and()
.exceptionHandling().accessDeniedPage("/403");
Refer docs ,if you need to enable CSRF :
http://docs.spring.io/spring-security/site/docs/4.0.x/reference/htmlsingle/#csrf-configure

This can also happen if using Spring Security SAML extension and your SAMLUserDetailsService returns a UsernameNotFoundException. Seems pretty counter-intuitive, but that's what it does by default (in my experience).

Related

Spring Security custom authentication provider's authenticate() method is not working

I followed the article Using Custom Authentication Provider Spring Security adding a custom authentication provider in Spring Security.
I found that if I POST to /login, it is redirected to /login.
My custom Authentication Provider's authenticate() is not called.
Even if I use Spring Security's TestingAuthenticationProvider, POST to /login still get redirected to /login.
Is there some thing wrong with my WebSecurityConfigure? This is my configure.
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/webjars/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
I use Spring Boot. Do I need to modify the application.properties file? Is there any working sample project on using custom authentication provider?
Have you tried using
http.authorizeRequests()
.antMatchers("/", "/webjars/**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
in your WebSecurityConfigure?
You will get a generated login-window that is using your CustomAuthenticationProvider as soon as you are trying to call a page you have not included in
.antMatchers("/", "/webjars/**").permitAll().

Spring Boot Security: How to run authentication filter before CSRF in Spring Boot?

I am always getting unauthorize on Login.
On Login i need to authenticate user as well as generate CSRF token based on JWT token generated from user credentials.
I have CsrfCookieGeneratorFilter but i need to pass JWT generated after sucessfull authentication. My current code always execute CsrfFilterfirst and after that run authentication thing.
So Authentication First and then CsrfCookieGeneraterFilter.
Could anyone guide how to achieve using following builder (I am quite new to this Spring security thing implementation)
Following is code i am trying:
httpSecurity
.authorizeRequests().antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.csrf()
.requireCsrfProtectionMatcher(csrfRequestMatcher)
.csrfTokenRepository(customCsrfTokenRepository)
.and()
.cors()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.exceptionHandling()
.authenticationEntryPoint(this.jwtAuthenticationEntryPoint);
httpSecurity.addFilterAt(new CsrfCookieGeneratorFilter(customCsrfTokenRepository), CsrfFilter.class);
httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);

Should I disable CORS in spring backend? Unathorized request is blocked

I'm working on project with spring boot and Vue, I need to protect my endpoints. The user will have specific role, admin role or typical user role. When I search for tutorials how to configure JWT and spring security I'm getting articles with disabled cors by cors().disable() only . And that's my question.. May I send request from my front Vue app via axios if cors in spring backend is disabled? Is it right approach to disable it? A lot of my requests from api were blocked by cors so I enabled it but I didn't implement user roles and it made me confused what to do now because I have to do it... Another problem is when I implemented httpSecurity.csrf().disable().authorizeRequests().antMatchers("/authenticate", "/register","/login").permitAll(). and tried to call /authenticate from another device in same network then spring blocked it but it shouldn't be blocked.. On the top of controller I have #CrossOrigin(origins="*", maxAge=3600) and #RestController so I don't know why my request is blocked.
Help me please if You have some ideas.
Best regards!
Set this in top of every controller
#CrossOrigin(origins = "*")
#RestController
And set the code in SecuriyConfig as follows. It worked for me.
httpSecurity.cors()
.and()
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(jwtAuthenticationEntryPoint)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/",
"/favicon.ico",
"/**/*.png",
"/**/*.ttf",
"/**/*.woff",
"/**/*.woff2",
"/**/*.gif",
"/**/*.svg",
"/**/*.jpg",
"/**/*.jpeg",
"/**/*.html",
"/**/*.css",
"/**/*.js")
.permitAll()
.antMatchers("/authenticate", "/register","/login")
.permitAll()
.antMatchers(HttpMethod.OPTIONS, "/**")
.permitAll()
.anyRequest()
.authenticated();

Spring security: set-cookie doesn't work in non-spring environment

I have a spinrg boot app where my frontend code is placed inside the static folder, and everything works great there.
I develop my frontend source outside my spring project and build it to the static folder.
When I run my spring boot app, the frontend works great and the login stores a cookie named JSESSIONID then my API requests work.
The problem is that when I develop my frontend I'm serving my client outside of spring, and the cookie is not stored in my browser upon a successful login.
The question:
Any idea how I can solve it- access and store the cookie although the client is not served with spring?
My spring httpsecurity config:
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/resources/**" , "/assets/**" , "/api/information").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.successHandler(successHandler())
.failureHandler(failureHandler())
// .failureUrl("/authentication/login-error.html")
.permitAll()
.and()
.exceptionHandling()
.accessDeniedHandler(accessDeniedHandler())
// .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and()
.and()
.logout()
.deleteCookies("JSESSIONID")
.permitAll();
Set cookie received from spring:
set-cookie:JSESSIONID=1F16D001A85DDD17CE840CF2A3694231;path=/;Secure;HttpOnly

How to use use `with(user(` when using Spring Session/Security in REST environment

Is it possible to pouplate a Test User with SecurityMockMvcRequestPostProcessors.user when using Spring Session with HeaderHttpSessionStrategy.
I tried something like:
mockMvc.perform(
get(URL)
.with(user("user").password("pwd").roles("USER", "ADMIN")))
.andExpect(status().isOk())
But it returns a 403.
Without the with(user( I get the a 401 so there is a difference.
I've a faily simple SecurityConfig containing:
http
.anonymous()
.and()
.authorizeRequests()
.antMatchers("/api/**").hasAuthority("USER")
.and()
.csrf()
.disable()
.httpBasic()
.and()
.requestCache()
.requestCache(new NullRequestCache());
I's very similar like https://github.com/spring-projects/spring-session/tree/1.0.1.RELEASE/samples/rest as I have an endpoint with I authenticate to with http basic. It returns the authentication token via the header which is then used in other REST calls.
So I was hoping that I just could use the with(user( in this scenario to make my tests easier.
Yes you should be able to do this. The problem is that
.with(user("user").password("pwd").roles("USER", "ADMIN")))
is applying roles which means the ROLE_ prefix is automatically added.
In contrast, your configuration is using:
.antMatchers("/api/**").hasAuthority("USER")
which does not automatically add the ROLE_ prefix. Instead, try using:
.antMatchers("/api/**").hasRole("USER")
NOTE: I have also updated the tests to include an example of with(user("user")).

Resources