<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Selvaraj Mani on Medium]]></title>
        <description><![CDATA[Stories by Selvaraj Mani on Medium]]></description>
        <link>https://medium.com/@selvarajmani?source=rss-1bdebe2e7fcc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*6B1BTSO64hUw5nCp</url>
            <title>Stories by Selvaraj Mani on Medium</title>
            <link>https://medium.com/@selvarajmani?source=rss-1bdebe2e7fcc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 18:57:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@selvarajmani/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Implementing Apple-id Sign-up and login for Flutter Android and Java BE using REST-based redirect]]></title>
            <link>https://medium.com/@selvarajmani/implementing-apple-id-sign-up-and-login-for-flutter-android-and-java-be-using-rest-based-redirect-9ed594846acf?source=rss-1bdebe2e7fcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ed594846acf</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-signup-page-ui]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[apple-id-sign-in]]></category>
            <dc:creator><![CDATA[Selvaraj Mani]]></dc:creator>
            <pubDate>Tue, 13 Jun 2023 17:08:45 GMT</pubDate>
            <atom:updated>2023-06-13T17:13:56.324Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y9D-zFPOcSU-D5YYgvRkZA.jpeg" /></figure><p>This article is a continuation of the previous detailed article, in that we enabled Apple-id authentication for the Flutter iOS application.</p><p>Please refer:</p><p><a href="https://medium.com/@selvarajmani/implementing-apple-id-signup-and-login-for-flutter-ios-java-be-application-bc0058248653">Implementing Apple id signup and login for Flutter iOS, Java BE Application</a></p><p>This article explains the steps that are involved in enabling the Apple-Id signup and login for the Flutter Android applications.</p><h4>Workflow</h4><p>To enable Apple-id authentication for Flutter Android with the backend Java involved the following steps.</p><ul><li>Create Service-Id on the Apple developer portal</li><li>Web authentication options for sign_in_with_apple package API</li><li>Create Redirect REST API</li></ul><h4>Authorization Sequence</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m6F01EzvEK3wrCObX10X4w.png" /></figure><p><strong>Steps:</strong></p><ul><li>Use the sign_in_with_apple pub package</li><li>Use the API SignInWithApple.getAppleIDCredential to log in with Apple-id</li><li>Provide the redirect-URI as a param in WebAuthenticationOptions</li><li>Once auth success the URL will redirect to the redirect-URI as given in the above step</li><li>The redirect URL/REST API will respond with the intent name and parameters to invoke</li><li>Once redirection success to the app through the provided Intent, the application will get the auth profile (includes id-token, access-token, scopes (email, name for the first time), and user-id.</li><li>Send the id-token and the access token to the backend server for validation</li><li>Validate the identity token using the public key fetched from the apple <a href="https://appleid.apple.com/auth/keys">https://appleid.apple.com/auth/keys</a></li><li>Validate the access token using the API <a href="https://appleid.apple.com/auth/token">https://appleid.apple.com/auth/token</a></li><li>Store/Forward the refresh token for the subsequent validations.</li></ul><h4>Create Service-ID</h4><p>Go to <a href="https://developer.apple.com/account/resources/identifiers/list">https://developer.apple.com/account/resources/identifiers/list</a> to create a new service-id for your Android application.</p><ol><li>Go to Identifiers page on apple developer portal</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9zwkvTNwnygl_zWKx3Cdzg.png" /></figure><p>2. Create the new service-identifier</p><p>3. Once the service-id is created configure the service ID</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O8LvoZCHLoKRR_r2KiRX2Q.png" /></figure><p>4. Select your App-ID to associate this service-id</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SmxSR1Ex9AwoT3-6X2GYow.png" /></figure><p>5. Enter the Return URL (https only, and localhost URL’s not accepted) this will be your REST endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GD8fgpht1v2E7LPUXxY9Wg.png" /></figure><h4>Flutter UI Changes</h4><p>Please refer to the previous article pasted above for the sign_in_with_apple API usage and the design.</p><pre>AuthorizationCredentialAppleID credential =<br>      await SignInWithApple.getAppleIDCredential(<br>          scopes: [<br>        AppleIDAuthorizationScopes.email,<br>        AppleIDAuthorizationScopes.fullName,<br>      ],<br>      webAuthenticationOptions: WebAuthenticationOptions(<br>          clientId: &quot;Service-ID&quot;,<br>          redirectUri: Uri.parse(<br>            &#39;https://&lt;your webserver rest host&gt;/&lt;api url&gt;&#39;, <br>//This is the URL We entered in the service-id configuration page<br>)));</pre><h4>Android Manifest Changes</h4><p>For Android, you need to add the following activity to handle the deep link for the redirect intent URL from the REST API. In android/app/src/main/AndroidManifest.xml add the below activity.</p><pre>&lt;activity<br>    android:name=&quot;com.aboutyou.dart_packages.sign_in_with_apple.SignInWithAppleCallback&quot;<br>    android:exported=&quot;true&quot;<br>    android:launchMode=&quot;singleTop&quot;&gt;<br>    &lt;intent-filter&gt;<br>    &lt;action android:name=&quot;android.intent.action.VIEW&quot; /&gt;<br>    &lt;category android:name=&quot;android.intent.category.DEFAULT&quot; /&gt;<br>    &lt;category android:name=&quot;android.intent.category.BROWSABLE&quot; /&gt;<br><br>    &lt;data android:scheme=&quot;signinwithapple&quot; /&gt;<br>    &lt;data android:path=&quot;callback&quot; /&gt;<br>    &lt;/intent-filter&gt;<br>&lt;/activity&gt;</pre><h4>Redirect URL REST API</h4><p>Apple Android authentication requires a redirect URL to be associated with the service identifier. The below example shows the redirect URL implementation using the jax-rs REST API in Java.</p><pre>@Path(&quot;/appleauth&quot;)<br>@Produces(MediaType.APPLICATION_JSON)<br>@Consumes(MediaType.APPLICATION_FORM_URLENCODED)<br>@POST<br>public Response handleAppleAuthAndroid(@Context HttpServletRequest requestContext,<br>        @FormParam(&quot;code&quot;) String code, <br>        @FormParam(&quot;id_token&quot;) String id_token,<br>        @FormParam(&quot;state&quot;) String state,<br>        @FormParam(&quot;user&quot;) String user) throws URISyntaxException {<br>    <br>    String redirectIntent = null;<br>    <br>    if (user != null) {<br>        redirectIntent = String.format(<br>                        &quot;intent://callback?&quot;<br>                        + &quot;code=%s&amp;&quot;<br>                        + &quot;id_token=%s&amp;&quot;<br>                        + &quot;state=%s&amp;&quot;<br>                        + &quot;user=%s&quot;<br>                        + &quot;#Intent;&quot;<br>                        + &quot;package=&lt;flutter android package name (reverse domain)&gt;;&quot;<br>                        + &quot;scheme=signinwithapple;&quot;<br>                        + &quot;end&quot;,<br>                        code, id_token, state, user);<br>    } else {<br>        redirectIntent = String.format(<br>                &quot;intent://callback?&quot;<br>                + &quot;code=%s&amp;&quot;<br>                + &quot;id_token=%s&amp;&quot;<br>                + &quot;#Intent;&quot;<br>                + &quot;package=&lt;flutter android package name (reverse domain)&gt;;&quot;<br>                + &quot;scheme=signinwithapple;&quot;<br>                + &quot;end&quot;,<br>                code, id_token);<br>    }<br>    <br>        <br>       URI uri = new URI(redirectIntent);<br>       <br>    Response response = Response.status(HttpStatus.SC_TEMPORARY_REDIRECT).location(uri).build();<br>    return response;<br>}</pre><p>The redirect API is POST and it accepts the media type APPLICATION_FORM_URLENCODED.</p><h4>Summary</h4><p>The above steps summarizes the workflow in making Apple-id authentication working for Flutter Android application with Java BE using Jax-rs REST API implementation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ed594846acf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Apple id signup and login for Flutter iOS, Java BE Application]]></title>
            <link>https://medium.com/@selvarajmani/implementing-apple-id-signup-and-login-for-flutter-ios-java-be-application-bc0058248653?source=rss-1bdebe2e7fcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc0058248653</guid>
            <category><![CDATA[apple-sign-in]]></category>
            <category><![CDATA[flutter-login]]></category>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[apple-login]]></category>
            <category><![CDATA[appletoken]]></category>
            <dc:creator><![CDATA[Selvaraj Mani]]></dc:creator>
            <pubDate>Sat, 03 Jun 2023 09:10:46 GMT</pubDate>
            <atom:updated>2023-06-03T09:10:46.153Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*50kXRVnGGDO7zGTSiPeKSw.jpeg" /></figure><p><em>Note: This is my first ever article, please forgive any grammatical mistakes :-). I want to share my experience in implementing apple id authentication for my Flutter (Java BE) application. Hope this will help some developers as a reference.</em></p><h4><strong>History</strong></h4><p>Recently we submitted an iOS application for approval on AppConnect, but after 24 hours received a mail saying “App Rejected” with one of the below reasons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LUXvanM5b8eCdoYqUsPZmw.png" /></figure><p>This was a surprise for me. Went back to square-1 to implement the Apple Id authentication for my Flutter application, I already had a bitter experience in implementing login&amp;signup with Facebook id. Initially, I thought Apple documentation will be too clear to understand how to implement (Ex: Stripe is a great example for development pleasure) Apple id sign-in, but the documentation is not clear and there are a lot of conflicting implementations and challenges when searching on the Internet. Finally, with the help of the Internet and ChatGPT, I could able to get the Apple id login working.</p><p>The following sections will explain step-by-step instructions we followed to get apple id working for our Flutter iOS application with Java backend.</p><h4><strong>Workflow</strong></h4><p>I followed the below workflow to get my apple-id authentication working for my Flutter iOS application.</p><ol><li>Creating the Apple Identifiers, Keys, Certificates</li><li>Enabling “Signup” and “Login” using Apple in the Flutter application (Frontend)</li><li>Enabling backend token verification (Java Backend)</li></ol><p>I will clearly mention about each step in the below sections, please feel free to skip a section if you are already done with that step.</p><h4><strong>Step-1: Creating the Apple Identifiers, Keys, Certificates</strong></h4><p>In this step, we need the following list of details to start integrating the Apple-id authentication.</p><p>Note: Apple allows only the paid developer account to be used in apple id auth verification. So as a pre-requisite, you need to have paid apple developer account.</p><ol><li>Apple application identifier (AppId)</li><li>Enable Apple sign-in capability</li><li>Enable Apple sign-in capability on XCode</li><li>Generate the Apple sign in Key</li></ol><p>Note: You have an existing iOS application so I&#39;m assuming you already have the Apple developer account and created the unique bundle-id/app-id.</p><h4><strong>Enable Sign in</strong></h4><p>Go to the developer.apple.com portal and navigate to “<em>Certificates, Identifiers &amp; Profiles</em>”, and enable sign-in with the Apple checkbox.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1BetCZdIhhejyjlum4fR8w.png" /></figure><h4><strong>Enable on XCode</strong></h4><ul><li>Open Runner.xcproject in Xcode.</li><li>Select your Runner in Target</li><li>Go to Signing &amp; Capabilities and add the “Sign in with Apple” capability like below</li><li>Generate the Key, Download the p8 cert (private cert), Note down the key id (KID)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0OCGsbkC216JLyNwf8HHQA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*03ZCFXpJ5GPR7UkswvEPVA.png" /></figure><h4><strong>Create sign-in key</strong></h4><p>Go to “<em>Certificates, Identifiers &amp; Profiles</em>”, and select the “<em>Keys</em>” tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HZr-SyXzscny8QM7uYWyFA.png" /></figure><p>Create a new key, provide some readable name, select the sign-in option, and configure to select the AppId this key is associated with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cg0H2EpI3cm_6Tx-aNrPbA.png" /></figure><p><em>Warning: Once you create the key make sure you download and save the key certificate which is a p8 extension file, Once you download you cannot re-download it again, you lost that key permanently.</em></p><p>Once you save the key and downloaded the key certificate (p8 private cert), Note down the “<strong>Key ID”. </strong>This is the Key Id we refer to as Kid from here on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ec1qtak8Z-7NlDbdw0A-Xw.png" /></figure><h4><strong>Summary</strong></h4><p>After step-1 we have the following details to be used for verification of the token.</p><ul><li>Kid (Key Identifier)</li><li>Client-Id (App Identifier)</li><li>P8 Private Key Cert (Key certificate downloaded)</li></ul><h4><strong>Step-2: Enabling frontend to use Apple-id in the Flutter application</strong></h4><p>I installed the below Flutter package to use the sign-in with Apple.</p><pre>sign_in_with_apple: ^4.3.0</pre><p>After installing the flutter package, on my login screen we integrated the two buttons for “Sign up” and “Login” with the Apple.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*oH9nG_Qivr0mJqxc3J0clg.png" /></figure><h4><strong>Signup Workflow</strong></h4><p>Note: Apple will share the e-mail and name only once during the initial login workflow on your application. Subsequent login will only give you the token and other details but not e-mail and name. So I had to store this information securely in the backend so I can retrieve this information later if needed.</p><p><em>Hint: If you are testing and trying multiple times to get the e-mail and the name from the Apple login workflow, make sure on the simulator/device to sign out from your iCloud (apple-id) and then re-sign in again, that will make to start the workflow fresh and again you will get the e-mail and name for the first sign in again.</em></p><pre>SignInButton(<br>  Buttons.AppleDark,<br>  elevation: 3.0,<br>  text: &quot;Sign up using Apple&quot;,<br>  shape: RoundedRectangleBorder(<br>      borderRadius: BorderRadius.circular(10.0)),<br>  onPressed: () async {<br>    try {<br>      AuthorizationCredentialAppleID credential =<br>          await SignInWithApple.getAppleIDCredential(<br>        scopes: [<br>          AppleIDAuthorizationScopes.email,<br>          AppleIDAuthorizationScopes.fullName,<br>        ],<br>      );<br><br>      await //Send the retrieved email, firstName, familyname to your <br>            //backend to store and fetch it later. Apple will not share <br>            //email and the name everytime you login with Apple-Id.<br>      <br>    } catch (ex) {<br>      print(ex);<br>    }<br>  },<br>)<br><br>//At this stage you got email, name and then you can proceed with <br>//the account creation screens carrying these details and create the <br>//user account on your backend servers.</pre><h4>Flutter Apple Sign-In</h4><pre><br>Platform.isIOS<br>    ? SignInButton(<br>        Buttons.AppleDark,<br>        elevation: 3.0,<br>        onPressed: () async {<br>          handleAppleAuthLogin();<br>        },<br>        shape: RoundedRectangleBorder(<br>            borderRadius: BorderRadius.circular(20.0)),<br>      )<br>)</pre><pre>void handleAppleAuthLogin() async {<br>    try {<br>      AuthorizationCredentialAppleID authzProfile =<br>          await SignInWithApple.getAppleIDCredential(<br>        scopes: [<br>          AppleIDAuthorizationScopes.email,<br>          AppleIDAuthorizationScopes.fullName,<br>        ],<br>      );<br><br>      // At this stage you get the following parameters from the login<br>      <br>      // authzProfile.email<br>      // authzProfile.identityToken<br>      // authzProfile.authorizationCode<br>      // authzProfile.userIdentifier<br>      <br>    } catch (ex) {<br>      print(ex);<br>    }<br>  }</pre><p>After your login with Apple, you get the following params in the authorization profile</p><p>- User e-mail<br>- Identity Token (JWT Token)<br>- Authorization Code (Used for initial login at the back end to fetch the refresh token)<br>- User Identifier (Fixed for each user, you will use this to look up your backend mapping table for fetching email for the given user-identifier, mentioned in the previous sign-up step.)</p><h4><strong>Step-3: Enabling backend token verification</strong></h4><p>As I mentioned earlier our backend is implemented in Java, we need the below dependencies to be able to verify the identity token and get the refresh token given the authorization code.</p><p>Backend implementation is a three-step validation process</p><ul><li>Validating the received identity token (JWT Token) using the Apple public key</li><li>Authorizing the user using the authorization code to fetch the refresh token during the initial login</li><li>Use the refresh token subsequently to verify the validity of the user.</li></ul><p><strong>Identity JWT Token Validation</strong></p><p>Before we delve into identity token validation, we need to fetch the Apple public key for verifying the ID Token</p><p><strong>Apple Public Key</strong></p><p>Use this URL to fetch the Apple public keys. The API returns multiple public keys to the application, We need to check the “kid” (please do not confuse it with the kid which we noted in the previous step, that is the private key id, this is the public key id).</p><p>The identity token that we got on the application will have the public kid in its header, we need to match that kid with the retrieved key list to get the right public key.</p><p><em>Note: When you decode the JWT token (identity token you got on the app), use jwt.io to see the JWT header with the kid.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2twx9h7cY6R2cc_9Bjt9Kg.png" /></figure><pre>https://appleid.apple.com/auth/keys<br><br>Returns :<br>{<br>  &quot;keys&quot;: [<br>    {<br>      &quot;kty&quot;: &quot;RSA&quot;,<br>      &quot;kid&quot;: &quot;W6WcOKB&quot;,   <br>      &quot;use&quot;: &quot;sig&quot;,<br>      &quot;alg&quot;: &quot;RS256&quot;,<br>      &quot;n&quot;: &quot;&lt;public key&gt;&quot;,<br>      &quot;e&quot;: &quot;AQAB&quot;<br>    },<br>    {<br>      &quot;kty&quot;: &quot;RSA&quot;,<br>      &quot;kid&quot;: &quot;fh6Bs8C&quot;,<br>      &quot;use&quot;: &quot;sig&quot;,<br>      &quot;alg&quot;: &quot;RS256&quot;,<br>      &quot;n&quot;: &quot;&lt;public key&gt;&quot;,<br>      &quot;e&quot;: &quot;AQAB&quot;<br>    },<br>    {<br>      &quot;kty&quot;: &quot;RSA&quot;,<br>      &quot;kid&quot;: &quot;YuyXoY&quot;,  &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; this is the public key identifier we need<br>      &quot;use&quot;: &quot;sig&quot;,<br>      &quot;alg&quot;: &quot;RS256&quot;,<br>      &quot;n&quot;: &quot;&lt;public key&gt;&quot;,<br>      &quot;e&quot;: &quot;AQAB&quot;<br>    }<br>  ]<br>}</pre><p><strong>Validation</strong></p><p>Required fields that are used in the subsequent sections.</p><p><em>Note: Refer to AuthorizationCredentialAppleID which we got on the Flutter app for these parameters, TEAM_ID &amp; KEY_ID you got it in the apple developer portal.</em></p><pre>private static final String P8_KEY_FILE_PATH = <br>          &quot;&lt;PATH WHERE THE P8 CERT FILE STORED \<br>          ex: /tmp/signin.apple.authkey&gt;&quot;; <br>// Replace with the actual path to the P8 key file<br>     <br>private String OAUTH_APPLE_TEAM_ID = <br>        &quot;&lt;DEVELOPER ACCOUNT TEAM ID&gt;&quot;;<br>     <br>private String OAUTH_APPLE_KEY_ID = <br>        &quot;&lt;KEY ID WHICH WE CREATED IN PREVIOUS STEP&gt;&quot;;<br><br>private String ID_TOKEN = <br>        &quot;&lt;JWT TOKEN WE GOT ON THE APP, SENT TO BACKEND FOR VEIRIFICATION&gt;&quot;;<br><br>private String AUTHZ_CODE = <br>        &quot;&lt;AUTHORIZATION CODE WE GOT EARLIER&gt;&quot;;</pre><pre>public PublicKey getAppleIdPublicKey(String kid) {<br>    //Fetch the public key<br>    String applePublicKeys = getUrlContents(&quot;https://appleid.apple.com/auth/keys&quot;);<br>    <br>    JSONObject applePublicKeysObject = toJsonObject(applePublicKeys);<br>    JSONArray keys = (JSONArray) applePublicKeysObject.get(&quot;keys&quot;);<br>    try {<br>     for(int idx=0; idx &lt; keys.size(); idx++) {<br>      JSONObject keyInstance = (JSONObject) keys.get(idx);<br>      //get the public key id<br>      String keyIdType = keyInstance.get(&quot;kid&quot;).toString();<br>      //If it matches with the id token kid<br>      if (keyIdType.equals(kid)) {<br>       //Get the key<br>       System.out.println(keyInstance.get(&quot;n&quot;));<br>       String modulus = keyInstance.get(&quot;n&quot;).toString();<br>       String exponent = keyInstance.get(&quot;e&quot;).toString();<br>       <br>       //Create the Java RSA PublicKey Instance with the key retrieved<br>       BigInteger bModulus, bExponent;<br>       KeyFactory factory = KeyFactory.getInstance(&quot;RSA&quot;);<br>       <br>       bModulus = new BigInteger(1, Base64.decodeBase64(modulus));<br>       bExponent = new BigInteger(1, Base64.decodeBase64(exponent));<br>       RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(bModulus, bExponent);<br>       return factory.generatePublic(publicKeySpec);<br>      }<br>       <br>     }<br>    } catch(NoSuchAlgorithmException | InvalidKeySpecException ex) {<br>     <br>    }<br>    <br>    return null;<br>}<br><br><br>private boolean verifyIdentityToken(String idToken, PublicKey publicKey) {<br>        Claims idClaims = Jwts.parserBuilder()<br>          /* This is the public key we got in the previous method*/<br>         .setSigningKey(publicKey) <br>         .build()<br>         .parseClaimsJws(idToken)<br>         .getBody();<br>        <br>        Date expDate = idClaims.getExpiration();<br>        Date now = new Date(System.currentTimeMillis());<br>        if (!expDate.before(expDate)) {<br>         System.out.println(&quot;Expired Token&quot;);<br>         return false;<br>        } <br>        <br>        System.out.println(&quot;Valid Token&quot;);<br>        return true;<br> }</pre><p><strong>Authorizing the user</strong></p><p>In the previous section we finished validating the received identity token, with that we are sure that the received identity token is not tampered with and is indeed generated by the Apple login authentication.</p><p>In this step, we proceed with the user authorization by invoking the API to validate the received authorization code by the Apple authentication servers.</p><p>The below-working code summarizes authorizing the user against the Apple auth servers. The following steps are involved in authorizing the user.</p><ol><li>Parse the downloaded key certificate (Recall the p8 file we fetched earlier) to create the PrivateKey instance, we need this to sign the client secret JWT we generate in step-2.</li><li>Generate the client secret (This is again JWT which we create to send it to Apple servers for validation). It&#39;s a way we put all our auth parameters and sign and send it to Apple servers.</li><li>Authorize user by invoking API: <a href="https://appleid.apple.com/auth/token">https://appleid.apple.com/auth/token</a></li><li>Save the refresh_token in your DB against the user login (or) send it to the app to send to our server for validation.</li><li>Validate refresh_token using API: <a href="https://appleid.apple.com/auth/token">https://appleid.apple.com/auth/token</a></li></ol><pre>//Main Driver method<br>private void appleAuth() throws Exception {<br><br>  //STEP-1: VALIDATE THE IDENTITY TOKEN<br>  //using auth0 library to parse and get the private key id<br>  DecodedJWT decodedJWT = JWT.decode(ID_TOKEN);<br>        String jwtAlgorithm = decodedJWT.getAlgorithm();<br>        String keyId = decodedJWT.getKeyId();<br>        <br><br>  System.out.println(&quot;Validating the apple id user identity token&quot;);<br>  //Get the public key<br>  PublicKey applePublicKey = getAppleIdPublicKey(keyId);<br>  //Verify the identity token using the retrieved public key<br>  verifyIdentityToken(ID_TOKEN, applePublicKey);<br>  <br>  //STEP-2: AUTHORIZE THE USER<br>  //Generate the client secret<br>  String clientSecret = generateClientSecret();<br>  System.out.println(&quot;Generated Token: &quot; + token);<br><br>  //Http Requests Client<br>  AppleTokenResponse tokenValidationResponse = authorizeUser(clientSecret, AUTHZ_CODE, false);<br>  System.out.println(tokenValidationResponse);<br>    <br>}<br><br>private String generateClientSecret() throws Exception {<br>    PrivateKey pKey = generatePrivateKey();<br>    <br>    return Jwts.builder()<br>         .setHeaderParam(JwsHeader.KEY_ID, OAUTH_APPLE_KEY_ID)<br>         .setIssuer(OAUTH_APPLE_TEAM_ID)<br>         .setAudience(&quot;https://appleid.apple.com&quot;)<br>         .setSubject(&quot;&lt;Application ID&gt;&quot;)<br>         .setExpiration(new Date(System.currentTimeMillis() + (1000 * 60 * 5)))<br>         .setIssuedAt(new Date(System.currentTimeMillis()))<br>         .signWith(pKey, SignatureAlgorithm.ES256)<br>         .compact();<br>}<br><br>private PrivateKey generatePrivateKey() throws Exception {<br>    try {<br>           // Read the contents of the P8 certificate file<br>           byte[] keyBytes = Files.readAllBytes(Paths.get(P8_KEY_FILE_PATH));<br>           String privateKeyContent = new String(keyBytes);<br><br>           // Extract the private key from the P8 certificate file<br>           String privateKeyPEM = privateKeyContent<br>                   .replace(&quot;-----BEGIN PRIVATE KEY-----&quot;, &quot;&quot;)<br>                   .replace(&quot;-----END PRIVATE KEY-----&quot;, &quot;&quot;)<br>                   .replaceAll(&quot;\\s+&quot;, &quot;&quot;);<br><br>           byte[] decodedKey = Base64.decodeBase64(privateKeyPEM);<br>           PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);<br>           KeyFactory keyFactory = KeyFactory.getInstance(&quot;EC&quot;);<br>           PrivateKey privateKey = keyFactory.generatePrivate(keySpec);<br>           return privateKey;<br>       } catch (Exception e) {<br>           e.printStackTrace();<br>       }<br>    return null;<br>}<br><br>AppleTokenResponse authorizeUser(String clientSecretJWT, String authzCode, boolean refreshToken) throws ClientProtocolException, IOException {<br>      CloseableHttpClient httpClient = HttpClients.createDefault();<br>      HttpPost httpPost = new HttpPost(&quot;https://appleid.apple.com/auth/token&quot;);<br>      <br>      httpPost.addHeader(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;);<br>      <br>      List&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;();<br>      <br>      params.add(new BasicNameValuePair(&quot;client_id&quot;, &quot;&lt;your app-id&gt;&quot;));<br>      params.add(new BasicNameValuePair(&quot;client_secret&quot;, clientSecretJWT));<br>      <br>      <br>      if (refreshToken == true) {<br>       params.add(new BasicNameValuePair(&quot;grant_type&quot;, &quot;refresh_token&quot;));<br>       params.add(new BasicNameValuePair(&quot;refresh_token&quot;, authzCode));<br>      } else {<br>       params.add(new BasicNameValuePair(&quot;code&quot;, authzCode));<br>       params.add(new BasicNameValuePair(&quot;grant_type&quot;, &quot;authorization_code&quot;));<br>      }<br>      <br>      httpPost.setEntity(new UrlEncodedFormEntity(params));<br>      <br>      HttpResponse httpResponse = httpClient.execute(httpPost);<br>      int responseCode = httpResponse.getStatusLine().getStatusCode();<br>         String responseBody = EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);<br><br>      System.out.println(&quot;RECEIVED STATUS: &quot; + responseCode);<br>      System.out.println(&quot;RESPONSE: &quot; + responseBody);<br>      <br>      if (responseCode == HttpStatus.SC_OK) {<br>       <br>       AppleTokenResponse tokenResponse = this.toObject(responseBody, AppleTokenResponse.class)<br>         .setSuccess(true);<br>       <br>       JSONObject responseBodyJson =  toJsonObject(responseBody);<br>       System.out.println(&quot;RESPONSE JSON: &quot; + responseBodyJson.toJSONString());<br>       return tokenResponse;<br>       <br>      }<br>      <br>      AppleTokenResponse tokenResponse = new AppleTokenResponse().setSuccess(false);<br>      <br>      return tokenResponse;<br>}</pre><p>This summarizes the workflow to integrate the Apple id authentication for the Flutter app with Java back end.</p><h4><strong>References</strong></h4><p><a href="https://chat.openai.com/">https://chat.openai.com/</a></p><ul><li><a href="https://developer.apple.com/documentation/sign_in_with_apple/generate_and_validate_tokens">Generate and validate tokens | Apple Developer Documentation</a></li><li><a href="https://murtazabagwala.xyz/posts/general-blogs">Apple Sign-In and the issue we faced with Expo</a></li><li><a href="https://p.agnihotry.com/post/validating_sign_in_with_apple_authorization_code/">Validating &quot;Sign in with Apple&quot; Authorization Code</a></li><li><a href="https://github.com/eBay/id-token-validation/blob/master/src/main/java/org/ebayopensource/apple/idtoken/AppleIDTokenValidator.java">id-token-validation/AppleIDTokenValidator.java at master · eBay/id-token-validation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc0058248653" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>