I developed an application with spring boot, which was working fine. There is a restful controller. I tried to add spring security to some of the pages.
The rest controller's endpoint is
/api/greetings
I configured the security settings in the class below.
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home","/api/greetings").permitAll()
//.antMatchers("/api/greetings","").permitAll()//can't do this
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
Now, when I tried accessing the Rest endpoint, from a Rest-client(Postman), only the GET method is accessible and i am getting 403 Forbidden response if I try to POST, PUT or DELETE.
{
"timestamp": 1467223888525,
"status": 403,
"error": "Forbidden",
"message": "Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.",
"path": "/api/greetings/2"
}
How do i solve this issue. I am new to Spring Security things.
UPDATE Answer
If you're using Spring security 4, you can disable specific routes easily
http.csrf().ignoringAntMatchers("/nocsrf","/ignore/startswith/**")
If not, you can enable/disable CSRF on specific routes using requireCsrfProtectionMatcher
http.csrf().requireCsrfProtectionMatcher(new RequestMatcher() {
private Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");
private RegexRequestMatcher apiMatcher = new RegexRequestMatcher("/v[0-9]*/.*", null);
#Override
public boolean matches(HttpServletRequest request) {
// No CSRF due to allowedMethod
if(allowedMethods.matcher(request.getMethod()).matches())
return false;
// No CSRF due to api call
if(apiMatcher.matches(request))
return false;
// CSRF for everything else that is not an API call or an allowedMethod
return true;
}
});
ORIGINAL Answer
You got an error because CSRF handling is 'on' by default with Spring Security.
You can disabled it by adding http.csrf().disable();.
But really, would you leave your application unsecured? I invite you to read this article to protect your application against CSRF, even if your application is based on REST service and not form submission.
Related
I know there is a lot of questions like this, but I could not find an answer which solves my case.
Here is my config:
#Configuration
#EnableWebSecurity
#RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(HttpMethod.POST, "/").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.permitAll()
.and()
.logout().permitAll();
}
}
And here is my endpoint I want users to have access without logging in:
#Slf4j
#RestController
public class MyController {
#PostMapping(value = "/", consumes = MediaType.TEXT_PLAIN_VALUE)
public void acceptAnonymously(HttpEntity<String> requestEntity) {
log.debug("body: {}", requestEntity.getBody());
}
}
So basically, I want to allow making unauthenticated POST requests to localhost:8080. Everything else should be authenticated. But when I hit localhost:8080 with postman, this is what I get:
So, CSRF stands for Cross-Site Request Forgery and I believe is enabled by default with Spring Web/Security. When it is enabled, you need to properly pass the correct csrf token to your app in order to access your application otherwise you will get thrown a 403 forbidden type error. Alternatively, there are other means of authenticating users if you so desired.
.csrf().disable()
Actually disabling CSRF is not a good idea for all situations. CSRF is enabled by default and as a result, the CSRF token is added to the HttpServletRequest attribute named _csrf. So you only need to add it to your requests.
If you are using Thymeleaf for your html templates you could add something like this to your forms:
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
Our application is using spring security to secure the application,i just added one rest controller which supporting spring oauth security, for oauth token validation, will be called by some other application following are my controller code
#RestController
#EnableResourceServer
public class Controller extends BaseRestController{
#RequestMapping(value="/api/v1/public/insertData", method=RequestMethod.POST)
ResponseEntity<?> insertTPQueueData(TitleProcurementQueue queue,Authentication authentication) {
return null;
}
}
after adding spring oauth security i am getting following error for my other controller using spring security
<oauth>
<error_description>
Full authentication is required to access this resource
</error_description>
<error>unauthorized</error>
</oauth>
Please help
When you put security in your project spring implement some filters, like Cors, basic auth etc..
So you need to tell spring how apply security in your resources.
enter link description here
need to create a class with #EnableWebSecurity
and configure like this:
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/h2-console/**").permitAll()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic()
.csrf().disable();
http.headers().frameOptions().sameOrigin();
}
I'm creating a statless webapp backend that provides bunch of Rest API endpoints. The WebSecurityConfig class that extends WebSecurityConfigurerAdapter looks like this:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.csrf().disable()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.addFilterBefore(
new JWTAuthenticationFilter(userDetailsServiceBean()),
UsernamePasswordAuthenticationFilter.class);
}
When I make a call to /logout endpoint, I expect to get Access Denied and 403 http status code in the response, but I get this:
{
"timestamp": 1495012033216,
"status": 405,
"error": "Method Not Allowed",
"exception": "org.springframework.web.HttpRequestMethodNotSupportedException",
"message": "Request method 'GET' not supported",
"path": "/login"
}
This is what I get with or without including the authentication JWT in the header. Why ? I don't have anything specific to /logout so why does this happen ?
I saw some questions before that login?logout gets the same behavior, but nothing regarding /logout. How should I override this behavior and make it just like any other Rest endpoints ?
What are the benefits of this default behavior ?
I'm developing an android app and I'm using Spring as a REST backend.
Every time I try to make post request to the server I get a 403 response with this message "Expected CSRF token not found. Has your session expired?".
I tried to disable csrf in the application.properties and with my own WebSecurityConfigurerAdapter implementation but to no avail.
Did I miss something ?
Try this :
.invalidateHttpSession(true)
.and()
.exceptionHandling()
.authenticationEntryPoint(new Http403ForbiddenEntryPoint())
.and()
.csrf()//Disabled CSRF protection
.disable();
Add this on your logoutSuccessHandler(...)
There are different ways to disable CSRF in Spring boot , by default in spring boot is enable
1. By Java Configuration
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
2. By Application.yml
security.enable-csrf: false
I'm trying to implement an Angular app using this tutorial: https://spring.io/guides/tutorials/spring-security-and-angular-js/
Logging in works and performing subsequent HTTP calls works, too. Angular successfully appends the CSRF token and Spring successfully parses it. Assuming the token is foo, the requests will contain these headers:
Cookie: JSESSIONID=...; XSRF-TOKEN=foo
X-XSRF-TOKEN: foo
Now, when trying to log out with
$http.post('logout', {}), Angular will use exactly the same headers. However, Spring answers with a 403:
Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.
This is what my security configuration looks like:
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic().and()
.authorizeRequests()
.antMatchers("/").permitAll()
.anyRequest().authenticated().and()
.logout().and()
.addFilterBefore(new CsrfHeaderFilter(), CsrfFilter.class);
}
CsrfHeaderFilter is the class explained in the tutorial (which apparently works for every other request).
I realize it's 2 months late, but I was following the exact same guide today and this unanswered post keeps on popping up so here's the solution.
Basically, you were missing the csrfTokenRepository() configuration in the HttpSecurity configurer.
Spring CsrfTokenRepository expects the header "X-CSRF-TOKEN" but Angular sends the token in a header called "X-XSRF-TOKEN" so the guide recommended you setup an instance of CsrfTokenRepository which expects the Angular default header "X-XSRF-TOKEN":
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic().and()
.authorizeRequests()
.antMatchers("/").permitAll()
.anyRequest().authenticated().and()
.logout()
.and()
//This is the first part you were missing
.csrf()
.csrfTokenRepository(csrfTokenRepository())
.and()
.addFilterBefore(new CsrfHeaderFilter(), CsrfFilter.class);
}
#Bean
public CsrfTokenRepository csrfTokenRepository(){
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
// This is the second part you were missing
repository.setHeaderName("X-XSRF-TOKEN");
return repository;
}