2016-09-19 91 views
0

我的web應用程序由Oauth2保護。對於ajax調用,必須在請求文件夾中提供access_token。例如,這裏是在factory.js的方法之一:Angular:如何在不顯示url中的access_token的情況下下載文件

service.getAll = function() { 
     var url = SERVER + "/ristore/foundation/"; 
     return $http({ 
      headers: {'Authorization': 'Bearer ' + $window.localStorage.getItem("access_token")}, 
      url: url, 
      method: 'GET', 
      crossOrigin: true 
     }) 
    } 

現在我想從網頁上下載文件。文件傳遞給客戶端從服務器流:

@RequestMapping(
     value = "/ristore/foundation/xml/{filename}", 
     method = RequestMethod.GET, 
     produces = "application/xml") 
public ResponseEntity<byte[]> downloadXMLFile(@PathVariable String filename) throws IOException { 
    FileSystemResource xmlFile = new FileSystemResource("/rsrch1/rists/moonshot/data/prod/foundation/xml/" + filename + ".xml"); 
    byte [] content = new byte[(int)xmlFile.contentLength()]; 
    IOUtils.read(xmlFile.getInputStream(), content); 

    return ResponseEntity.ok() 
     .contentType(MediaType.parseMediaType("application/octet-stream")) 
     .contentLength(xmlFile.contentLength()) 
     .body(content); 
} 

在HTML中,我指定將被點擊開始下載按鈕上的NG-點擊():

 <td data-title="'File'" class="text-center"><span class="glyphicon glyphicon-download-alt" ng-click="download(report.filename)"></span></a> 
      </td> 

基礎上回答這個帖子Download files in Javascript with OAuth2$window.open用於處理的URL在我的控制器:

$scope.download = function(filename) { 
     var url = "http://rcdrljboss01a:9880/ristoreService/ristore/foundation/xml/" + filename + "?access_token=" + $window.localStorage.getItem("access_token"); 
     $window.open(url); 
    } 

我能夠下載文件這種方式,但在的access_token在downloadin所示g網址。有沒有辦法在url中隱藏access_token?

回答

1

您應該將訪問令牌放在標題中而不是查詢參數中。

這個tutorial顯示了這是如何工作的細節。

編輯:有沒有辦法將標記添加到wondow.open(..)的標題?

不,這似乎不是可以直接更改window.open頭(..)

你可以做什麼:

獲取與阿賈克斯的XML,打開一個新窗口,並設置該文件作爲窗口的內容(僞代碼,您可能需要將內容轉換爲字符串):

var win = open('some-url','windowName','height=300,width=300'); 
win.document.write(content); 
+0

我確實已將access_token放在標題中,用於所有其他請求(如帖子)。但現在我正在使用$ window.open作爲url。如果有一種方法使用標題,我會這樣做。 – ddd

相關問題