-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoAuth.java
More file actions
70 lines (53 loc) · 2.07 KB
/
Copy pathoAuth.java
File metadata and controls
70 lines (53 loc) · 2.07 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.mycompany.app;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import javafx.application.HostServices;
import javafx.stage.Stage;
public class oAuth {
private String clientID;
private String redirectURI;
private String baseUrl;
private HostServices hostServices;
private HttpServer httpServer;
private Stage stage;
public oAuth (String clientID, String redirectURI, String url, Stage stage, HostServices hostServices) {
this.clientID = clientID;
this.redirectURI = redirectURI;
this.baseUrl = url;
this.stage = stage;
this.hostServices = hostServices;
}
public void authenticate() {
// set up a http server to listen to redirect
try {
httpServer = HttpServer.create(new InetSocketAddress("localhost", 1234), 0);
HttpContext context = httpServer.createContext("/auth");
context.setHandler(exchange -> handleRequest(exchange));
httpServer.start();
// open up default browser with login page
String loginURL = baseUrl + "/sharing/oauth2/authorize?client_id=" +
clientID + "&response_type=code&redirect_uri=" + redirectURI;
hostServices.showDocument(loginURL);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void handleRequest(HttpExchange exchange) throws IOException {
// crude capture of the auth code needed to get the token
System.out.println("message : " + exchange.getRequestURI().toString());
// output something in the web browser to say go back to your app
String response = "Please return to your app";
exchange.sendResponseHeaders(200, response.getBytes().length);//response code and length
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
// stop the server
this.httpServer.stop(0);
// attempt to return focus to the JavaFX app, but this doesn't work
this.stage.requestFocus();
}
}