88import oauth .signpost .exception .OAuthCommunicationException ;
99import oauth .signpost .exception .OAuthExpectationFailedException ;
1010import oauth .signpost .exception .OAuthMessageSignerException ;
11+ import oauth .signpost .http .HttpParameters ;
12+ import org .apache .commons .codec .binary .Base64 ;
13+ import org .apache .http .HttpEntity ;
14+ import org .apache .http .HttpEntityEnclosingRequest ;
1115import org .apache .http .HttpRequest ;
16+ import org .apache .commons .io .IOUtils ;
1217
1318import java .io .IOException ;
1419import java .net .URISyntaxException ;
20+ import java .net .URLEncoder ;
21+ import java .security .MessageDigest ;
22+ import java .security .NoSuchAlgorithmException ;
1523import java .util .HashMap ;
1624import java .util .Map ;
1725
2230 */
2331public class LtiOauthSigner implements LtiSigner {
2432
33+ private MessageDigest md ;
34+
35+ public LtiOauthSigner () {
36+ try {
37+ md = MessageDigest .getInstance ("SHA1" );
38+ } catch (NoSuchAlgorithmException e ) {
39+ throw new RuntimeException ("Could not construct new instance of LtiOauthSigner" , e );
40+ }
41+ }
42+
43+ public LtiOauthSigner (MessageDigest md ) {
44+ this .md = md ;
45+ }
46+
2547 @ Override
2648 public HttpRequest sign (HttpRequest request , String key , String secret ) throws LtiSigningException {
2749 CommonsHttpOAuthConsumer signer = new CommonsHttpOAuthConsumer (key , secret );
2850 try {
51+ String body = getRequestBody (request );
52+ String bodyHash = new String (Base64 .encodeBase64 (md .digest (body .getBytes ())));
53+
54+ HttpParameters params = new HttpParameters ();
55+ params .put ("oauth_body_hash" , URLEncoder .encode (bodyHash , "UTF-8" ));
56+ signer .setAdditionalParameters (params );
57+
2958 signer .sign (request );
30- } catch (OAuthMessageSignerException |OAuthExpectationFailedException |OAuthCommunicationException e ) {
59+ } catch (OAuthMessageSignerException |OAuthExpectationFailedException |OAuthCommunicationException | IOException e ) {
3160 throw new LtiSigningException ("Exception encountered while singing Lti request..." , e );
3261 }
3362 return request ;
@@ -51,4 +80,14 @@ public Map<String, String> signParameters(Map<String, String> parameters, String
5180 }
5281 }
5382
83+ private String getRequestBody (HttpRequest req ) throws IOException {
84+ if (req instanceof HttpEntityEnclosingRequest ){
85+ HttpEntity body = ((HttpEntityEnclosingRequest ) req ).getEntity ();
86+ return IOUtils .toString (body .getContent ());
87+ } else {
88+ // requests with no entity have an empty string as the body
89+ return "" ;
90+ }
91+ }
92+
5493}
0 commit comments