首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Spring boot安全性- postman可以使用REST,但curl命令失败

Spring boot安全性- postman可以使用REST,但curl命令失败
EN

Stack Overflow用户
提问于 2019-01-15 17:19:24
回答 2查看 1.1K关注 0票数 1

我刚接触spring boot,特别是spring security。我正在对我的简单REST服务进行一些测试。

其中有两个:http://localhost:8080/sayhellohttp://localhost:8080/api/sayhello

我的安全配置是这样的:

代码语言:javascript
运行
复制
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/时,我得到了这个:

代码语言:javascript
运行
复制
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/"}

我到底做错了什么?

谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-01-15 17:28:55

默认情况下,所有的url都是在Spring-Security中进行身份验证的。

使用use的代码行

代码语言:javascript
运行
复制
http.httpBasic().and()
                .authorizeRequests()
                .antMatchers("/api/**")  // all url with /api/** will be authenticated having role of USER.
                .hasRole("USER")
                .anyRequest()
                .fullyAuthenticated();

这里

代码语言:javascript
运行
复制
            .antMatchers("/api/**")
            .hasRole("USER")

所有url都被Spring-security筛选器拦截。但是匹配/api/**模式的api必须有角色USER。除了不匹配的url必须通过Spring-security筛选器进行验证。

您应该像这样使用。

代码语言:javascript
运行
复制
  .antMatchers("/sayhello/**").permitAll();

代码语言:javascript
运行
复制
  .anyRequest().permitAll()

将此行添加到您的httpAuthentication将允许您匿名访问http://localhost:8080/sayhello接口。

或者您可以像这样覆盖configure(WebSecurity web)。(这也是可行的)。

代码语言:javascript
运行
复制
@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/sayhello");
}

谢谢。。

票数 2
EN

Stack Overflow用户

发布于 2019-01-15 17:32:08

Spring Security默认情况下会在所有端点上启用URL身份验证。因此,可以更容易地定义允许的URL。以下是修改后的代码

代码语言:javascript
运行
复制
http.httpBasic().and()
            .authorizeRequests()
            .antMatchers("/sayhello").permitAll()
            .anyRequest()
            .hasRole("USER")
            .fullyAuthenticated();
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54195838

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档