我试图通过X509--客户端认证来实现一个客户端对我的spring boot rest API的认证。我已经创建了一个私钥。
openssl genrsa -des3 -out client.key 1024
为了创建这个密钥,我设置了一些通用的密码,比如: changeit
,这个密码被用于所有后续的文件创建和请求中。
接下来,我创建了一个证书签署请求。
openssl req -new -key client.key -out client.csr
并设置了通用名称 localhost
(据我了解,其他字段无关紧要?)
接下来,使用csr创建证书。
openssl x509 -req -days 3650 -in client.csr -signkey client.key -out client.crt
接着,创建Java Truststore
keytool -import -file client.crt -alias clientCA -keystore truststore.jks
最后,创建keystore作为一个.p12文件。
openssl pkcs12 -export -in client.crt -inkey client.key -certfile client.crt -name "clientcert" -out keystore.p12
在Spring boot(2.0.2版本)这边,我已经有了安全配置类:
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.x509();
}
/*
* localhost is the CN of the client certificate
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("localhost")
.password("none")
.roles("USER");
}
}
和application.properties文件
server.port=8443
logging.level.root=info
server.ssl.key-store=classpath:keystore.p12
server.ssl.key-store-password=changeit
server.ssl.trust-store=classpath:truststore.jks
server.ssl.trust-store-password=changeit
server.ssl.client-auth=need
security.headers.hsts=NONE
提交一个像这样的获取请求
curl -vkE ./keystore.p12:changeit --cert-type P12 "https://localhost:8443/customers/test"
给了我一个有效的响应(故意改变或省略适当的证书扔一个SSL错误),这是很好的。
现在。如果我试着用同样的方式提交一个POST的请求体,如
curl -kiE ./keystore.p12:changeit --cert-type P12 -X POST -H "Content-Type: application/json" --data @req-body.json "https://localhost:8443/customers"
我得到了以下回复。
HTTP/1.1 403
Set-Cookie: JSESSIONID=106214250C497F20C5F1AA02E554B316; Path=/; Secure; HttpOnly
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
Strict-Transport-Security: max-age=31536000 ; includeSubDomains
X-Frame-Options: DENY
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Mon, 16 Jul 2018 13:49:43 GMT
{"timestamp":"2018-07-16T13:49:43.335+0000","status":403,"error":"Forbidden","message":"Forbidden","path":"/customers"}%
我不知道为什么会发生这种情况(403),所以很想寻求帮助。
P.S. 提交除GET以外的任何http方法(甚至是控制器不支持的方法):都会抛出同样的403 - Forbidden。
P.P.S.用GET调用一个不存在的资源,会返回一个漂亮的正确的404响应。所以这和HTTP方法的设置有关系吗?
找到了原因。我禁用了csrf,现在可以用了。