我使用的是Spring Security 5.0.13,我想激活登录页面的csrf保护。我使用的是xml配置,我将其从
<http>
...
<csrf disabled="true"/>
</http>至
<bean id="csrfMatcher" class="org.springframework.security.web.util.matcher.AntPathRequestMatcher">
<constructor-arg name="pattern" value="/j_spring_security_check"/>
<constructor-arg name="httpMethod" value="POST"/>
</bean>
<csrf request-matcher-ref="csrfMatcher" />但是,j_spring_security_logout端点现在需要一个POST请求,而它过去接受的是GET请求。我知道对于注销按钮有一个POST请求会更好,但是我不能破坏这个功能,因为它在我控制之外的其他地方使用。
如何在不影响注销url谓词的情况下为登录页面激活csrf保护?
发布于 2020-08-13 03:14:57
CSRF保护要求您为所有导致更改的请求发送一个包含CRSF属性值的隐藏输入。这就是保护你的东西--这个CSRF属性是由你的服务器生成的,因此不能通过从你的网站之外的其他地方发送请求来伪造。
您只能使用post请求在表单中发送隐藏的输入,因此,如果您希望使用post,则需要使用csrf。好消息是,这非常简单,大多数模板引擎都会自动为您设置所有内容。
使用Thymeleaf,你甚至不需要改变任何东西,它会自动在你的post请求中生成这个属性。
使用Mustache时,您需要添加以下属性:
spring.mustache.expose-request-attributes=true然后使用以下形式:
<form id="logoutForm" method="POST" action="/logout">
<input type="hidden" name="_csrf" value="{{_csrf.token}}"/>
<button type=submit>Logout</button>
</form>正如你所看到的,这确实是相对简单的,但你必须将隐藏的crsf.token值添加到每个post请求,实现取决于你的模板引擎,就像我说的胸腺叶,你不需要担心它。
发布于 2020-08-13 06:18:14
根据Spring Security reference docs,您可以修改Spring Security与/logout端点的匹配方式。默认情况下,它查找POST /logout,但您可以将其配置为查找GET /logout:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) {
http
// ... other configs
.logout(logout -> logout
.logoutRequestMatcher(new AntPathRequestMatcher("/logout", "GET"))
);
}
}虽然您可以声明自己的LogoutFilter和register it类型的<bean>,但通过<logout>元素没有直接的XML等效项。或者logging a ticket可能是将其添加到<logout>中的一个选项。
https://stackoverflow.com/questions/63381803
复制相似问题