Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package code;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import org.apache.commons.codec.binary.Base64;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
public class ObtainToken implements HttpHandler{
private KeyCloak kcs;
public ObtainToken(KeyCloak kcs) {
this.kcs = kcs;
}
@Override
public void handle(HttpExchange exchange) throws IOException {
URI requestURI = exchange.getRequestURI();
String stringURI = requestURI.toString();
boolean wantsRedirectPage = Helper.compareText(stringURI,URI.create("/").toString());
boolean wantsToken = Helper.compareText(stringURI,URI.create("/secured").toString());
if(!wantsRedirectPage && !wantsToken) {
String error = "Invalid URI";
OutputStream os = exchange.getResponseBody();
exchange.sendResponseHeaders(400, error.getBytes().length);
os.write(error.getBytes());
os.close();
return;
}
String requestMethod = exchange.getRequestMethod();
if (Helper.compareText(requestMethod, "GET")) {
// get the html page
List<String> strlist = new ArrayList<>();
String response = null;
if(wantsRedirectPage)
response = getRedirectPage("/redirect.html");
if(wantsToken)
response = getRedirectPage("/domains.html");
strlist.add("text/html");
if(response != null && !Helper.compareText(response, "fail")){
response = response.replace("$DOMAIN", kcs.authServer())
.replace("$REALM", kcs.realm())
.replace("$MY_REDIRECT_URI", kcs.redirectUri());
exchange.getResponseHeaders().put("content-type", strlist);
exchange.sendResponseHeaders(200, response.getBytes().length);
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
} else {
exchange.sendResponseHeaders(500, response.getBytes().length);
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
// String[] arr = stringURI.split("/secured");
// for(int i=0; i<arr.length; i++)
// System.out.println(arr[i]);
// System.out.println("lunghezza = "+arr.length);
//
// String allParamsString = stringURI.split("/secured")[1];
// System.out.println("allParamsString = "+allParamsString);
// String[] allParamsArray = allParamsString.split("&");
// String state = allParamsArray[0];
// if(!this.state.equals(state)) {
// Helper.badRequest(exchange);
// return;
// }
// String authCode = allParamsArray[2];
//
// // request token
// String httpsURL = "http://"+kcs.authServer()+"/realms/"+kcs.realm()+"/protocol/openid-connect/token";
// URL myUrl = new URL(httpsURL);
//// SSLUtilities.trustAllHttpsCertificates();
//// SSLUtilities.trustAllHostnames();
// HttpsURLConnection conn = (HttpsURLConnection)myUrl.openConnection();
//
// conn.setReadTimeout(7000);
// conn.setConnectTimeout(7000);
// conn.setRequestMethod("POST");
// conn.setDoOutput(true);
// conn.setDoInput(true);
//
// conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
//
// String body = "grant_type=authorization_code"
// + "&client_id="+kcs.clientId()
// + "&code_verifier="+codeVerifier
// + "&code="+authCode
// + "&redirect_uri=https://localhost:3000/secured";
// OutputStream outputStream = conn.getOutputStream();
// outputStream.write(body.getBytes("UTF-8"));
// outputStream.close();
//
// String inputLine;
// InputStream is = conn.getInputStream();
// InputStreamReader isr = new InputStreamReader(is);
// BufferedReader br = new BufferedReader(isr);
// String response = "";
// while ((inputLine = br.readLine()) != null) {
// response += inputLine;
// }
//
// br.close();
// System.out.println(response);
// String answer = response.replace(remoteHOST,localHOST);
} else {
Helper.methodNotAllowed(exchange);
}
}
private static String getRedirectPage(String fileName) {
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
StringBuilder answer = new StringBuilder();
if (getExtension(page).length() == 0)
page += ".html";
BufferedReader bufferedReader = null;
try {
FileReader fileReader = new FileReader(page);
bufferedReader = new BufferedReader(fileReader);
boolean isComment = false;
while ((line = bufferedReader.readLine()) != null) {
line = line.trim();
if(line.startsWith("<!--") && line.endsWith("-->")) {
continue;
}
if(line.startsWith("<!--")) {
isComment = true;
continue;
}
if(line.endsWith("-->")) {
isComment = false;
continue;
}
if(!isComment && line.length()>0)
answer.append(line).append("\n");
}
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '" + page + "'");
return "fail";
} catch (IOException ex) {
System.out.println("Error reading file '" + page + "'");
return "fail";
} finally {
try{
if(bufferedReader != null)
bufferedReader.close();
} catch (IOException ex){
System.out.println("Error closing bufferedReader");
}
}
return answer.toString();
}
private static String getExtension(String file) {
int i = file.length() - 1;
while (i > 0 && file.charAt(i) != '.' && file.charAt(i) != '/')
i--;
if (file.charAt(i) == '.')
return file.substring(i + 1);
else
return "";
}
//
// private String createRandomString() {
// SecureRandom sr = new SecureRandom();
// byte[] code = new byte[32];
// sr.nextBytes(code);
// return java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(code);
// }
//
//
// private String createCodeChallenge(String verifier) throws UnsupportedEncodingException, NoSuchAlgorithmException {
// byte[] bytes = verifier.getBytes("US-ASCII");
// MessageDigest md = MessageDigest.getInstance("SHA-256");
// md.update(bytes, 0, bytes.length);
// byte[] digest = md.digest();
// return Base64.encodeBase64URLSafeString(digest);
// }