Members of the developer community have requested examples for OAuth implementations in different languages. We’ve created a few examples which can be found here, but in recognition of the talented developers in our community, we wanted to invite you to share your own!
Feel free to contribute your own examples of OAuth Client Credentials flow in this thread!
Golang example for using the golang oauth client for the Client Credential flow.
I felt like most other examples weren’t using the oauth2 library, and this makes it easy, plus it gives you auto-refresh of the oauth credential if it expires.
package main
import (
"context"
"io/ioutil"
"log"
"golang.org/x/oauth2/clientcredentials"
)
func main() {
// Setup oauth2 config
conf := &clientcredentials.Config{
ClientID: "client_id_here",
ClientSecret: "client_secret_here",
TokenURL: "https://us.battle.net/oauth/token",
}
// Get a HTTP client
client := conf.Client(context.Background())
// Use the client, to get a WoW boss, and print the result
resp, err := client.Get("https://us.api.blizzard.com/wow/boss/24723")
if err != nil {
log.Fatal(err)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
log.Println("response: ", string(body))
}
6 Likes
In C#
private OAuthToken RequestAuthorizationToken()
{
var client = new RestClient("https://us.battle.net/oauth/token");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", $"grant_type=client_credentials&client_id={ClientId}&client_secret={ClientSecret}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var token = JsonConvert.DeserializeObject<OAuthToken>(response.Content);
}
public class OAuthToken
{
public string access_token { get; set; }
public string token_type { get; set; }
public int expires_in { get; set; }
public string scope { get; set; }
}
5 Likes
I’m kinda late to the game, but I work in java. Here’s an app that gets the token and does a few requests
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import java.util.logging.Logger;
import org.json.JSONObject;
/**
* @author Afterimage
* / Earthfury
* / Mal'ganis
*
* For this app to work, you need to download and include in your classpath
* json.jar which can be downloaded from https://github.com/stleary/JSON-java
* (direct link https://search.maven.org/remotecontent?filepath=org/json/json/20210307/json-20210307.jar)
*
* You will also have to enter your own CLIENT_ID & CLIENT_SECRET obtained through
* blizzard OAuth service (https://develop.battle.net/documentation/guides/getting-started)
*
*/
public class BlizzardAPI {
private static final Logger logger = Logger.getLogger(BlizzardAPI.class.getSimpleName());
private static final String CLIENT_ID = "PUT_YOUR_CLIENT_ID_HERE";
private static final String CLIENT_SECRET = "PUT_YOUR_CLIENT_SECRET_HERE";
private static final String TOKEN_URL = "https://us.battle.net/oauth/token";
private static long TokenExpireTime = 0;
private static JSONObject Token = null;
private static String inputStreamToString(final InputStream in) throws IOException {
final byte [] data = new byte [2046];
final ByteArrayOutputStream out = new ByteArrayOutputStream();
int numRead = in.read(data);
while (numRead > -1) {
out.write(data, 0, numRead);
numRead = in.read(data);
}
return out.toString();
}
private static JSONObject createToken() throws IOException {
logger.warning("Creating new authentication token");
final String encoding = "utf-8";
final String encodedCredentials = Base64.getEncoder().encodeToString(String.format("%s:%s", CLIENT_ID, CLIENT_SECRET).getBytes(encoding));
final URL url = new URL(TOKEN_URL);
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Authorization", String.format("Basic %s", encodedCredentials));
connection.setDoOutput(true);
connection.getOutputStream().write("grant_type=client_credentials".getBytes(encoding));
int responseCode = connection.getResponseCode();
final InputStream in = connection.getInputStream();
if (responseCode != 200) {
final String message = in == null ? "" : inputStreamToString(in);
logger.severe("Failed to authenticate. responseCode: " + responseCode + ", message=" + message);
return null;
}
final String str = inputStreamToString(in);
Token = new JSONObject(str);
TokenExpireTime = System.currentTimeMillis() + Long.parseLong(Token.get("expires_in").toString()) - 5000L;
return Token;
}
public static JSONObject getToken() throws IOException {
logger.fine("get");
if (TokenExpireTime > System.currentTimeMillis()) {
return createToken();
}
if (Token == null) {
return createToken();
}
else {
return Token;
}
}
public static String get(final String uri, final String namespace, final String locale) throws IOException {
JSONObject token = getToken();
if (token == null) {
return null;
}
final StringBuffer buf = new StringBuffer();
buf.append(uri);
if (uri.contains("?")) {
buf.append("&");
}
else {
buf.append("?");
}
buf.append("namespace=").append(namespace);
buf.append("&locale=").append(locale);
buf.append("&access_token=").append(token.getString("access_token"));
logger.info(buf.toString());
final URL url = new URL(buf.toString());
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int responseCode = connection.getResponseCode();
if (responseCode != 200) {
logger.severe("Failed to request data."
+ ", uri=" + uri
+ ", responseCode=" + responseCode);
return null;
}
final InputStream in = connection.getInputStream();
return inputStreamToString(in);
}
public static void main(String [] args) {
final String namespace = "static-classic-us";
final String locale = "en_US";
final String baseURL = "https://us.api.blizzard.com";
final String [] testPaths = {
"/data/wow/item-class/index",
"/data/wow/media/item/19019",
"/data/wow/creature/30"
};
try {
for (final String path: testPaths) {
final String uri = baseURL + path;
final String result = get(uri, namespace, locale);
final JSONObject object = new JSONObject(result);
logger.info(uri + " ===> " + object.toString(2));
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
github.com/Ulminia/blizzard-api-oauth
my php oauth2 lib for wow game data is updated and ready to use now
hi guys im ok with that?
import requests
from requests.auth import HTTPBasicAuth
import aiohttp
import asyncio
import json
from typing import Union, List, Dict, Tuple
from config import CLIENT_ID, redirect_uri, CLIENT_SECRET, DBPATH
from objects import DB, Character
db = DB()
def get_authorization_link(discord_id: str) → str:
“”"
Generate the authorization link for the user to authorize the application.
Args:
discord_id (str): The Discord ID of the user.
Returns:
str: The authorization link.
"""
print(CLIENT_ID, CLIENT_SECRET)
return f"https://oauth.battle.net/authorize?response_type=code&scope=wow.profile&state={discord_id}&redirect_uri={redirect_uri}/auth&client_id={CLIENT_ID}"
def generate_access_token(auth_code: str) → Dict:
“”"
Generate an access token using the authorization code.
Args:
auth_code (str): The authorization code received from the authorization link.
Returns:
Dict: The response containing the access token and other details.
"""
url = "https://oauth.battle.net/token"
data = {
"redirect_uri": f"{redirect_uri}/auth",
"grant_type": "authorization_code",
"code": auth_code,
}
response = requests.post(url, auth=HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET), data=data)
response.raise_for_status()
return response.json()
Someone can help me please?