如何登录并开机自检到受 Spring Security 保护的 RESTful 资源



我正在创建一个RESTful Web应用程序,并使用Spring作为后端。当我没有实现 Spring 安全性时,我可以通过使用命令行中的 curl 命令成功地将新记录添加到 JPA 实体"时间戳"。我现在正在使用 Spring 安全性,以便在用户未通过身份验证时,他们将被重定向到登录页面。但是现在当我尝试 curl 添加以下内容的记录时:

curl -i -X POST -v -u myusername:mypass -H "Content-Type:application/json" -d '{ "timestamp" : "2016-06-16T08:17:20.000Z", "peopleIn" : "1", "peopleOut":"0", "venue": "localhost://8181/venues/12" }' http://localhost:8181/timestamps

这显示在终端中:

*   Trying ::1...
* Connected to localhost (::1) port 8181 (#0)
* Server auth using Basic with user 'harry.quigley2@mail.dcu.ie'
> POST /timestamps HTTP/1.1
> Host: localhost:8181
> Authorization: Basic aGFycnkucXVpZ2xleTJAbWFpbC5kY3UuaWU6b2s=
> User-Agent: curl/7.43.0
> Accept: */*
> Content-Type:application/json
> Content-Length: 118
>
* upload completely sent off: 118 out of 118 bytes
< HTTP/1.1 302 Found
HTTP/1.1 302 Found
< Server: Apache-Coyote/1.1
Server: Apache-Coyote/1.1
< X-Content-Type-Options: nosniff
X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
Pragma: no-cache
< Expires: 0
Expires: 0
< X-Frame-Options: DENY
X-Frame-Options: DENY
< Set-Cookie: JSESSIONID=A8EDFA6339DA76B11E0CDF6BB566A748; Path=/; HttpOnly
Set-Cookie: JSESSIONID=A8EDFA6339DA76B11E0CDF6BB566A748; Path=/; HttpOnly
< Location: http://localhost:8181/login
Location: http://localhost:8181/login
< Content-Length: 0
Content-Length: 0
< Date: Sat, 28 May 2016 16:35:53 GMT
Date: Sat, 28 May 2016 16:35:53 GMT

我收到 302 重定向。此外,每行都重复两次 - 我不确定为什么会这样。

我的 Spring 安全配置是:

@Configuration
@EnableWebSecurity
@ComponentScan(basePackageClasses = CustomUserDetailsService.class)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    public void configureGlobal(UserDetailsService userDetailsService, AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                    .antMatchers("/", "/venue/new", "/static/**").permitAll()
                    .anyRequest().authenticated();
                http.formLogin()
                    .loginPage("/login")
                    .permitAll()
                    .and()
                .logout()
                    .permitAll();
        http.csrf().disable();
    }
}

如果有人能理解为什么我被重定向并建议更改哪些内容以便能够发布到 JPA 实体,那就太好了!谢谢

要使用 cURL 进行身份验证,您需要设置 HTTP 基本身份验证:

http.httpBasic();

最新更新