Play后端和JavaScript客户端之间的编码/解码URL

时间:2015-02-07 17:54:15

标签: javascript scala playframework url-encoding

我玩REST API和一个JavaScript客户端,在URL中发送令牌:签名对,如下所示:

http://localhost:9000/auth/users/all/0/11?auth=eyJhbGciOiJIUzI1N...ciOiJIU:8so/gRFwOoPXp2x6RfyUpMYIMD4=

在JavaScript客户端中,我对URL进行编码,如下所示:

signature = CryptoJS.HmacSHA1(token + method + obj.url.slice(baseUrl.length) + body, apiKey).toString(CryptoJS.enc.Base64);
...
obj.url = obj.url + (obj.url.indexOf("?") > 0 ? "&" : "?") + "auth=" + encodeURIComponent(token + ":" + signature);

然后,在Play后端我解码URL如下:

import java.nio.charset.{StandardCharsets => SC}
import play.utils.UriEncoding

// auth(0) => token, auth(1) => signature
val auth = UriEncoding.decodePathSegment(jwt, SC.US_ASCII.name).split(":")

问题是由于斜杠导致UriEncoding崩溃:

play.api.Application$$anon$1:
Execution exception[[InvalidUriEncodingException: Cannot decode eyJhbGciOiJIUzI1N...vZ5v18d2EZik1ki5W9_6XABi-JA:8so/gRFwOoPXp2x6RfyUpMYIMD4=: illegal character at position 715.]]

现在我的问题是:

  1. 在使用encodeURIComponent
  2. 对网址进行编码之前,我应该在JavaScript客户端中使用base64
  3. 在Play后端,我应该使用哪种编码,US_ASCIIUTF_8

1 个答案:

答案 0 :(得分:4)

刚刚将UriEncoding.decodePathSegment替换为UriEncoding.decodePath并且有效:

import java.nio.charset.{StandardCharsets => SC}
import play.utils.UriEncoding

// auth(0) => token, auth(1) => signature
val auth = UriEncoding.decodePath(jwt, SC.US_ASCII.name).split(":")

我希望它有所帮助。