1+ package org .gitlab4j .api .utils ;
2+
3+ import java .io .IOException ;
4+ import java .io .OutputStream ;
5+ import java .io .PrintWriter ;
6+
7+ import javax .ws .rs .WebApplicationException ;
8+ import javax .ws .rs .core .StreamingOutput ;
9+
10+ /**
11+ * This StreamingOutput implementation is utilized to send a OAuth2 token request
12+ * in a secure manner. The password is never copied to a String, instead it is
13+ * contained in a SecretString that is cleared when an instance of this class is finalized.
14+ */
15+ public class Oauth2LoginStreamingOutput implements StreamingOutput , AutoCloseable {
16+
17+ private final String username ;
18+ private final SecretString password ;
19+
20+ public Oauth2LoginStreamingOutput (String username , CharSequence password ) {
21+ this .username = username ;
22+ this .password = new SecretString (password );
23+ }
24+
25+ public Oauth2LoginStreamingOutput (String username , char [] password ) {
26+ this .username = username ;
27+ this .password = new SecretString (password );
28+ }
29+
30+ @ Override
31+ public void write (OutputStream output ) throws IOException , WebApplicationException {
32+
33+ PrintWriter writer = new PrintWriter (output );
34+ writer .append ("{ " );
35+ writer .append ("\" grant_type\" : \" password\" , " );
36+ writer .append ("\" username\" : \" " + username + "\" , " );
37+ writer .append ("\" password\" : " );
38+
39+ // Output the quoted password
40+ writer .append ('"' );
41+ for (int i = 0 , length = password .length (); i < length ; i ++) {
42+ char c = password .charAt (i );
43+ writer .append (c );
44+ }
45+ writer .append ('"' );
46+
47+ writer .append (" }" );
48+ writer .flush ();
49+ writer .close ();
50+ }
51+
52+ /**
53+ * Clears the contained password's data.
54+ */
55+ public void clearPassword () {
56+ password .clear ();
57+ }
58+
59+ @ Override
60+ public void close () {
61+ password .clear ();
62+ }
63+
64+ @ Override
65+ public void finalize () throws Throwable {
66+ clearPassword ();
67+ super .finalize ();
68+ }
69+ }
0 commit comments