by securing and endpoint with a role, works for GET methods bot not POST, I receive 403 Forbidden

霸气de小男生 提交于 2020-01-05 04:18:15

问题


By using Keycloack springboot adapter (with spring security), when defining the typical SecurityConfig (which extends from KeycloakWebSecurityConfigurerAdapter), and overriding the "configure" method, I run into a problem when defining access roles for an endpoint, like follows:

// typically access is defined something like this:
http
.authorizeRequests()
.antMatchers(GET, "/SOME_ENDPOINT").hasRole("SOME_ROLE")
....

This works for me, but when I change GET for POST, suddenly my API responds with - 403 Forbidden - for the intended endpoint (yes, I also updated the HTTP method on the controller's @RequestMapping annotation method itself).

What is even weirder is that I have already created many "bearer only" API's, also secured via Keycloak + springboot adapter + spring security, which have no problem whatsoever differentiating this type of endpoint access by HTTP method (I have used POST, PATCH, PUT, etc), and they work fine.

Is there some kind of restriction with "non bearer only" clients, or may I be overlooking something?

EDIT: The problem seem to stem from the fact that spring security only allows per default GET methods, and a way to go around this as suggested on the link I shared in the comments, would be disabling csrf as follows:

.csrf().disable() 

As also explained there, this deactivates the security for all endpoints which is not what I intend to do. What I'd expect would be that all http POSTs method calls (or any HTTP method) would be treated and secured by the same schema as their "GET" counterpart.


回答1:


Long story short, for anybody running into a similar problem; Spring security by its default CSRF (cross site request forgery) protection policy, will produce an HTTP 403 access denied for all non safe http verbs (POST, PUT, PATCH, DELETE) type of request.

One approach often seen here on stack overflow forums to go around this, is simply to disable csrf checks for a subset of the endpoints like this:

//@configure method of your Spring Security config

// disable some endpoints
http.csrf().ignoringAntMatchers("/URL_PREFIX_WHERE_CRSF_IS_IGNORED/*")....

// or disable all endpoints
http.csrf().disable()....

A better approach would be to explicitly include csrf tokens for any request (and thus avoiding the need to deactivate csrf checks).

Insight into the problem was provided by PraveenKumar Lalasangi as seen on the comments, and here is a detailed documentation related to the inclusion/use of csrf tokens:

https://docs.spring.io/spring-security/site/docs/3.2.5.RELEASE/reference/htmlsingle/#csrf-include-csrf-token



来源:https://stackoverflow.com/questions/58165128/by-securing-and-endpoint-with-a-role-works-for-get-methods-bot-not-post-i-rece

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!