我有一个Spring休息服务,我正在尝试为其添加安全性。我跟着this tutorial,但是当我尝试直接访问该服务时,我收到以下错误:
出现意外错误(type = Internal Server Error, 状态= 500)。无法评估表达式'ROLE_USER'
这是我的安全配置:
webSecurityConfig.xml
<http entry-point-ref="restAuthenticationEntryPoint">
<intercept-url pattern="/**" access="ROLE_USER"/>
<form-login
authentication-success-handler-ref="mySuccessHandler"
authentication-failure-handler-ref="myFailureHandler"
/>
<logout />
</http>
<beans:bean id="mySuccessHandler"
class="com.eficid.cloud.security.rest.AuthenticationSuccessHandler"/>
<beans:bean id="myFailureHandler" class=
"org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"/>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="temp" password="temp" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
SpringSecurityConfig
:
public class SpringSecurityConfig {
public SpringSecurityConfig() {
super();
}
}
尝试使用curl登录时,我也收到此错误:
{
"timestamp":1460399841286,
"status":403,"error":"Forbidden",
"message":"Could not verify the provided CSRF token because your session was not found.",
"path":"/spring-security-rest/login"
}
我是否需要手动将csrf令牌添加到命令中?该服务具有自签名证书,如果这有任何区别。
答案 0 :(得分:4)
如果您不需要启用CRF,那么您可以在webSecurityConfig.xml文件中禁用它,如下所示:
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/login.html" access="hasRole('ANONYMOUS')" />
<intercept-url pattern="/**" access="hasRole('ROLE_USER')"/>
<!-- This form is a default form that used to login
<http-basic/>
-->
<form-login login-page="/login.html"/>
<csrf disabled="true"/>
</http>
如果启用了CSRF,则必须在要登录或注销的页面中包含_csrf.token。以下代码需要添加到表单中:
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
答案 1 :(得分:3)
答案 2 :(得分:3)
Spring安全阻止POST请求。
要启用它,您可以:
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" class="form-control" />
(例如:
<form id="computerForm" action="addComputer" method="POST">
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" class="form-control" />
)
或者如果你使用anotation,你可以通过在你的WebSecurityConfigurerAdapter上添加 csrf()。disable 来直接在你的代码中允许POST(我还没找到xml等价物):
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
.and().formLogin()
.csrf().disable()
;}