使用spring和angular2进行基本身份验证(如何设置XSRF-TOKEN和JSESSIONID)

时间:2017-01-09 08:54:47

标签: java spring spring-mvc angular cookies

所以我有一个spring服务器,我在其中实现了以下配置:

@Configuration
@EnableWebSecurity
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    private static String REALM="Authentication";

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {

        auth.inMemoryAuthentication().withUser("cris").password("123").roles("ADMIN");
        auth.inMemoryAuthentication().withUser("felix").password("felix123").roles("USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.
                httpBasic().and()
                .authorizeRequests()
                .antMatchers("/user", "/vehicles", "/signin").permitAll()
                .anyRequest().authenticated().and()
                .csrf()
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
    }

}

我有以下界面

@RequestMapping("logs")
public interface LogController {

    @RequestMapping(value = "", method = RequestMethod.GET)
    ResponseEntity getLogs();
}

它的实施:

@CrossOrigin(origins = "*", exposedHeaders = {"x-auth-token", "x-requested-with"}, allowedHeaders="*", allowCredentials = "true")
@RestController(  )
public class LogControllerImpl implements LogController {

    @Autowired
    LogService logService;

    //Get all logs
    public ResponseEntity getLogs() {

        List<LogEntityDTO> allLogs = logService.getAllLogs();
        if (allLogs == null)
            return ResponseEntity.notFound().build();

        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.set("authenticated", "you");

        return ResponseEntity.ok(allLogs);
    }

在angular2中,我发出如下请求:

sendAuthentification(credentials:string):Observable {

var headers = new Headers();

headers.append('Authorization', 'Basic ' +  btoa('cris:123'));
headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers.append('withCredentials', 'true');

return this.http.get(this.requestService.getPath() + "/logs", {headers});

}

问题在于,当我从Angular2发出请求时,响应具有以下标头(pragma,content-type,cache control,expires):
enter image description here

但实际上来自服务器的响应标头如下:
  enter image description here

预期的行为是将JSESSIONID和XSRF-TOKEN作为cookie自动保存在浏览器中,但它不会这样做。
问题是使用angular2我无法访问Get-Cookie标头以尝试手动保存cookie。

注意:如果我尝试直接从浏览器发出请求(没有angular2应用程序),浏览器会自动将JSESSIONID和XSRF-TOKEN存储为cookie。

这个问题是angular2问题还是Spring服务器配置问题?如何从angular2获得JSESSIONID和XSRF-TOKEN?

0 个答案:

没有答案