Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get list of all Auth0 users

I want to get list of Auth0 users from Java API (auth0 client). Can i do it? API based on Java+Spring Security. I have tried to do it with RestTemplate:

List findAllUsers(){
    String idToken = RestService.getIdToken()
    HttpHeaders headers = new HttpHeaders()
    headers.set("Authorization", "Bearer $idToken");
    List users = []
    try{
        ResponseEntity entity = restTemplate.exchange(issuer+"api/v2/users", HttpMethod.GET, new HttpEntity<Object>(headers), List)
        users = entity.getBody()
    } catch (HttpClientErrorException e){
        e.printStackTrace()
    }
    return users
}

But i'm getting 403 Forbidden status.

like image 298
Sergey Linnik Avatar asked Sep 05 '16 14:09

Sergey Linnik


2 Answers

Yes, this is possible. However, you shall need to use an Auth0 Management Token.

See this sample I wrote, where I do a search (in this case filtering to get a specific user account rather than all users).

You can get Management Token and see the search options here. You need to give your management token read:users and read:user_idp_tokens scopes as per docs.

Would recommend you start by using a tool like Postman to get the correct search, then convert to Java. You can use the snippet and associated dependencies listed in the sample link above OkHttpClient

    <dependency>
        <groupId>com.squareup.okhttp3</groupId>
        <artifactId>okhttp</artifactId>
        <version>3.2.0</version>
    </dependency>

Also, Postman can be used to generate the code from the request you define too. Auth0 currently does not provide a Management API for Java library, but will do so soon.

Update:

Here is some working code, just replace with your Management Token and Tenant (for the URL).

import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;

/**
 * Created by arcseldon on 07/09/2016.
 */
public class GetUsers {

    public static void main(String[] args) throws IOException {

        final String MANAGEMENT_TOKEN = "YOUR_MANAGEMENT_TOKEN";

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url("https://<YOUR_TENANT>.auth0.com/api/v2/users")
                .get()
                .addHeader("authorization", "Bearer " + MANAGEMENT_TOKEN)
                .addHeader("cache-control", "no-cache")
                .build();
        Response response = client.newCall(request).execute();
        System.out.println("All done: " + response.body().string());
    }
}
like image 78
arcseldon Avatar answered Sep 22 '22 01:09

arcseldon


You can use the Library Apache HTTP Client:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.2</version>
</dependency>

and this code works fine :

HttpClient httpclient = new DefaultHttpClient();

                URIBuilder builder = new URIBuilder("https://domain.auth0.com/api/v2/users");
                HttpGet httpGet = new HttpGet(builder.build());
                httpGet.setHeader("Accept", "application/json");
                httpGet.setHeader("Content-type", "application/json");
                httpGet.setHeader(
                        "Authorization",
                        "Bearer "+ token);

                HttpResponse responseHttp = httpclient.execute(httpGet);

                HttpEntity entity = responseHttp.getEntity();

                BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));

                StringBuffer result = new StringBuffer();

                String line = "";
                while ((line = rd.readLine()) != null) {
                    result.append(line);
                    System.out.println(line);
                }

This code you will give you only 50 users, if your users are over than 50 you have to use this URL :

https://domain.auth0.com/api/v2/users?per_page=50&page="+ pageNumber + "&include_totals=true"

and you can specify the number of users per page and the page number including the total of users.

the result of this code is a JSON, so the easiest way to parse it by using the Gson library:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.7</version>
</dependency>

and here is an example of parsing a Json String using the Gson Library :

 public String parse(String jsonLine) {
    JsonElement jelement = new JsonParser().parse(jsonLine);
    JsonObject  jobject = jelement.getAsJsonObject();
    jobject = jobject.getAsJsonObject("data");
    JsonArray jarray = jobject.getAsJsonArray("translations");
    jobject = jarray.get(0).getAsJsonObject();
    String result = jobject.get("translatedText").toString();
    return result;
}
like image 25
Spartan Avatar answered Sep 22 '22 01:09

Spartan