Skip to content

Instantly share code, notes, and snippets.

@fernferret
Last active January 12, 2023 03:06
Show Gist options
  • Save fernferret/7692878 to your computer and use it in GitHub Desktop.
Save fernferret/7692878 to your computer and use it in GitHub Desktop.
Steam OpenID Authentication in Java
package com.fernferret.steambot.web;
import org.openid4java.association.AssociationException;
import org.openid4java.consumer.ConsumerException;
import org.openid4java.consumer.ConsumerManager;
import org.openid4java.consumer.VerificationResult;
import org.openid4java.discovery.DiscoveryException;
import org.openid4java.discovery.DiscoveryInformation;
import org.openid4java.discovery.Identifier;
import org.openid4java.message.AuthRequest;
import org.openid4java.message.MessageException;
import org.openid4java.message.ParameterList;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Steam OpenID Login Helper
* <p/>
* In this example, I'm using Spark to handle my request/response.
* <p>Usage:</p>
* <p>
* {@code // Generate a new openid object }
* <br />
* {@code SteamOpenID openid = new SteamOpenID() }
* <p/>
* <p>
* {@code // Redirect the user to the steam login page }
* <br />
* {@code response.redirect(openid.login("http://www.mysite.com/postLogin")); }
* <p>
* {@code // This will return null or a string containing the long variant of }
* {@code the steam id (known as the community id) }
* <br />
* {@code String steamId64 = openid.verify(request.url(), request.queryMap().toMap());}
* <p/>
*/
public class SteamOpenID {
private static final String STEAM_OPENID = "http://steamcommunity.com/openid";
private final ConsumerManager manager;
private final Pattern STEAM_REGEX = Pattern.compile("(\\d+)");
private DiscoveryInformation discovered;
/**
* Creates the {@link ConsumerManager} and sets up
* the {@link DiscoveryInformation}
*/
public SteamOpenID() {
System.setProperty("org.apache.commons.logging.Log",
"org.apache.commons.logging.impl.NoOpLog");
manager = new ConsumerManager();
manager.setMaxAssocAttempts(0);
try {
discovered = manager.associate(manager.discover(STEAM_OPENID));
} catch (DiscoveryException e) {
e.printStackTrace();
discovered = null;
}
}
/**
* Perform a login then redirect to the callback url. When the
* callback url is opened, you are responsible for
* verifying the OpenID login.
*
* @param callbackUrl A String of a url that this login page should
* take you to. This should be an absolute URL.
* @return Returns the URL of the OpenID login page. You should
* redirect your user to this.
*/
public String login(String callbackUrl) {
if (this.discovered == null) {
return null;
}
try {
AuthRequest authReq = manager.authenticate(this.discovered, callbackUrl);
return authReq.getDestinationUrl(true);
} catch (MessageException | ConsumerException e) {
e.printStackTrace();
}
return null;
}
/**
* Verify the Steam OpenID Login
*
* @param receivingUrl The url that received the Login (this should be the
* same as the callbackUrl that you used in
* the {@link #login(String)} method.
* @param responseMap A {@link Map} that contains the response values from the login.
* @return Returns the Steam Community ID as a string.
*/
public String verify(String receivingUrl, Map responseMap) {
if (this.discovered == null) {
return null;
}
ParameterList responseList = new ParameterList(responseMap);
try {
VerificationResult verification = manager.verify(receivingUrl, responseList, this.discovered);
Identifier verifiedId = verification.getVerifiedId();
if (verifiedId != null) {
String id = verifiedId.getIdentifier();
Matcher matcher = STEAM_REGEX.matcher(id);
if (matcher.find()) {
System.out.println();
return matcher.group(1);
}
}
} catch (MessageException | DiscoveryException | AssociationException e) {
e.printStackTrace();
}
return null;
}
}
package com.fernferret.steambot.web;
import spark.Request;
import spark.Response;
import spark.Route;
import static spark.Spark.get;
/**
* Demonstrates the SteamOpenID login class.
*/
public class WebThread implements Runnable {
private final SteamOpenID openid = new SteamOpenID();
private String getFullUrl(Request request, String path) {
StringBuilder builder = new StringBuilder(request.host());
builder.insert(0, "http://");
builder.append(path);
return builder.toString();
}
@Override
public void run() {
get(new Route("/") {
@Override
public Object handle(Request request, Response response) {
String id = request.session(true).attribute("steamid");
StringBuilder bodyString = new StringBuilder();
if (id != null) {
bodyString.append("<h2>Welcome ");
bodyString.append(id);
bodyString.append("</h2>");
bodyString.append("<a href=\"logout\">Logout</a>");
} else {
bodyString.append("<a href=\"trade\">Login</a>");
}
return bodyString.toString();
}
});
get(new Route("/trade") {
@Override
public String handle(Request request, Response response) {
response.redirect(openid.login(getFullUrl(request, "/auth")));
// We should never return here.
// The OpenID login provider should take us somewhere else!
halt(403, "Go Away!");
return null;
}
});
get(new Route("/logout") {
@Override
public String handle(Request request, Response response) {
request.session(true).removeAttribute("steamid");
response.redirect(openid.login(getFullUrl(request, "/")));
return null;
}
});
get(new Route("/auth") {
@Override
public String handle(Request request, Response response) {
String user = openid.verify(request.url(), request.queryMap().toMap());
String fullUrl = getFullUrl(request, "/");
if (user == null) {
response.redirect(fullUrl);
}
request.session(true).attribute("steamid", user);
response.redirect(fullUrl);
return null;
}
});
}
}
package com.fernferret.steambot;
import com.fernferret.steambot.web.WebThread;
/**
* Tests the WebThread class.
*/
public class WebThreadTest {
public static void main(String[] args) {
Thread thread = new Thread(new WebThread());
thread.start();
while(true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@AlexSuvorov2k
Copy link

Hello. how i'm can connect this with android activity?
Thanks

@oharaandrew314
Copy link

Wow, thank you so much for this. I've been trying to figure this out all evening, and this is the first example that actually works.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment