This commit is contained in:
huanghongxun 2015-10-05 16:41:36 +08:00
parent c561faf1f7
commit 1d252ea71c
15 changed files with 399 additions and 668 deletions

View File

@ -28,8 +28,8 @@ import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.GameProfile;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.properties.PropertyMap;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.YggdrasilAuthenticationService;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.YggdrasilUserAuthentication;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.properties.LegacyPropertyMapSerializer;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.UUIDTypeAdapter;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.properties.LegacyPropertyMapSerializer;
/**
*
@ -52,7 +52,7 @@ public final class YggdrasilAuthenticator extends IAuthenticator {
UserProfileProvider result = new UserProfileProvider();
result.setUserName(info.username);
result.setSuccess(true);
result.setUserId(UUIDTypeAdapter.fromUUID(ua.getSelectedProfile().getId()));
result.setUserId(UUIDTypeAdapter.fromUUID(ua.getSelectedProfile().id));
result.setUserProperties(new GsonBuilder().registerTypeAdapter(PropertyMap.class, new LegacyPropertyMapSerializer()).create().toJson(ua.getUserProperties()));
result.setUserPropertyMap(new GsonBuilder().registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer()).create().toJson(ua.getUserProperties()));
result.setAccessToken(ua.getAuthenticatedToken());
@ -83,7 +83,7 @@ public final class YggdrasilAuthenticator extends IAuthenticator {
if (ArrayUtils.isNotEmpty(profiles)) {
names = new String[profiles.length];
for (int i = 0; i < profiles.length; i++)
names[i] = profiles[i].getName();
names[i] = profiles[i].name;
Selector s = new Selector(null, names, C.i18n("login.choose_charactor"));
s.setVisible(true);
selectedProfile = profiles[s.sel];
@ -91,10 +91,10 @@ public final class YggdrasilAuthenticator extends IAuthenticator {
} else
username = JOptionPane.showInputDialog(C.i18n("login.no_charactor"));
else
username = selectedProfile.getName();
username = selectedProfile.name;
result.setUserName(username);
result.setSuccess(true);
result.setUserId(selectedProfile == null ? OfflineAuthenticator.getUUIDFromUserName(username) : UUIDTypeAdapter.fromUUID(selectedProfile.getId()));
result.setUserId(selectedProfile == null ? OfflineAuthenticator.getUUIDFromUserName(username) : UUIDTypeAdapter.fromUUID(selectedProfile.id));
result.setUserProperties(new GsonBuilder().registerTypeAdapter(PropertyMap.class, new LegacyPropertyMapSerializer()).create().toJson(ua.getUserProperties()));
result.setUserPropertyMap(new GsonBuilder().registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer()).create().toJson(ua.getUserProperties()));
String authToken = ua.getAuthenticatedToken();
@ -138,9 +138,9 @@ public final class YggdrasilAuthenticator extends IAuthenticator {
ua.logIn();
if (!ua.isLoggedIn()) throw new Exception(C.i18n("login.wrong_password"));
GameProfile profile = ua.getSelectedProfile();
info.setUserName(profile.getName());
info.setUserName(profile.name);
info.setSuccess(true);
info.setUserId(profile.getId().toString());
info.setUserId(profile.id.toString());
info.setAccessToken(ua.getAuthenticatedToken());
} catch (Exception ex) {
info.setErrorReason(ex.getMessage());

View File

@ -1,4 +1,4 @@
package org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.exceptions;
package org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil;
public class AuthenticationException extends Exception {

View File

@ -1,6 +0,0 @@
package org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil;
public abstract interface AuthenticationService {
public abstract UserAuthentication createUserAuthentication();
}

View File

@ -1,246 +0,0 @@
package org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jackhuang.hellominecraft.logging.logger.Logger;
import org.jackhuang.hellominecraft.utils.StrUtils;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.properties.Property;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.properties.PropertyMap;
public abstract class BaseUserAuthentication
implements UserAuthentication {
private static final Logger LOGGER = new Logger("BaseUserAuthentication");
protected static final String STORAGE_KEY_PROFILE_NAME = "displayName";
protected static final String STORAGE_KEY_PROFILE_ID = "uuid";
protected static final String STORAGE_KEY_PROFILE_PROPERTIES = "profileProperties";
protected static final String STORAGE_KEY_USER_NAME = "username";
protected static final String STORAGE_KEY_USER_ID = "userid";
protected static final String STORAGE_KEY_USER_PROPERTIES = "userProperties";
private final AuthenticationService authenticationService;
private final PropertyMap userProperties = new PropertyMap();
private String userid;
private String username;
private String password;
private GameProfile selectedProfile;
protected BaseUserAuthentication(AuthenticationService authenticationService) {
this.authenticationService = authenticationService;
}
@Override
public boolean canLogIn() {
return (!canPlayOnline()) && (StrUtils.isNotBlank(getUsername())) && (StrUtils.isNotBlank(getPassword()));
}
@Override
public void logOut() {
this.password = null;
this.userid = null;
setSelectedProfile(null);
getModifiableUserProperties().clear();
}
@Override
public boolean isLoggedIn() {
return getSelectedProfile() != null;
}
@Override
public void setUsername(String username) {
if ((isLoggedIn()) && (canPlayOnline())) {
throw new IllegalStateException("Cannot change username whilst logged in & online");
}
this.username = username;
}
@Override
public void setPassword(String password) {
if ((isLoggedIn()) && (canPlayOnline()) && (StrUtils.isNotBlank(password))) {
throw new IllegalStateException("Cannot set password whilst logged in & online");
}
this.password = password;
}
protected String getUsername() {
return this.username;
}
protected String getPassword() {
return this.password;
}
@Override
public void loadFromStorage(Map<String, Object> credentials) {
logOut();
setUsername((String)credentials.get("username"));
if (credentials.containsKey("userid")) {
this.userid = (String)credentials.get("userid");
} else {
this.userid = this.username;
}
if (credentials.containsKey("userProperties")) {
try {
List<Map> list = (List<Map>) credentials.get("userProperties");
for (Map propertyMap : list) {
String name = (String) propertyMap.get("name");
String value = (String) propertyMap.get("value");
String signature = (String) propertyMap.get("signature");
if (signature == null) {
getModifiableUserProperties().put(name, new Property(name, value));
} else {
getModifiableUserProperties().put(name, new Property(name, value, signature));
}
}
} catch (Throwable t) {
LOGGER.warn("Couldn't deserialize user properties", t);
}
}
if ((credentials.containsKey("displayName")) && (credentials.containsKey("uuid"))) {
GameProfile profile = new GameProfile(UUIDTypeAdapter.fromString((String)credentials.get("uuid")), (String)credentials.get("displayName"));
if (credentials.containsKey("profileProperties")) {
try {
List<Map> list = (List<Map>) credentials.get("profileProperties");
for (Map propertyMap : list) {
String name = (String) propertyMap.get("name");
String value = (String) propertyMap.get("value");
String signature = (String) propertyMap.get("signature");
if (signature == null) {
profile.getProperties().put(name, new Property(name, value));
} else {
profile.getProperties().put(name, new Property(name, value, signature));
}
}
} catch (Throwable t) {
LOGGER.warn("Couldn't deserialize profile properties", t);
}
}
setSelectedProfile(profile);
}
}
@Override
public Map<String, Object> saveForStorage() {
Map result = new HashMap();
if (getUsername() != null) {
result.put("username", getUsername());
}
if (getUserID() != null) {
result.put("userid", getUserID());
} else if (getUsername() != null) {
result.put("username", getUsername());
}
if (!getUserProperties().isEmpty()) {
List properties = new ArrayList();
for (Property userProperty : getUserProperties().values()) {
Map property = new HashMap();
property.put("name", userProperty.getName());
property.put("value", userProperty.getValue());
property.put("signature", userProperty.getSignature());
properties.add(property);
}
result.put("userProperties", properties);
}
GameProfile sel = getSelectedProfile();
if (sel != null) {
result.put("displayName", sel.getName());
result.put("uuid", sel.getId());
List properties = new ArrayList();
for (Property profileProperty : sel.getProperties().values()) {
Map property = new HashMap();
property.put("name", profileProperty.getName());
property.put("value", profileProperty.getValue());
property.put("signature", profileProperty.getSignature());
properties.add(property);
}
if (!properties.isEmpty()) {
result.put("profileProperties", properties);
}
}
return result;
}
protected void setSelectedProfile(GameProfile selectedProfile) {
this.selectedProfile = selectedProfile;
}
@Override
public GameProfile getSelectedProfile() {
return this.selectedProfile;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append(getClass().getSimpleName());
result.append("{");
if (isLoggedIn()) {
result.append("Logged in as ");
result.append(getUsername());
if (getSelectedProfile() != null) {
result.append(" / ");
result.append(getSelectedProfile());
result.append(" - ");
if (canPlayOnline()) {
result.append("Online");
} else {
result.append("Offline");
}
}
} else {
result.append("Not logged in");
}
result.append("}");
return result.toString();
}
public AuthenticationService getAuthenticationService() {
return this.authenticationService;
}
@Override
public String getUserID() {
return this.userid;
}
@Override
public PropertyMap getUserProperties() {
if (isLoggedIn()) {
PropertyMap result = new PropertyMap();
result.putAll(getModifiableUserProperties());
return result;
}
return new PropertyMap();
}
protected PropertyMap getModifiableUserProperties() {
return this.userProperties;
}
protected void setUserid(String userid) {
this.userid = userid;
}
}

View File

@ -6,67 +6,45 @@ import org.jackhuang.hellominecraft.utils.StrUtils;
public class GameProfile {
private final UUID id;
private final String name;
private final PropertyMap properties = new PropertyMap();
private boolean legacy;
public final UUID id;
public final String name;
public final PropertyMap properties = new PropertyMap();
public GameProfile(UUID id, String name) {
if ((id == null) && (StrUtils.isBlank(name))) {
if ((id == null) && (StrUtils.isBlank(name)))
throw new IllegalArgumentException("Name and ID cannot both be blank");
}
this.id = id;
this.name = name;
}
public UUID getId() {
return this.id;
}
public String getName() {
return this.name;
}
public PropertyMap getProperties() {
return this.properties;
}
public boolean isComplete() {
return (this.id != null) && (StrUtils.isNotBlank(getName()));
return (id != null) && (StrUtils.isNotBlank(name));
}
@Override
public boolean equals(Object o) {
if (this == o) {
if (this == o)
return true;
}
if ((o == null) || (getClass() != o.getClass())) {
if ((o == null) || (getClass() != o.getClass()))
return false;
}
GameProfile that = (GameProfile) o;
if (this.id != null ? !this.id.equals(that.id) : that.id != null) {
if (id != null ? !id.equals(that.id) : that.id != null)
return false;
}
return this.name != null ? this.name.equals(that.name) : that.name == null;
return name != null ? name.equals(that.name) : that.name == null;
}
@Override
public int hashCode() {
int result = this.id != null ? this.id.hashCode() : 0;
result = 31 * result + (this.name != null ? this.name.hashCode() : 0);
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "GameProfile{" + "id=" + id + ", name=" + name + ", properties=" + properties + ", legacy=" + legacy + '}';
}
public boolean isLegacy() {
return this.legacy;
return "GameProfile{" + "id=" + id + ", name=" + name + ", properties=" + properties + '}';
}
}

View File

@ -1,148 +0,0 @@
package org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import org.jackhuang.hellominecraft.logging.logger.Logger;
import org.jackhuang.hellominecraft.utils.system.IOUtils;
import org.jackhuang.hellominecraft.utils.NetUtils;
import org.jackhuang.hellominecraft.utils.Utils;
public abstract class HttpAuthenticationService implements AuthenticationService {
private static final Logger LOGGER = new Logger("HttpAuthenticationService");
private final Proxy proxy;
protected HttpAuthenticationService(Proxy proxy) {
this.proxy = proxy;
}
public Proxy getProxy() {
return this.proxy;
}
protected HttpURLConnection createUrlConnection(URL url) throws IOException {
LOGGER.debug("Opening connection to " + url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection(this.proxy);
connection.setConnectTimeout(15000);
connection.setReadTimeout(15000);
connection.setUseCaches(false);
return connection;
}
public String performPostRequest(URL url, String post, String contentType) throws IOException {
Utils.requireNonNull(url);
Utils.requireNonNull(post);
Utils.requireNonNull(contentType);
HttpURLConnection connection = createUrlConnection(url);
byte[] postAsBytes = post.getBytes("UTF-8");
connection.setRequestProperty("Content-Type", contentType + "; charset=utf-8");
connection.setRequestProperty("Content-Length", "" + postAsBytes.length);
connection.setDoOutput(true);
LOGGER.debug("Writing POST data to " + url + ": " + post);
OutputStream outputStream = null;
try {
outputStream = connection.getOutputStream();
IOUtils.write(postAsBytes, outputStream);
} finally {
IOUtils.closeQuietly(outputStream);
}
LOGGER.debug("Reading data from " + url);
InputStream inputStream = null;
try {
inputStream = connection.getInputStream();
String result = NetUtils.getStreamContent(inputStream, "UTF-8");
LOGGER.debug("Successful read, server response was " + connection.getResponseCode());
LOGGER.debug("Response: " + result);
String str1 = result;
return str1;
} catch (IOException e) {
IOUtils.closeQuietly(inputStream);
inputStream = connection.getErrorStream();
if (inputStream != null) {
LOGGER.debug("Reading error page from " + url);
String result = NetUtils.getStreamContent(inputStream, "UTF-8");
LOGGER.debug("Successful read, server response was " + connection.getResponseCode());
LOGGER.debug("Response: " + result);
String str2 = result;
return str2;
}
LOGGER.debug("Request failed", e);
throw e;
} finally {
IOUtils.closeQuietly(inputStream);
}
}
public String performGetRequest(URL url)
throws IOException {
Utils.requireNonNull(url);
HttpURLConnection connection = createUrlConnection(url);
LOGGER.debug("Reading data from " + url);
InputStream inputStream = null;
try {
inputStream = connection.getInputStream();
String result = NetUtils.getStreamContent(inputStream, "UTF-8");
LOGGER.debug("Successful read, server response was " + connection.getResponseCode());
LOGGER.debug("Response: " + result);
String str1 = result;
return str1;
} catch (IOException e) {
IOUtils.closeQuietly(inputStream);
inputStream = connection.getErrorStream();
if (inputStream != null) {
LOGGER.debug("Reading error page from " + url);
String result = NetUtils.getStreamContent(inputStream, "UTF-8");
LOGGER.debug("Successful read, server response was " + connection.getResponseCode());
LOGGER.debug("Response: " + result);
String str2 = result;
return str2;
}
LOGGER.debug("Request failed", e);
throw e;
} finally {
IOUtils.closeQuietly(inputStream);
}
}
public static String buildQuery(Map<String, Object> query) {
if (query == null) return "";
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, Object> entry : query.entrySet()) {
if (builder.length() > 0)
builder.append('&');
try {
builder.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
LOGGER.error("Unexpected exception building query", e);
}
if (entry.getValue() != null) {
builder.append('=');
try {
builder.append(URLEncoder.encode(entry.getValue().toString(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
LOGGER.error("Unexpected exception building query", e);
}
}
}
return builder.toString();
}
}

View File

@ -1,13 +0,0 @@
package org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil;
public abstract class HttpUserAuthentication extends BaseUserAuthentication {
protected HttpUserAuthentication(HttpAuthenticationService authenticationService) {
super(authenticationService);
}
@Override
public HttpAuthenticationService getAuthenticationService() {
return (HttpAuthenticationService) super.getAuthenticationService();
}
}

View File

@ -1,40 +0,0 @@
package org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.exceptions.AuthenticationException;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.properties.PropertyMap;
import java.util.Map;
public abstract interface UserAuthentication {
public abstract boolean canLogIn();
public abstract void logIn()
throws AuthenticationException;
public abstract void logOut();
public abstract boolean isLoggedIn();
public abstract boolean canPlayOnline();
public abstract GameProfile[] getAvailableProfiles();
public abstract GameProfile getSelectedProfile();
public abstract void selectGameProfile(GameProfile paramGameProfile)
throws AuthenticationException;
public abstract void loadFromStorage(Map<String, Object> paramMap);
public abstract Map<String, Object> saveForStorage();
public abstract void setUsername(String paramString);
public abstract void setPassword(String paramString);
public abstract String getAuthenticatedToken();
public abstract String getUserID();
public abstract PropertyMap getUserProperties();
}

View File

@ -9,29 +9,36 @@ import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.GameProfile;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.HttpAuthenticationService;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.UserAuthentication;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.exceptions.AuthenticationException;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.exceptions.InvalidCredentialsException;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.properties.PropertyMap;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.response.Response;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.UUIDTypeAdapter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.UUID;
import org.jackhuang.hellominecraft.C;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.response.Response;
import org.jackhuang.hellominecraft.logging.logger.Logger;
import org.jackhuang.hellominecraft.utils.NetUtils;
import org.jackhuang.hellominecraft.utils.StrUtils;
import org.jackhuang.hellominecraft.utils.Utils;
import org.jackhuang.hellominecraft.utils.system.IOUtils;
public class YggdrasilAuthenticationService extends HttpAuthenticationService {
public class YggdrasilAuthenticationService {
private static final Logger LOGGER = new Logger("HttpAuthenticationService");
private final Proxy proxy;
private final String clientToken;
private final Gson gson;
public YggdrasilAuthenticationService(Proxy proxy, String clientToken) {
super(proxy);
this.proxy = proxy;
this.clientToken = clientToken;
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(GameProfile.class, new GameProfileSerializer());
@ -40,26 +47,144 @@ public class YggdrasilAuthenticationService extends HttpAuthenticationService {
this.gson = builder.create();
}
@Override
public UserAuthentication createUserAuthentication() {
public YggdrasilUserAuthentication createUserAuthentication() {
return new YggdrasilUserAuthentication(this);
}
public Proxy getProxy() {
return this.proxy;
}
protected HttpURLConnection createUrlConnection(URL url) throws IOException {
LOGGER.debug("Opening connection to " + url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection(this.proxy);
connection.setConnectTimeout(15000);
connection.setReadTimeout(15000);
connection.setUseCaches(false);
return connection;
}
public String performPostRequest(URL url, String post, String contentType) throws IOException {
Utils.requireNonNull(url);
Utils.requireNonNull(post);
Utils.requireNonNull(contentType);
HttpURLConnection connection = createUrlConnection(url);
byte[] postAsBytes = post.getBytes("UTF-8");
connection.setRequestProperty("Content-Type", contentType + "; charset=utf-8");
connection.setRequestProperty("Content-Length", "" + postAsBytes.length);
connection.setDoOutput(true);
LOGGER.debug("Writing POST data to " + url + ": " + post);
OutputStream outputStream = null;
try {
outputStream = connection.getOutputStream();
IOUtils.write(postAsBytes, outputStream);
} finally {
IOUtils.closeQuietly(outputStream);
}
LOGGER.debug("Reading data from " + url);
InputStream inputStream = null;
try {
inputStream = connection.getInputStream();
String result = NetUtils.getStreamContent(inputStream, "UTF-8");
LOGGER.debug("Successful read, server response was " + connection.getResponseCode());
LOGGER.debug("Response: " + result);
String str1 = result;
return str1;
} catch (IOException e) {
IOUtils.closeQuietly(inputStream);
inputStream = connection.getErrorStream();
if (inputStream != null) {
LOGGER.debug("Reading error page from " + url);
String result = NetUtils.getStreamContent(inputStream, "UTF-8");
LOGGER.debug("Successful read, server response was " + connection.getResponseCode());
LOGGER.debug("Response: " + result);
String str2 = result;
return str2;
}
LOGGER.debug("Request failed", e);
throw e;
} finally {
IOUtils.closeQuietly(inputStream);
}
}
public String performGetRequest(URL url)
throws IOException {
Utils.requireNonNull(url);
HttpURLConnection connection = createUrlConnection(url);
LOGGER.debug("Reading data from " + url);
InputStream inputStream = null;
try {
inputStream = connection.getInputStream();
String result = NetUtils.getStreamContent(inputStream, "UTF-8");
LOGGER.debug("Successful read, server response was " + connection.getResponseCode());
LOGGER.debug("Response: " + result);
String str1 = result;
return str1;
} catch (IOException e) {
IOUtils.closeQuietly(inputStream);
inputStream = connection.getErrorStream();
if (inputStream != null) {
LOGGER.debug("Reading error page from " + url);
String result = NetUtils.getStreamContent(inputStream, "UTF-8");
LOGGER.debug("Successful read, server response was " + connection.getResponseCode());
LOGGER.debug("Response: " + result);
String str2 = result;
return str2;
}
LOGGER.debug("Request failed", e);
throw e;
} finally {
IOUtils.closeQuietly(inputStream);
}
}
public static String buildQuery(Map<String, Object> query) {
if (query == null)
return "";
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, Object> entry : query.entrySet()) {
if (builder.length() > 0)
builder.append('&');
try {
builder.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
LOGGER.error("Unexpected exception building query", e);
}
if (entry.getValue() != null) {
builder.append('=');
try {
builder.append(URLEncoder.encode(entry.getValue().toString(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
LOGGER.error("Unexpected exception building query", e);
}
}
}
return builder.toString();
}
protected <T extends Response> T makeRequest(URL url, Object input, Class<T> classOfT) throws AuthenticationException {
try {
String jsonResult = input == null ? performGetRequest(url) : performPostRequest(url, this.gson.toJson(input), "application/json");
Response result = (Response) this.gson.fromJson(jsonResult, classOfT);
if (result == null) {
if (result == null)
return null;
}
if (StrUtils.isNotBlank(result.getError())) {
if (result.getError().equals("ForbiddenOperationException")) {
throw new InvalidCredentialsException(result.getErrorMessage());
}
throw new AuthenticationException(result.getErrorMessage());
}
if (StrUtils.isNotBlank(result.error))
throw new AuthenticationException("InvalidCredentials " + result.errorMessage);
return (T) result;
} catch (IOException | IllegalStateException | JsonParseException e) {
@ -84,12 +209,10 @@ public class YggdrasilAuthenticationService extends HttpAuthenticationService {
@Override
public JsonElement serialize(GameProfile src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject result = new JsonObject();
if (src.getId() != null) {
result.add("id", context.serialize(src.getId()));
}
if (src.getName() != null) {
result.addProperty("name", src.getName());
}
if (src.id != null)
result.add("id", context.serialize(src.id));
if (src.name != null)
result.addProperty("name", src.name);
return result;
}
}

View File

@ -1,24 +1,95 @@
package org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jackhuang.hellominecraft.C;
import org.jackhuang.hellominecraft.logging.logger.Logger;
import org.jackhuang.hellominecraft.utils.ArrayUtils;
import org.jackhuang.hellominecraft.utils.NetUtils;
import org.jackhuang.hellominecraft.utils.StrUtils;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.GameProfile;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.HttpUserAuthentication;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.exceptions.AuthenticationException;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.exceptions.InvalidCredentialsException;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.properties.Property;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.properties.PropertyMap;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.request.AuthenticationRequest;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.request.RefreshRequest;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.response.AuthenticationResponse;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.response.RefreshResponse;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.response.User;
public class YggdrasilUserAuthentication extends HttpUserAuthentication {
public class YggdrasilUserAuthentication {
protected static final String STORAGE_KEY_PROFILE_NAME = "displayName";
protected static final String STORAGE_KEY_PROFILE_ID = "uuid";
protected static final String STORAGE_KEY_PROFILE_PROPERTIES = "profileProperties";
protected static final String STORAGE_KEY_USER_NAME = "username";
protected static final String STORAGE_KEY_USER_ID = "userid";
protected static final String STORAGE_KEY_USER_PROPERTIES = "userProperties";
private final YggdrasilAuthenticationService authenticationService;
private final PropertyMap userProperties = new PropertyMap();
private String userid;
private String username;
private String password;
private GameProfile selectedProfile;
public void setUsername(String username) {
if ((isLoggedIn()) && (canPlayOnline())) {
throw new IllegalStateException("Cannot change username whilst logged in & online");
}
this.username = username;
}
public void setPassword(String password) {
if ((isLoggedIn()) && (canPlayOnline()) && (StrUtils.isNotBlank(password))) {
throw new IllegalStateException("Cannot set password whilst logged in & online");
}
this.password = password;
}
protected String getUsername() {
return this.username;
}
protected String getPassword() {
return this.password;
}
protected void setSelectedProfile(GameProfile selectedProfile) {
this.selectedProfile = selectedProfile;
}
public GameProfile getSelectedProfile() {
return this.selectedProfile;
}
public YggdrasilAuthenticationService getAuthenticationService() {
return this.authenticationService;
}
public String getUserID() {
return this.userid;
}
public PropertyMap getUserProperties() {
if (isLoggedIn()) {
PropertyMap result = new PropertyMap();
result.putAll(getModifiableUserProperties());
return result;
}
return new PropertyMap();
}
protected PropertyMap getModifiableUserProperties() {
return this.userProperties;
}
protected void setUserid(String userid) {
this.userid = userid;
}
private static final Logger LOGGER = new Logger("YggdrasilUserAuthentication");
private static final String BASE_URL = "https://authserver.mojang.com/";
@ -30,18 +101,16 @@ public class YggdrasilUserAuthentication extends HttpUserAuthentication {
private boolean isOnline;
public YggdrasilUserAuthentication(YggdrasilAuthenticationService authenticationService) {
super(authenticationService);
this.authenticationService = authenticationService;
}
@Override
public boolean canLogIn() {
return (!canPlayOnline()) && (StrUtils.isNotBlank(getUsername())) && ((StrUtils.isNotBlank(getPassword())) || (StrUtils.isNotBlank(getAuthenticatedToken())));
}
@Override
public void logIn() throws AuthenticationException {
if (StrUtils.isBlank(getUsername())) {
throw new InvalidCredentialsException(C.i18n("login.invalid_username"));
throw new AuthenticationException(C.i18n("login.invalid_username"));
}
if (StrUtils.isNotBlank(getAuthenticatedToken())) {
@ -49,16 +118,16 @@ public class YggdrasilUserAuthentication extends HttpUserAuthentication {
} else if (StrUtils.isNotBlank(getPassword())) {
logInWithPassword();
} else {
throw new InvalidCredentialsException(C.i18n("login.invalid_password"));
throw new AuthenticationException(C.i18n("login.invalid_password"));
}
}
protected void logInWithPassword() throws AuthenticationException {
if (StrUtils.isBlank(getUsername())) {
throw new InvalidCredentialsException(C.i18n("login.invalid_username"));
throw new AuthenticationException(C.i18n("login.invalid_username"));
}
if (StrUtils.isBlank(getPassword())) {
throw new InvalidCredentialsException(C.i18n("login.invalid_password"));
throw new AuthenticationException(C.i18n("login.invalid_password"));
}
LOGGER.info("Logging in with username & password");
@ -66,11 +135,11 @@ public class YggdrasilUserAuthentication extends HttpUserAuthentication {
AuthenticationRequest request = new AuthenticationRequest(this, getUsername(), getPassword());
AuthenticationResponse response = (AuthenticationResponse) getAuthenticationService().makeRequest(ROUTE_AUTHENTICATE, request, AuthenticationResponse.class);
if (!response.getClientToken().equals(getAuthenticationService().getClientToken())) {
if (!response.clientToken.equals(getAuthenticationService().getClientToken())) {
throw new AuthenticationException(C.i18n("login.changed_client_token"));
}
User user = response.getUser();
User user = response.user;
if ((user != null) && (user.getId() != null)) {
setUserid(user.getId());
@ -79,10 +148,10 @@ public class YggdrasilUserAuthentication extends HttpUserAuthentication {
}
this.isOnline = true;
this.accessToken = response.getAccessToken();
this.accessToken = response.accessToken;
this.profiles = response.getAvailableProfiles();
setSelectedProfile(response.getSelectedProfile());
this.profiles = response.availableProfiles;
setSelectedProfile(response.selectedProfile);
getModifiableUserProperties().clear();
updateUserProperties(user);
@ -103,11 +172,11 @@ public class YggdrasilUserAuthentication extends HttpUserAuthentication {
if (StrUtils.isBlank(getUsername())) {
setUserid(getUsername());
} else {
throw new InvalidCredentialsException(C.i18n("login.invalid_uuid_and_username"));
throw new AuthenticationException(C.i18n("login.invalid_uuid_and_username"));
}
}
if (StrUtils.isBlank(getAuthenticatedToken())) {
throw new InvalidCredentialsException(C.i18n("login.invalid_access_token"));
throw new AuthenticationException(C.i18n("login.invalid_access_token"));
}
LOGGER.info("Logging in with access token");
@ -115,50 +184,48 @@ public class YggdrasilUserAuthentication extends HttpUserAuthentication {
RefreshRequest request = new RefreshRequest(this);
RefreshResponse response = (RefreshResponse) getAuthenticationService().makeRequest(ROUTE_REFRESH, request, RefreshResponse.class);
if (!response.getClientToken().equals(getAuthenticationService().getClientToken())) {
if (!response.clientToken.equals(getAuthenticationService().getClientToken())) {
throw new AuthenticationException(C.i18n("login.changed_client_token"));
}
if ((response.getUser() != null) && (response.getUser().getId() != null)) {
setUserid(response.getUser().getId());
if ((response.user != null) && (response.user.getId() != null)) {
setUserid(response.user.getId());
} else {
setUserid(getUsername());
}
this.isOnline = true;
this.accessToken = response.getAccessToken();
this.profiles = response.getAvailableProfiles();
setSelectedProfile(response.getSelectedProfile());
this.accessToken = response.accessToken;
this.profiles = response.availableProfiles;
setSelectedProfile(response.selectedProfile);
getModifiableUserProperties().clear();
updateUserProperties(response.getUser());
updateUserProperties(response.user);
}
@Override
public void logOut() {
super.logOut();
this.password = null;
this.userid = null;
setSelectedProfile(null);
getModifiableUserProperties().clear();
this.accessToken = null;
this.profiles = null;
this.isOnline = false;
}
@Override
public GameProfile[] getAvailableProfiles() {
return this.profiles;
}
@Override
public boolean isLoggedIn() {
return StrUtils.isNotBlank(this.accessToken);
}
@Override
public boolean canPlayOnline() {
return (isLoggedIn()) && (getSelectedProfile() != null) && (this.isOnline);
}
@Override
public void selectGameProfile(GameProfile profile) throws AuthenticationException {
if (!isLoggedIn()) {
throw new AuthenticationException(C.i18n("login.profile.not_logged_in"));
@ -173,25 +240,114 @@ public class YggdrasilUserAuthentication extends HttpUserAuthentication {
RefreshRequest request = new RefreshRequest(this, profile);
RefreshResponse response = (RefreshResponse) getAuthenticationService().makeRequest(ROUTE_REFRESH, request, RefreshResponse.class);
if (!response.getClientToken().equals(getAuthenticationService().getClientToken())) {
if (!response.clientToken.equals(getAuthenticationService().getClientToken())) {
throw new AuthenticationException(C.i18n("login.changed_client_token"));
}
this.isOnline = true;
this.accessToken = response.getAccessToken();
setSelectedProfile(response.getSelectedProfile());
this.accessToken = response.accessToken;
setSelectedProfile(response.selectedProfile);
}
@Override
public void loadFromStorage(Map<String, Object> credentials) {
super.loadFromStorage(credentials);
logOut();
setUsername((String)credentials.get("username"));
if (credentials.containsKey("userid")) {
this.userid = (String)credentials.get("userid");
} else {
this.userid = this.username;
}
if (credentials.containsKey("userProperties")) {
try {
List<Map> list = (List<Map>) credentials.get("userProperties");
for (Map propertyMap : list) {
String name = (String) propertyMap.get("name");
String value = (String) propertyMap.get("value");
String signature = (String) propertyMap.get("signature");
if (signature == null) {
getModifiableUserProperties().put(name, new Property(name, value));
} else {
getModifiableUserProperties().put(name, new Property(name, value, signature));
}
}
} catch (Throwable t) {
LOGGER.warn("Couldn't deserialize user properties", t);
}
}
if ((credentials.containsKey("displayName")) && (credentials.containsKey("uuid"))) {
GameProfile profile = new GameProfile(UUIDTypeAdapter.fromString((String)credentials.get("uuid")), (String)credentials.get("displayName"));
if (credentials.containsKey("profileProperties")) {
try {
List<Map> list = (List<Map>) credentials.get("profileProperties");
for (Map propertyMap : list) {
String name = (String) propertyMap.get("name");
String value = (String) propertyMap.get("value");
String signature = (String) propertyMap.get("signature");
if (signature == null) {
profile.properties.put(name, new Property(name, value));
} else {
profile.properties.put(name, new Property(name, value, signature));
}
}
} catch (Throwable t) {
LOGGER.warn("Couldn't deserialize profile properties", t);
}
}
setSelectedProfile(profile);
}
this.accessToken = (String)credentials.get(STORAGE_KEY_ACCESS_TOKEN);
}
@Override
public Map<String, Object> saveForStorage() {
Map result = super.saveForStorage();
Map result = new HashMap();
if (getUsername() != null) {
result.put("username", getUsername());
}
if (getUserID() != null) {
result.put("userid", getUserID());
} else if (getUsername() != null) {
result.put("username", getUsername());
}
if (!getUserProperties().isEmpty()) {
List properties = new ArrayList();
for (Property userProperty : getUserProperties().values()) {
Map property = new HashMap();
property.put("name", userProperty.getName());
property.put("value", userProperty.getValue());
property.put("signature", userProperty.getSignature());
properties.add(property);
}
result.put("userProperties", properties);
}
GameProfile sel = getSelectedProfile();
if (sel != null) {
result.put("displayName", sel.name);
result.put("uuid", sel.id);
List properties = new ArrayList();
for (Property profileProperty : sel.properties.values()) {
Map property = new HashMap();
property.put("name", profileProperty.getName());
property.put("value", profileProperty.getValue());
property.put("signature", profileProperty.getSignature());
properties.add(property);
}
if (!properties.isEmpty()) {
result.put("profileProperties", properties);
}
}
if (StrUtils.isNotBlank(getAuthenticatedToken())) {
result.put("accessToken", getAuthenticatedToken());
@ -203,12 +359,11 @@ public class YggdrasilUserAuthentication extends HttpUserAuthentication {
@Deprecated
public String getSessionToken() {
if ((isLoggedIn()) && (getSelectedProfile() != null) && (canPlayOnline())) {
return String.format("token:%s:%s", new Object[]{getAuthenticatedToken(), getSelectedProfile().getId()});
return String.format("token:%s:%s", new Object[]{getAuthenticatedToken(), getSelectedProfile().id});
}
return null;
}
@Override
public String getAuthenticatedToken() {
return this.accessToken;
}
@ -217,9 +372,4 @@ public class YggdrasilUserAuthentication extends HttpUserAuthentication {
public String toString() {
return "YggdrasilAuthenticationService{profiles=" + Arrays.toString(this.profiles) + ", selectedProfile=" + getSelectedProfile() + ", username='" + getUsername() + '\'' + ", isLoggedIn=" + isLoggedIn() + ", canPlayOnline=" + canPlayOnline() + ", accessToken='" + this.accessToken + '\'' + ", clientToken='" + getAuthenticationService().getClientToken() + '\'' + '}';
}
@Override
public YggdrasilAuthenticationService getAuthenticationService() {
return (YggdrasilAuthenticationService) super.getAuthenticationService();
}
}

View File

@ -1,19 +0,0 @@
package org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.exceptions;
public class InvalidCredentialsException extends AuthenticationException {
public InvalidCredentialsException() {
}
public InvalidCredentialsException(String message) {
super(message);
}
public InvalidCredentialsException(String message, Throwable cause) {
super(message, cause);
}
public InvalidCredentialsException(Throwable cause) {
super(cause);
}
}

View File

@ -10,7 +10,6 @@ import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class PropertyMap extends HashMap<String, Property> {
@ -23,13 +22,10 @@ public class PropertyMap extends HashMap<String, Property> {
@Override
public PropertyMap deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
PropertyMap result = new PropertyMap();
Iterator i$;
Map.Entry<String, JsonElement> entry;
if ((json instanceof JsonObject)) {
JsonObject object = (JsonObject) json;
for (i$ = object.entrySet().iterator(); i$.hasNext();) {
entry = (Map.Entry<String, JsonElement>) i$.next();
for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
if ((entry.getValue() instanceof JsonArray)) {
for (JsonElement element : (JsonArray) entry.getValue()) {
result.put(entry.getKey(),

View File

@ -4,29 +4,9 @@ import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.GameProfile;
public class AuthenticationResponse extends Response {
private String accessToken;
private String clientToken;
private GameProfile selectedProfile;
private GameProfile[] availableProfiles;
private User user;
public String getAccessToken() {
return this.accessToken;
}
public String getClientToken() {
return this.clientToken;
}
public GameProfile[] getAvailableProfiles() {
return this.availableProfiles;
}
public GameProfile getSelectedProfile() {
return this.selectedProfile;
}
public User getUser() {
return this.user;
}
public String accessToken;
public String clientToken;
public GameProfile selectedProfile;
public GameProfile[] availableProfiles;
public User user;
}

View File

@ -4,29 +4,9 @@ import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.GameProfile;
public class RefreshResponse extends Response {
private String accessToken;
private String clientToken;
private GameProfile selectedProfile;
private GameProfile[] availableProfiles;
private User user;
public String getAccessToken() {
return this.accessToken;
}
public String getClientToken() {
return this.clientToken;
}
public GameProfile[] getAvailableProfiles() {
return this.availableProfiles;
}
public GameProfile getSelectedProfile() {
return this.selectedProfile;
}
public User getUser() {
return this.user;
}
public String accessToken;
public String clientToken;
public GameProfile selectedProfile;
public GameProfile[] availableProfiles;
public User user;
}

View File

@ -1,20 +1,16 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.response;
/**
*
* @author huangyuhui
*/
public class Response {
private String error;
private String errorMessage;
private String cause;
public String getError() {
return this.error;
}
public String getCause() {
return this.cause;
}
public String getErrorMessage() {
return this.errorMessage;
}
public String error;
public String errorMessage;
public String cause;
}