我刚接触spring boot,特别是spring security。我正在对我的简单REST服务进行一些测试。
其中有两个:http://localhost:8080/sayhello和http://localhost:8080/api/sayhello
我的安全配置是这样的:
http.httpBasic().and()
.authorizeRequests()
.antMatchers("/api/**")
.hasRole("USER")
.anyRequest()
.fullyAuthenticated();
我希望通过身份验证的是http://localhost:8080/api/sayhello,而不是http://localhost:8080/sayhello
当我在postman上测试http://localhost:8080/sayhello时,我看到了正确的消息,即"Hi!“。
但是当我运行这个curl命令curl -i -X GET http://localhost:8080/sayhello/
时,我得到了这个:
HTTP/1.1 401
Set-Cookie: JSESSIONID=DDB9A6FF9CBCB9811E141FF17A5D40CB; Path=/; HttpOnly
WWW-Authenticate: Basic realm="Realm"
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
X-Frame-Options: DENY
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Tue, 15 Jan 2019 09:11:09 GMT
{"timestamp":"2019-01-15T09:11:09.509+0000","status":401,"error":"Unauthorized","message":"Unauthorized","path":"/sayhello/"}
我到底做错了什么?
谢谢。
发布于 2019-01-15 17:28:55
默认情况下,所有的url都是在Spring-Security
中进行身份验证的。
使用use的代码行
http.httpBasic().and()
.authorizeRequests()
.antMatchers("/api/**") // all url with /api/** will be authenticated having role of USER.
.hasRole("USER")
.anyRequest()
.fullyAuthenticated();
这里
.antMatchers("/api/**")
.hasRole("USER")
所有url都被Spring-security筛选器拦截。但是匹配/api/**
模式的api必须有角色USER
。除了不匹配的url必须通过Spring-security
筛选器进行验证。
您应该像这样使用。
.antMatchers("/sayhello/**").permitAll();
或
.anyRequest().permitAll()
将此行添加到您的httpAuthentication将允许您匿名访问http://localhost:8080/sayhello
接口。
或者您可以像这样覆盖configure(WebSecurity web)
。(这也是可行的)。
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/sayhello");
}
谢谢。。
发布于 2019-01-15 17:32:08
Spring Security默认情况下会在所有端点上启用URL身份验证。因此,可以更容易地定义允许的URL。以下是修改后的代码
http.httpBasic().and()
.authorizeRequests()
.antMatchers("/sayhello").permitAll()
.anyRequest()
.hasRole("USER")
.fullyAuthenticated();
https://stackoverflow.com/questions/54195838
复制相似问题