@@ -851,9 +851,17 @@ - (void)getIDTokenResultForcingRefresh:(BOOL)forceRefresh
851851 "error" out parameter.
852852 */
853853- (FIRAuthTokenResult *)parseIDToken : (NSString *)token error : (NSError **)error {
854+ // Though this is an internal method, errors returned here are surfaced in user-visible
855+ // callbacks.
854856 *error = nil ;
855857 NSArray *tokenStringArray = [token componentsSeparatedByString: @" ." ];
856858
859+ // The JWT should have three parts, though we only use the second in this method.
860+ if (tokenStringArray.count != 3 ) {
861+ *error = [FIRAuthErrorUtils malformedJWTErrorWithToken: token underlyingError: nil ];
862+ return nil ;
863+ }
864+
857865 // The token payload is always the second index of the array.
858866 NSString *idToken = tokenStringArray[1 ];
859867
@@ -863,8 +871,10 @@ - (FIRAuthTokenResult *)parseIDToken:(NSString *)token error:(NSError **)error {
863871 [[idToken stringByReplacingOccurrencesOfString: @" _" withString: @" /" ] mutableCopy ];
864872
865873 // Replace "-" with "+"
866- tokenPayload =
867- [[tokenPayload stringByReplacingOccurrencesOfString: @" -" withString: @" +" ] mutableCopy ];
874+ [tokenPayload replaceOccurrencesOfString: @" -"
875+ withString: @" +"
876+ options: kNilOptions
877+ range: NSMakeRange (0 , tokenPayload.length)];
868878
869879 // Pad the token payload with "=" signs if the payload's length is not a multiple of 4.
870880 while ((tokenPayload.length % 4 ) != 0 ) {
@@ -874,19 +884,22 @@ - (FIRAuthTokenResult *)parseIDToken:(NSString *)token error:(NSError **)error {
874884 [[NSData alloc ] initWithBase64EncodedString: tokenPayload
875885 options: NSDataBase64DecodingIgnoreUnknownCharacters ];
876886 if (!decodedTokenPayloadData) {
877- *error = [FIRAuthErrorUtils unexpectedResponseWithDeserializedResponse : token];
887+ *error = [FIRAuthErrorUtils malformedJWTErrorWithToken : token underlyingError: nil ];
878888 return nil ;
879889 }
890+ NSError *jsonError = nil ;
891+ NSJSONReadingOptions options = NSJSONReadingMutableContainers|NSJSONReadingAllowFragments ;
880892 NSDictionary *tokenPayloadDictionary =
881893 [NSJSONSerialization JSONObjectWithData: decodedTokenPayloadData
882- options: NSJSONReadingMutableContainers|NSJSONReadingAllowFragments
883- error: error];
884- if (*error) {
894+ options: options
895+ error: &jsonError];
896+ if (jsonError != nil ) {
897+ *error = [FIRAuthErrorUtils malformedJWTErrorWithToken: token underlyingError: jsonError];
885898 return nil ;
886899 }
887900
888901 if (!tokenPayloadDictionary) {
889- *error = [FIRAuthErrorUtils unexpectedResponseWithDeserializedResponse : token];
902+ *error = [FIRAuthErrorUtils malformedJWTErrorWithToken : token underlyingError: nil ];
890903 return nil ;
891904 }
892905
0 commit comments