1919import static org .junit .Assert .assertEquals ;
2020import static org .junit .Assert .assertNotNull ;
2121import static org .junit .Assert .assertNotSame ;
22- import static org .junit .Assert .assertNull ;
2322import static org .junit .Assert .assertSame ;
2423import static org .junit .Assert .assertTrue ;
2524import static org .junit .Assert .fail ;
2625
27- import com .google .api .client .googleapis .testing .auth .oauth2 .MockTokenServerTransport ;
28- import com .google .api .client .googleapis .util .Utils ;
29- import com .google .api .client .http .HttpTransport ;
30- import com .google .api .client .json .JsonFactory ;
31- import com .google .api .client .json .gson .GsonFactory ;
3226import com .google .api .core .ApiFuture ;
33- import com .google .auth .http .HttpTransportFactory ;
34- import com .google .auth .oauth2 .GoogleCredentials ;
35- import com .google .auth .oauth2 .ServiceAccountCredentials ;
36- import com .google .auth .oauth2 .UserCredentials ;
3727import com .google .common .base .Defaults ;
38- import com .google .common .base .Strings ;
3928import com .google .firebase .FirebaseApp ;
4029import com .google .firebase .FirebaseOptions ;
41- import com .google .firebase .ImplFirebaseTrampolines ;
4230import com .google .firebase .TestOnlyImplFirebaseTrampolines ;
43- import com .google .firebase .auth .internal .FirebaseCustomAuthToken ;
44- import com .google .firebase .database .MapBuilder ;
4531import com .google .firebase .testing .ServiceAccount ;
4632import com .google .firebase .testing .TestUtils ;
47- import java .io .ByteArrayInputStream ;
48- import java .io .IOException ;
49- import java .io .InputStream ;
5033import java .lang .reflect .InvocationTargetException ;
5134import java .lang .reflect .Method ;
5235import java .lang .reflect .Modifier ;
5336import java .util .ArrayList ;
54- import java .util .Arrays ;
55- import java .util .Collection ;
56- import java .util .Collections ;
57- import java .util .HashMap ;
5837import java .util .List ;
59- import java .util .Map ;
6038import java .util .concurrent .ExecutionException ;
6139import java .util .concurrent .TimeUnit ;
6240import java .util .concurrent .TimeoutException ;
6341
6442import org .junit .After ;
6543import org .junit .Assert ;
66- import org .junit .Assume ;
6744import org .junit .Before ;
6845import org .junit .Test ;
69- import org .junit .runner .RunWith ;
70- import org .junit .runners .Parameterized ;
71- import org .junit .runners .Parameterized .Parameters ;
7246
73- @ RunWith (Parameterized .class )
7447public class FirebaseAuthTest {
7548
76- private static final String ACCESS_TOKEN = "mockaccesstoken" ;
77- private static final String CLIENT_SECRET = "mockclientsecret" ;
78- private static final String CLIENT_ID = "mockclientid" ;
79- private static final String REFRESH_TOKEN = "mockrefreshtoken" ;
80- private static final JsonFactory JSON_FACTORY = Utils .getDefaultJsonFactory ();
81-
82- private final FirebaseOptions firebaseOptions ;
83- private final boolean isCertCredential ;
84-
85- public FirebaseAuthTest (FirebaseOptions baseOptions , boolean isCertCredential ) {
86- this .firebaseOptions = baseOptions ;
87- this .isCertCredential = isCertCredential ;
88- }
89-
90- @ Parameters
91- public static Collection <Object []> data () throws Exception {
92- // Initialize this test suite with all available credential implementations.
93- return Arrays .asList (
94- new Object [][] {
95- {
96- new FirebaseOptions .Builder ().setCredentials (createCertificateCredential ()).build (),
97- /* isCertCredential */ true
98- },
99- {
100- new FirebaseOptions .Builder ()
101- .setCredentials (createRefreshTokenCredential ())
102- .setProjectId ("test-project-id" )
103- .build (),
104- /* isCertCredential */ false
105- },
106- {
107- new FirebaseOptions .Builder ()
108- .setCredentials (TestUtils .getApplicationDefaultCredentials ())
109- .build (),
110- /* isCertCredential */ false
111- },
112- });
113- }
114-
115- private static GoogleCredentials createRefreshTokenCredential () throws IOException {
116-
117- final MockTokenServerTransport transport = new MockTokenServerTransport ();
118- transport .addClient (CLIENT_ID , CLIENT_SECRET );
119- transport .addRefreshToken (REFRESH_TOKEN , ACCESS_TOKEN );
120-
121- Map <String , Object > secretJson = new HashMap <>();
122- secretJson .put ("client_id" , CLIENT_ID );
123- secretJson .put ("client_secret" , CLIENT_SECRET );
124- secretJson .put ("refresh_token" , REFRESH_TOKEN );
125- secretJson .put ("type" , "authorized_user" );
126- InputStream refreshTokenStream =
127- new ByteArrayInputStream (JSON_FACTORY .toByteArray (secretJson ));
128-
129- return UserCredentials .fromStream (refreshTokenStream , new HttpTransportFactory () {
130- @ Override
131- public HttpTransport create () {
132- return transport ;
133- }
134- });
135- }
136-
137- private static GoogleCredentials createCertificateCredential () throws IOException {
138- final MockTokenServerTransport transport = new MockTokenServerTransport (
139- "https://accounts.google.com/o/oauth2/token" );
140- transport .addServiceAccount (ServiceAccount .EDITOR .getEmail (), ACCESS_TOKEN );
141- return ServiceAccountCredentials .fromStream (ServiceAccount .EDITOR .asStream (),
142- new HttpTransportFactory () {
143- @ Override
144- public HttpTransport create () {
145- return transport ;
146- }
147- });
148- }
49+ private static final FirebaseOptions firebaseOptions = FirebaseOptions .builder ()
50+ .setCredentials (TestUtils .getCertCredential (ServiceAccount .EDITOR .asStream ()))
51+ .build ();
14952
15053 @ Before
15154 public void setup () {
152- TestOnlyImplFirebaseTrampolines .clearInstancesForTest ();
15355 FirebaseApp .initializeApp (firebaseOptions );
15456 }
15557
@@ -163,8 +65,6 @@ public void testGetInstance() {
16365 FirebaseAuth defaultAuth = FirebaseAuth .getInstance ();
16466 assertNotNull (defaultAuth );
16567 assertSame (defaultAuth , FirebaseAuth .getInstance ());
166- String token = TestOnlyImplFirebaseTrampolines .getToken (FirebaseApp .getInstance (), false );
167- Assert .assertTrue (!token .isEmpty ());
16868 }
16969
17070 @ Test
@@ -173,8 +73,6 @@ public void testGetInstanceForApp() {
17373 FirebaseAuth auth = FirebaseAuth .getInstance (app );
17474 assertNotNull (auth );
17575 assertSame (auth , FirebaseAuth .getInstance (app ));
176- String token = TestOnlyImplFirebaseTrampolines .getToken (app , false );
177- Assert .assertTrue (!token .isEmpty ());
17876 }
17977
18078 @ Test
@@ -234,126 +132,26 @@ public void testInitAfterAppDelete() throws ExecutionException, InterruptedExcep
234132 assertNotNull (auth2 );
235133 assertNotSame (auth1 , auth2 );
236134
237- if (isCertCredential ) {
238- ApiFuture <String > future = auth2 .createCustomTokenAsync ("foo" );
239- assertNotNull (future );
240- assertNotNull (future .get (TestUtils .TEST_TIMEOUT_MILLIS , TimeUnit .MILLISECONDS ));
241- }
242- }
243-
244- @ Test
245- public void testAppWithAuthVariableOverrides () {
246- Map <String , Object > authVariableOverrides = Collections .singletonMap ("uid" , (Object ) "uid1" );
247- FirebaseOptions options =
248- new FirebaseOptions .Builder (firebaseOptions )
249- .setDatabaseAuthVariableOverride (authVariableOverrides )
250- .build ();
251- FirebaseApp app = FirebaseApp .initializeApp (options , "testGetAppWithUid" );
252- assertEquals ("uid1" , app .getOptions ().getDatabaseAuthVariableOverride ().get ("uid" ));
253- String token = TestOnlyImplFirebaseTrampolines .getToken (app , false );
254- Assert .assertTrue (!token .isEmpty ());
255- }
256-
257- @ Test
258- public void testCreateCustomToken () throws Exception {
259- GoogleCredentials credentials = TestOnlyImplFirebaseTrampolines .getCredentials (firebaseOptions );
260- Assume .assumeTrue ("Skipping testCredentialCertificateRequired for cert credential" ,
261- credentials instanceof ServiceAccountCredentials );
262-
263- FirebaseApp app = FirebaseApp .initializeApp (firebaseOptions , "testCreateCustomToken" );
264- FirebaseAuth auth = FirebaseAuth .getInstance (app );
265-
266- String token = auth .createCustomTokenAsync ("user1" ).get ();
267-
268- FirebaseCustomAuthToken parsedToken = FirebaseCustomAuthToken .parse (new GsonFactory (), token );
269- assertEquals (parsedToken .getPayload ().getUid (), "user1" );
270- assertEquals (parsedToken .getPayload ().getSubject (), ServiceAccount .EDITOR .getEmail ());
271- assertEquals (parsedToken .getPayload ().getIssuer (), ServiceAccount .EDITOR .getEmail ());
272- assertNull (parsedToken .getPayload ().getDeveloperClaims ());
273- assertTrue (ServiceAccount .EDITOR .verifySignature (parsedToken ));
274- }
275-
276- @ Test
277- public void testCreateCustomTokenWithDeveloperClaims () throws Exception {
278- GoogleCredentials credentials = TestOnlyImplFirebaseTrampolines .getCredentials (firebaseOptions );
279- Assume .assumeTrue ("Skipping testCredentialCertificateRequired for cert credential" ,
280- credentials instanceof ServiceAccountCredentials );
281-
282- FirebaseApp app =
283- FirebaseApp .initializeApp (firebaseOptions , "testCreateCustomTokenWithDeveloperClaims" );
284- FirebaseAuth auth = FirebaseAuth .getInstance (app );
285-
286- String token =
287- auth .createCustomTokenAsync ("user1" , MapBuilder .of ("claim" , "value" )).get ();
288-
289- FirebaseCustomAuthToken parsedToken = FirebaseCustomAuthToken .parse (new GsonFactory (), token );
290- assertEquals (parsedToken .getPayload ().getUid (), "user1" );
291- assertEquals (parsedToken .getPayload ().getSubject (), ServiceAccount .EDITOR .getEmail ());
292- assertEquals (parsedToken .getPayload ().getIssuer (), ServiceAccount .EDITOR .getEmail ());
293- assertEquals (parsedToken .getPayload ().getDeveloperClaims ().keySet ().size (), 1 );
294- assertEquals (parsedToken .getPayload ().getDeveloperClaims ().get ("claim" ), "value" );
295- assertTrue (ServiceAccount .EDITOR .verifySignature (parsedToken ));
296- }
297-
298- @ Test
299- public void testServiceAccountRequired () throws Exception {
300- GoogleCredentials credentials = TestOnlyImplFirebaseTrampolines .getCredentials (firebaseOptions );
301- Assume .assumeFalse ("Skipping testServiceAccountRequired for service account credentials" ,
302- credentials instanceof ServiceAccountCredentials );
303-
304- FirebaseApp app = FirebaseApp .initializeApp (firebaseOptions , "testServiceAccountRequired" );
305- try {
306- FirebaseAuth .getInstance (app ).createCustomTokenAsync ("foo" ).get ();
307- fail ("Expected exception." );
308- } catch (IllegalStateException expected ) {
309- Assert .assertEquals (
310- "Failed to initialize FirebaseTokenFactory. Make sure to initialize the SDK with "
311- + "service account credentials or specify a service account ID with "
312- + "iam.serviceAccounts.signBlob permission. Please refer to "
313- + "https://firebase.google.com/docs/auth/admin/create-custom-tokens for more details "
314- + "on creating custom tokens." ,
315- expected .getMessage ());
316- }
135+ ApiFuture <String > future = auth2 .createCustomTokenAsync ("foo" );
136+ assertNotNull (future );
137+ assertNotNull (future .get (TestUtils .TEST_TIMEOUT_MILLIS , TimeUnit .MILLISECONDS ));
317138 }
318139
319140 @ Test
320- public void testProjectIdRequired () throws Exception {
321- FirebaseApp app = FirebaseApp .initializeApp (firebaseOptions , "testProjectIdRequired" );
322- String projectId = ImplFirebaseTrampolines .getProjectId (app );
323- Assume .assumeTrue ("Skipping testProjectIdRequired for settings with project ID" ,
324- Strings .isNullOrEmpty (projectId ));
325-
141+ public void testProjectIdRequired () {
142+ FirebaseOptions options = FirebaseOptions .builder ()
143+ .setCredentials (new MockGoogleCredentials ())
144+ .build ();
145+ FirebaseApp app = FirebaseApp .initializeApp (options , "testProjectIdRequired" );
326146 try {
327- FirebaseAuth .getInstance (app ). verifyIdTokenAsync ( "foo" ). get () ;
147+ FirebaseAuth .getInstance (app );
328148 fail ("Expected exception." );
329149 } catch (IllegalArgumentException expected ) {
330150 Assert .assertEquals (
331- "Must initialize FirebaseApp with a project ID to call verifyIdToken()" ,
332- expected .getMessage ());
333- }
334- }
335-
336- @ Test
337- public void testVerifyIdTokenWithExplicitProjectId () throws Exception {
338- GoogleCredentials credentials = TestOnlyImplFirebaseTrampolines .getCredentials (firebaseOptions );
339- Assume .assumeFalse (
340- "Skipping testVerifyIdTokenWithExplicitProjectId for service account credentials" ,
341- credentials instanceof ServiceAccountCredentials );
342-
343- FirebaseOptions options =
344- new FirebaseOptions .Builder (firebaseOptions )
345- .setProjectId ("mock-project-id" )
346- .build ();
347- FirebaseApp app = FirebaseApp .initializeApp (options , "testVerifyIdTokenWithExplicitProjectId" );
348- try {
349- FirebaseAuth .getInstance (app ).verifyIdTokenAsync ("foo" ).get ();
350- fail ("Expected exception." );
351- } catch (ExecutionException expected ) {
352- Assert .assertNotEquals (
353- "com.google.firebase.FirebaseException: Must initialize FirebaseApp with a project ID "
354- + "to call verifyIdToken()" ,
151+ "Project ID is required to access the auth service. Use a service account credential "
152+ + "or set the project ID explicitly via FirebaseOptions. Alternatively you can "
153+ + "also set the project ID via the GOOGLE_CLOUD_PROJECT environment variable." ,
355154 expected .getMessage ());
356- assertTrue (expected .getCause () instanceof IllegalArgumentException );
357155 }
358156 }
359157
0 commit comments