<?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 Oscar Hernandez on Medium]]></title>
        <description><![CDATA[Stories by Oscar Hernandez on Medium]]></description>
        <link>https://medium.com/@Osa_Soft?source=rss-2f3be2e87efa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*iWqebFJekKAWfku5.jpg</url>
            <title>Stories by Oscar Hernandez on Medium</title>
            <link>https://medium.com/@Osa_Soft?source=rss-2f3be2e87efa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 18:31:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Osa_Soft/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[Thoughts about `get`ing Java Collections]]></title>
            <link>https://medium.com/@Osa_Soft/thoughts-about-get-ing-java-collections-97daf8db961a?source=rss-2f3be2e87efa------2</link>
            <guid isPermaLink="false">https://medium.com/p/97daf8db961a</guid>
            <category><![CDATA[getter]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[collection]]></category>
            <category><![CDATA[discussion]]></category>
            <dc:creator><![CDATA[Oscar Hernandez]]></dc:creator>
            <pubDate>Wed, 18 Mar 2020 15:33:29 GMT</pubDate>
            <atom:updated>2020-03-18T15:44:40.814Z</atom:updated>
            <content:encoded><![CDATA[<p>So this came up in a discussion that I had with one of my collegues recently, as we were talking about some of his comments on one of my merge requests. What’s the best way to get a Collection?</p><h3>Naive approach</h3><p>First we have the very basic, naive approach, where we can treat it like a regular primitive getter. Let’s take the following class representing a pub and containing a set of beers that they have on tap.</p><pre>public class Pub {<br>  private Set&lt;String&gt; beers;<br>  <br>  public Pub(String... beers) {<br>    this.beers = new HashSet&lt;&gt;(Arrays.asList(beers)));<br>  }<br>  <br>  public Set&lt;String&gt; getBeers() {<br>    return this.beers;<br>  }<br>}</pre><p>Seems ok, right? Well, not really. There’s an inherent problem to this approach, which breaks our encapsulation. Since a Set (or in general Collection ) is not inherently immutable, when we return the same instance, a consumer of this method might inadvertently change the inner state of our class. Let’s say I want to list all the types of beers I can get in two pubs.</p><pre>Pub hipsterPub = new Pub(&quot;IPA&quot;, &quot;Summer Ale&quot;);<br>Pub pilsnerPub = new Pub(&quot;Pilsner&quot;);</pre><pre>Set&lt;String&gt; beers = hipsterPub.getBeers();<br>beers.addAll(basementPub.getBeers());</pre><p>Seems fine on first sight, but if we try to System.out.println(hipsterPub.getBeers()); we suddenly see we’ve inadvertently changed our hipsterPub menu!</p><pre>[Summer Ale, IPA, Pilsner]</pre><h3>Copy approach</h3><p>Ok, so we see why returning the same instance is not a great idea. A simple sollution comes to mind — let’s return a new instance! The implementation is fairly straight forward:</p><pre>public class Pub {<br>  private Set&lt;String&gt; beers;<br>  <br>  public Pub(String... beers) {<br>    this.beers = new HashSet&lt;&gt;(Arrays.asList(beers));<br>  }<br>  <br>  public Set&lt;String&gt; getBeers() {<br>    return new HashSet&lt;&gt;(this.beers);<br>  }<br>}</pre><p>By wrapping the response in a new instance, any consumer can do whatever they please with the returned value, and it won’t affect our pub. We can see that repeating the example from above:</p><pre>Pub hipsterPub = new Pub(&quot;IPA&quot;, &quot;Summer Ale&quot;);<br>Pub pilsnerPub = new Pub(&quot;Pilsner&quot;);<br>    <br>Set&lt;String&gt; beers = hipsterPub.getBeers();<br>beers.addAll(pilsnerPub.getBeers());<br>    <br>System.out.println(hipsterPub.getBeers());</pre><p>Huzzah! Our hipsters are still safe from the evils of pilsner beer.</p><p>This approach seems fairly reasonable, and works for setters as well. Let’s say we also want to allow setting our beers. In order to again avoid unwanted outside meddling, our setter would look something like this:</p><pre>public void setBeers(Collection&lt;String&gt; beers) {<br>  this.beers = new HashSet&lt;&gt;(beers);<br>}</pre><p>However, this approach has some caveats. Mainly if we are working with large collections and call the getter often. Creating a new instance has overhead, which is not insignificant. Let’s take the following example with 100,000 entries.</p><pre>Set&lt;Integer&gt; numbers = new HashSet&lt;&gt;();<br>for (int i = 0; i &lt;= 100000; i++) {<br>  numbers.add(i);<br>}<br>    <br>long t = System.currentTimeMillis();<br>Set&lt;Integer&gt; copySet = new HashSet&lt;&gt;(numbers);<br>   <br>System.out.println(System.currentTimeMillis() - t);</pre><p>Creating the new instance takes 42ms. It’s not terrible and it’s a big set of data, but if the getter gets called repeatedly, it adds up.</p><h3>Unmodifiable approach</h3><p>So what can we do? We don’t want any consumer of our getter to be able to influence the internal state of our class, but we also don’t want the overhead that comes with creating a new instance every time the getter is called.</p><p>The solution comes with simply forbidding any modifications to the output of our getter.</p><pre>public Set&lt;String&gt; getBeers() {<br>  return Collections.unmodifiableSet(this.beers);<br>}</pre><p>Now our beer listing code above will throw an exception on runtime Exception in thread &quot;main&quot; java.lang.UnsupportedOperationException , forcing us to write it a bit differently (though arguably better):</p><pre>Set&lt;String&gt; beers = new HashSet&lt;&gt;();<br>beers.addAll(hipsterPub.getBeers());<br>beers.addAll(pilsnerPub.getBeers());</pre><p>So this approach removes our overhead every time the getter gets called, as Collections::unmodifiableX simply wraps the existing instance.</p><p>As with everything though, there are still some issues with this approach:</p><h4>Consumer must be aware of internal implementation</h4><p>Since our getter exposes in its definition only that it returns a Set , the consumer isn’t aware that it returns an UnmodifiableSet and they will only realize it once the exception happens. During runtime.</p><p>While good tests should uncover that long before such code gets anywhere near productions, things can slip through the cracks sometimes.</p><p>In this case, I believe it would be best to have this explicitely declared in the api, such as by naming the method getUnmodifiableBeers() instead.</p><h4>Another kind of meddling</h4><p>Another issue with this approach is that it’s now open to another kind of outside interference, this time inside-out.</p><p>Let’s say we want to be able to add beers to our pub. Our class now looks like this:</p><pre>public class Pub {<br>  private Set&lt;String&gt; beers;<br>  <br>  public Pub(String... beers) {<br>    this.beers = new HashSet&lt;&gt;(Arrays.asList(beers));<br>  }<br>  <br>  public Set&lt;String&gt; getBeers() {<br>    return Collections.unmodifiableSet(this.beers);<br>  }<br>  <br>  public void addBeer(String beer) {<br>    this.beers.add(beer);<br>  }<br>}</pre><p>Let’s say I’m making a list of beers I want to try, and all of the beers currently on tap in our hipsterPub seem good, so I create my list:</p><pre>Set&lt;String&gt; beersToTry = hipsterPub.getBeers();</pre><p>Now our pub suddenly has another beer on tap.</p><pre>hipsterPub.addBeer(&quot;Guinness&quot;);    </pre><p>and suddenly my list includes something I definitely don’t want.</p><pre>System.our.println(beersToTry);<br>-&gt; [Guinness, Summer Ale, IPA]</pre><p>Now sure, you probably wouldn’t be doing it like this, but once you take into account the collection and/or the object might be getting passed along to different methods, classes and threads, weird things can begin to happen.</p><h3>In conclusion</h3><p>I really don’t have a universal “best” way to handle this situation, and the optimal way likely depends on your specific scenario. I just wanted to get some of my thoughts out there and hopefully hear some more opinions on the matter.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97daf8db961a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Micronaut app with Micronaut Data, Liquibase and Testcontainers]]></title>
            <link>https://medium.com/@Osa_Soft/creating-a-micronaut-app-with-micronaut-data-liquibase-and-testcontainers-5f833e69f289?source=rss-2f3be2e87efa------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f833e69f289</guid>
            <category><![CDATA[groovy]]></category>
            <category><![CDATA[liquibase]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[micronaut]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Oscar Hernandez]]></dc:creator>
            <pubDate>Mon, 09 Sep 2019 15:37:48 GMT</pubDate>
            <atom:updated>2019-09-09T15:37:48.888Z</atom:updated>
            <content:encoded><![CDATA[<p>Starting a new project is always a chance to play around with new technologies. I’ve been anxious to properly give a try to Micronaut ever since its announcement on Greach 2018 and besides a small CLI app I haven’t really had the chance yet. Since then, the team behind Micronaut has also released Micronaut Data (formerly Predator), which aims to combine the ease of use of Spring Data to the lightning speed and compile-time magic of Micronaut. So when I was starting a new project, it was clear I needed to use both of these.</p><p>As these technologies are fairly new, theres not much information about them online yet and at times it was hard to find a way to properly combine everything I needed for what a basic production-ready stack.</p><p>The goal of this post is to bring together and aggregate what I learned during the creation of a basic app skeleton and create a guide for others to save the time I spent getting it all working.</p><h3>Create basic empty Micronaut app</h3><p>All right, let’s start from the top. Assuming you have <a href="https://sdkman.io/">SDKMan</a> installed, let’s install the Micronaut CLI tools.</p><pre>sdk install micronaut 1.2.1</pre><p>and create a Groovy Micronaut app (you can use Java or Kotlin, the entire process should be similar)</p><pre>mn create-app cloud.osasoft.micronaut.example.basicExample --lang=groovy</pre><p>This will createa Micronaut app in a subfolder called basicExample with the base package being cloud.osasoft.micronaut.example</p><h3>Set up Micronaut Data for usage with MySQL</h3><p>Next up, let’s get the dependencies we’ll need. These are going to be the dependencies for Micronaut Data nad MySQL.</p><p>Set the Micronaut Data version in gradle.properties by adding the following line:</p><pre>micronautDataVersion=1.0.0.M1</pre><p>and let’s add these dependencies to our build.gradle :</p><pre>compileOnly &quot;io.micronaut.data:micronaut-data-processor:$micronautDataVersion&quot;<br>implementation &quot;io.micronaut.data:micronaut-data-jdbc:$micronautDataVersion&quot;<br>runtimeOnly &quot;io.micronaut.configuration:micronaut-jdbc-tomcat&quot;<br>compileOnly &#39;jakarta.persistence:jakarta.persistence-api:2.2.2&#39;<br>implementation &#39;mysql:mysql-connector-java:8.0.17&#39;<br>implementation &quot;io.micronaut.configuration:micronaut-jdbc-hikari&quot;</pre><p>In brief, above we have the dependencies for Micronaut Data itself and then we have the MySQL Java connector and Hikari for connection pooling.</p><p>In application.yml we can now set up the connection simply with</p><pre>datasources:<br>  default:<br>    url: jdbc:mysql://localhost:3306/example<br>    username: sa<br>    password: sa<br>    dialect: MYSQL</pre><h3>Set up Liquibase for migrations (and using Groovy DSL)</h3><p>Next, we want to get Liquibase up and running to handle our database migrations. Since I prefer the Groovy DSL for Liquibase over XML, I’ll also be adding the liquibase-groovy-dsl library. We just add the following dependencies:</p><pre>implementation &#39;io.micronaut.configuration:micronaut-liquibase&#39;<br>implementation &#39;org.liquibase:liquibase-groovy-dsl:2.0.3&#39;</pre><h4>Create root changelog file</h4><p>Now let’s create the default root changelog file. Let’s create it as resources/db/liquibase-changelog.groovy :</p><pre>package db<br><br>databaseChangeLog <strong>{<br></strong><br><strong>}</strong></pre><p>and leave it empty for now. In here we will reference the migration changelog files we want applied. At the time of writing, to my knowledge there is no support for auto-generated changelogs for Micronaut Data, such like what is provided by the Grails Liquibase plugin for GORM, so any migration files we will have to write ourselves, but thats later.</p><h4>Configure Liquibase</h4><p>In order for the Liquibase migrations to run, we need to configure them in application.yml</p><pre>jpa:<br>  default:<br>    properties:<br>      hibernate:<br>        hbm2ddl:<br>          auto: validate<br><br>liquibase:<br>  datasources:<br>    default:<br>      change-log: &#39;classpath:db/liquibase-changelog.groovy&#39;</pre><p>The JPA configuration part just tells Hibernate not to do any changes to the DB based on the model, we want to leave that to Liquibase. auto:none is also a valid option here.<br>Liquibase config just points it to our created root changelog file.</p><p>At this point, if we run the app, we should see some output from Liquibase as it creates the DATABASECHANGELOG and other tables it uses to keep track of our migrations.</p><pre>16:56:57.101 [main] INFO  liquibase.executor.jvm.JdbcExecutor - SELECT * FROM `example`.DATABASECHANGELOG ORDER BY DATEEXECUTED ASC, ORDEREXECUTED ASC<br>16:56:57.102 [main] INFO  liquibase.executor.jvm.JdbcExecutor - SELECT COUNT(*) FROM `example`.DATABASECHANGELOGLOCK<br>16:56:57.107 [main] INFO  l.lockservice.StandardLockService - Successfully released change log lock<br>16:56:57.512 [main] INFO  io.micronaut.runtime.Micronaut - Startup completed in 2290ms. Server Running: <a href="http://localhost:8080/">http://localhost:8080</a></pre><h4>Create a basic entity</h4><p>Now let’s create our first migration. For that, lets create a simple entity Person.groovy</p><pre>@Entity<br>@CompileStatic<br>class Player {<br><br>    @Id<br>    @AutoPopulated<br>    UUID id<br><br>    @DateCreated<br>    Date dateCreated<br><br>    @DateUpdated<br>    Date dateUpdated<br><br>    String firstName<br>    String lastName<br>    int yearOfBirth<br>}</pre><p>and a migration to go with it in resources/db/migrations.initialSchema.groovy</p><pre>package db.migrations<br><br>databaseChangeLog <strong>{<br>    </strong>changeSet(author: &quot;oscar&quot;, id: &quot;1&quot;) <strong>{<br>        </strong>createTable(tableName: &quot;person&quot;) <strong>{<br>            </strong>column(name: &quot;id&quot;, type: &quot;UUID&quot;) <strong>{<br>                </strong>constraints(primaryKey: &quot;true&quot;)<br>            <strong>}<br><br>            </strong>column(name: &quot;date_created&quot;, type: &quot;DATETIME&quot;) <strong>{<br>                </strong>constraints(nullable: &quot;false&quot;)<br>            <strong>}<br>            </strong>column(name: &quot;date_updated&quot;, type: &quot;DATETIME&quot;) <strong>{<br>                </strong>constraints(nullable: &quot;false&quot;)<br>            <strong>}<br><br>            </strong>column(name: &quot;first_name&quot;, type: &quot;VARCHAR(50)&quot;)</pre><pre>            column(name: &quot;last_name&quot;, type: &quot;VARCHAR(50)&quot;)</pre><pre>            column(name: &quot;year_of_birth&quot;, type: &quot;INT&quot;) <strong>{<br>                </strong>constraints(nullable: &quot;false&quot;)<br>            <strong>}<br>        }<br>    }<br>}</strong></pre><p>and let the root changelog know we want to apply this migration</p><pre>package db<br><br>databaseChangeLog <strong>{<br>    </strong>include file: &#39;migrations/initialschema.groovy&#39;, relativeToChangelogFile: true<br><strong>}</strong></pre><p>Running the app now, we should see Liquibase creating the new table</p><pre>17:08:37.251 [main] INFO  liquibase.changelog.ChangeSet - Table person created<br>17:08:37.251 [main] INFO  liquibase.changelog.ChangeSet - ChangeSet classpath:db/migrations/initialschema.groovy::1::oscar ran successfully in 14ms</pre><p>With this, our basic app is ready to go! Now let’s set up tests.</p><h3>Add and configure Testcontainers and Spock</h3><p>I use Spock as my testing framework of choice, but Junit config should be fairly similar. Testcontainers are great in that it allows our tests to run against the actual DB implementation the final product will, so we can avoid some incompatibility issues with, for example, H2 that might pop up.</p><p>First, let’s add the Testcontainers Spock and MySQL dependencies</p><pre>testCompile &quot;org.testcontainers:spock:1.12.1&quot;<br>testCompile &quot;org.testcontainers:mysql:1.12.1&quot;</pre><p>and let’s create a very basic test, just to see that our application context starts up properly</p><pre>@MicronautTest<br>class ExampleApplicationTest extends Specification {<br><br>    @Inject<br>    ApplicationContext applicationContext<br><br>    void setup() {<br>    }<br><br>    void cleanup() {<br>    }<br><br>    def &quot;Application starts&quot;() {<br>        expect:<br>            applicationContext<br>    }<br>}</pre><p>If we run the test now, it will try and connect to the same database we defined previously, so let’s create a test config under test resources called application-test.yml</p><pre>datasources:<br>  default:<br>    url: jdbc:tc:mysql://localhost/test<br>    driverClassName: org.testcontainers.jdbc.ContainerDatabaseDriver<br>    username: test<br>    password: test</pre><p>Since the url contains :tc:mysql and we specified the driver being Testcontainers, a Docker image of MySQL will be spun up automatically along with the application context, and the app will connect to it. test:test are the default credentials for Testcontainers MySQL image. You can configure these as well as the MySQL version to be used (see the <a href="https://www.testcontainers.org/modules/databases/mysql/">docs</a>)</p><p>Running the test now, we should see a happy whale in the output:</p><pre>17:25:56.606 [Test worker] INFO  🐳 [mysql:5.7.22] - Container mysql:5.7.22 started</pre><p>And there we have it. A fully functional skeleton of a Micronaut + Micronaut Data application with Liquibase migrations and Testcontainers for our database during testing.</p><h4>Sources</h4><p>Here’s a (nonexhaustive) list of sources I used when setting the whole thing up:</p><p><a href="https://docs.micronaut.io/latest/guide/index.html">https://docs.micronaut.io/latest/guide/index.html</a><a href="https://micronaut-projects.github.io/micronaut-data/1.0.x/guide/"><br>https://micronaut-projects.github.io/micronaut-data/1.0.x/guide/</a><br><a href="https://micronaut-projects.github.io/micronaut-liquibase/latest/guide/index.html">https://micronaut-projects.github.io/micronaut-liquibase/latest/guide/index.html</a><br><a href="https://www.testcontainers.org/modules/databases/">https://www.testcontainers.org/modules/databases/</a><br><a href="https://www.liquibase.org/quickstart/quickstart_lb.html">https://www.liquibase.org/quickstart/quickstart_lb.html</a><br><a href="https://github.com/micronaut-projects/micronaut-data/tree/master/examples">https://github.com/micronaut-projects/micronaut-data/tree/master/examples</a><br><a href="https://github.com/micronaut-projects/micronaut-examples">https://github.com/micronaut-projects/micronaut-examples</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f833e69f289" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Native Mobile Facebook Authentication for a REST Grails 3 application with Spring Security…]]></title>
            <link>https://medium.com/@Osa_Soft/using-native-mobile-facebook-authentication-for-a-rest-grails-3-application-with-spring-security-9532c3cf1850?source=rss-2f3be2e87efa------2</link>
            <guid isPermaLink="false">https://medium.com/p/9532c3cf1850</guid>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[groovy]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[facebook]]></category>
            <category><![CDATA[grails]]></category>
            <dc:creator><![CDATA[Oscar Hernandez]]></dc:creator>
            <pubDate>Tue, 20 Mar 2018 15:33:59 GMT</pubDate>
            <atom:updated>2018-03-20T15:33:59.490Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h3>Using Native Mobile Facebook Authentication for a REST Grails 3 application with Spring Security Rest</h3><p>If you only care about the code, check out the full Gist on <a href="https://medium.com/u/8df3bf3c40ae">GitHub</a>: <a href="https://gist.github.com/OsaSoft/d805672062deb0da277267ca4d86b335">https://gist.github.com/OsaSoft/d805672062deb0da277267ca4d86b335</a></p><p>Sometimes while working on either job-related, study-related or hobby-related projects, I come onto problems that not even <a href="https://medium.com/u/d53dd768d047">Stack Overflow</a> seems to be able to solve for me, or the answer I find needs a little more explanation and elaboration. For problems like these I have decided a few times in the past to post some Gists on <a href="https://medium.com/u/8df3bf3c40ae">GitHub</a>, hoping to help whoever might stumble upon my code, searching for a solution to the same, or a very similar problem. However, now I feel that Gists are not always fully self explanatory, and so have decided to, over time, write some more detailed posts about my adventures in Codeland. Here’s my first attempt at doing so.</p><p>I have been in love with Grails since I first got my hands on doing support work on an old Grails 1.3.7 project at my job. As a framework it was elegant with no need of extensive piles of xml configurations just to get a Hello World working, the structure was well organised and along with features coming from the use of the Groovy language it just blew me away. That is why ever since, whenever I had full control over the technologies I’d use in a new project, Grails has always been my first choice. For these reasons too, when I started working on a project for a student app at my university, Grails 3 with the REST profile was a no-brainer. The app, written in React native, would call the backend API and all would be good, right?</p><p>Well here is the problem I stumbled upon: In order to secure access to the backend’s API endpoints, I decided to use Spring Security, along with the amazing Spring Security Rest plugin by <a href="https://medium.com/u/d41273300566">Álvaro Sánchez-Mariscal</a>. However, since the frontend would be a smartphone app, it would be great if we could use the native Facebook login, where the app takes an access token from the Facebook app and uses that to authenticate.</p><p>However, the Spring Security Rest plugin only supports Facebook login using oAuth, which is more fit to be used with a JS frontend and uses redirect chains. So, what can be done to use Facebook’s native mobile login, which creates a Facebook Access Token?</p><p>The basic idea goes like this:</p><ol><li>Mobile app uses Facebook’s native login and gets Facebook Access Token</li><li>Mobile app passes the Facebook Access Token to the backend app.</li><li>Backend app uses Facebook Access Token to pull user information from Facebook’s API and creates/logs in user based on it.</li><li>Backend app logs in the user internally and generates an oAuth acess_token, refresh_token pair</li><li>Backend app sends oAuth tokens back to the mobile app.</li><li>Mobile app uses oAuth tokens to authenticate with backend app on any subsequent API calls.</li></ol><p>Let’s start with the relevant parts in our <strong><em>User</em></strong> class (the one generated by Spring Security). For convenience, let’s add a comma separated list of fields we want to access from the Facebook user (mind that in order to get them, the relevant permissions must be requested and granted in the mobile part of the login):</p><pre>static final facebookFields = &quot;id,email,first_name,last_name,picture&quot;</pre><p>Here we’re just going to get some very basic information, you can see the full list of available fields over at Facebook’s docs <a href="https://developers.facebook.com/docs/graph-api/reference/v2.2/user">(https://developers.facebook.com/docs/graph-api/reference/v2.2/user</a>)</p><p>Next, we want to be able to create a User object:</p><pre>static User facebookLogin(FacebookUserInfo fbInfo) {<br>	def user = findByUsername(fbInfo.id)<br>	boolean isNew = false<br>	if (!user) { //user doesnt exist yet<br>		isNew = true<br>		user = new User(username: fbInfo.id, password: RandomStringUtils.randomAlphanumeric(16))<br><br>	}<br>	user.with { //or other fields you want<br>		firstname = fbInfo.firstname<br>		lastname = fbInfo.lastname<br>		fbPictureUrl = fbInfo.profilePictureUrl<br>	}<br><br>	if (user.isDirty() || isNew) { //if any fields changed or is a new user, save<br>		user.save(flush: true)<br>	}<br><br>	if (!user.hasErrors()) { //give user roles if user saved properly<br>		def userRole = Role.findByAuthority(&quot;ROLE_USER&quot;)<br>		def facebookRole = Role.findByAuthority(&quot;ROLE_FACEBOOK&quot;)<br><br>		if (!user.authorities.contains(userRole)) UserRole.create(user, userRole, true)<br>		if (!user.authorities.contains(facebookRole)) UserRole.create(user, facebookRole, true)<br>		}<br><br>	user<br>}</pre><p>So, what’s going on here: We pass this method a FacebookUserInfo, which is just a data container POGO with the fields we want, in this case id,email,firstname,lastname and profilePictureUrl. We try to find a user with the same Facebook id and create a new one with the passed data in case we cant find an existing user. Then we just update the data, as things such as name, picture and others might change between logins and we want to keep our end as up to date as possible. Finally we add all the roles the user is supposed to have, if they don’t have them yet.</p><p>Okay, so far so good.</p><p>Next let’s create a FacebookService that will take care of communicating with Facebook’s API. We add values for Facebook’s API url and our app key to load from config:</p><pre>@Value(‘${facebook.graph.api.url}’) String fbApiUrl @Value(‘${facebook.graph.api.key}’) String fbAppId</pre><p>Add in a RESTClient and inilize it to Facebook’s API url</p><pre>RESTClient client<br><br>@PostConstruct<br>void init() {<br>    client = new RESTClient(fbApiUrl)<br>}</pre><p>Next, we add themethod that will call the API to get all the user information:</p><pre>def getUserInfo(String fbAcessToken) {<br>    def resp = client.get(path: &quot;me&quot;, query: [access_token: fbAcessToken, fields: User.facebookFields])<br>    if (resp.status != 200) {<br>       log.error &quot;Error getting user information! $resp.status: $resp.data&quot;<br>    } else {<br>       resp.data<br>    }<br>}</pre><p>Note we’re getting User.facebookFields here. I take them from the static field we defined in our User class, since I want the fields be same for all situations, but you could pull them out of a dabase, config file, etc.</p><p>We also want another method here, to check if the access token we got is for our app:</p><pre>boolean isTokenForApp(String fbAccessToken) {<br>    def resp = client.get(path: &quot;app&quot;, query: [access_token: fbAccessToken])<br><br>    resp.status == 200 &amp;&amp; resp.data.id == fbAppId<br>}</pre><p>Ok, so we’ve got the foundation done. We can get user information from Facebook based on a valid access token and we can create a User based on the info we get. Now to put it all together under an endpoint that our app can call. Let’s put this under a FacebookController</p><pre>@Secured(&quot;permitAll&quot;)<br>class FacebookController {<br>   static <em>responseFormats </em>= [&#39;json&#39;]<br>   static <em>allowedMethods </em>= [auth: &quot;POST&quot;]<br><br>   def restAuthenticationEventPublisher<br>   def userDetailsService<br>   def tokenGenerator<br>   def tokenStorageService<br>   def accessTokenJsonRenderer<br><br>   def facebookService</pre><p>Let’s quickly go through the beans we want injected here.</p><ul><li>restAuthenticationEventPublisher will pass our authentication token to all relevant parts of the authentication system, so that our app will be able to authenticate with our own oAuth tokens</li><li>userDetailsService will get us the UserDetails object we will need to create our tokens</li><li>tokenGenerator will generate our tokens</li><li>tokenStorageService will store our tokens</li><li>accessTokenJsonRenderer will, you guessed it, render our tokens as a json</li><li>facebookService should feel familiar</li></ul><p>Now for the authentication method itself:</p><pre>def auth() {<br>   def fbToken = request.JSON?.fb_access_token<br>   if (!facebookService.isTokenForApp(fbToken)) {<br>      respond([error: &quot;Incorrect app access token&quot;], status: HttpStatus.<em>UNAUTHORIZED</em>)<br>      return<br>   }<br><br>   def userInfo = facebookService.getUserInfo(fbToken)<br><br>   if (!userInfo?.id) { //something went wrong<br>      respond([error: userInfo?.error], status: HttpStatus.<em>UNAUTHORIZED</em>)<br>      return<br>   }<br><br>   userInfo = new FacebookUserInfo(<br>         id: userInfo.id,<br>         email: userInfo.email,<br>         firstname: userInfo.first_name,<br>         lastname: userInfo.last_name,<br>         profilePictureUrl: userInfo.picture?.data?.url<br>   )<br><br>   User user = User.<em>facebookLogin</em>(userInfo)<br><br>   if (!user || user.hasErrors()) {<br>      respond([error: [message: &quot;persist error&quot;, errors: user.errors]], status: HttpStatus.<em>INTERNAL_SERVER_ERROR</em>)<br>      return<br>   }</pre><p>So far so good. We get the Facebook Access Token from the json payload in the request, check whether it is a valid token for our app and get user info from Facebook and based on it get an existing or new <strong><em>User.</em></strong></p><p>Now all we need to do is get the rest of the system know we’ve authenticated a user, create some authentications token for them and register those. Finally, we’ll send them back to our mobile app:</p><pre>def userDetails = userDetailsService.loadUserByUsername(user.username)<br><br>   AccessToken accessToken = tokenGenerator.generateAccessToken(userDetails)<br>   tokenStorageService.storeToken(accessToken.accessToken, userDetails)<br><br>   restAuthenticationEventPublisher.publishTokenCreation(accessToken)<br><br>   SecurityContextHolder.<em>context</em>.setAuthentication(accessToken)<br><br>   render contentType: &#39;application/json&#39;, encoding: &#39;UTF-8&#39;, text: accessTokenJsonRenderer.generateJson(accessToken)<br>}</pre><p>Now for the final touch. Since we are using the REST profile and a unconventional url for the authentication endpoint, we have to set it up in UrlMappings</p><pre>class UrlMappings {<br><br>    static <em>mappings </em>= {<br>        post &quot;/facebook/auth(.$format)?&quot;(controller: &quot;facebook&quot;, action: &quot;auth&quot;)<br>    }<br>}</pre><p>And that’s it! Now we can use Facebook’s native mobil login in our Grails 3 REST application.</p><p>I hope this helps whoever finds it. If you find any mistakes or possible improvements, please let me know. You can find me on Twitter as Osa_Soft or on <a href="https://medium.com/u/8df3bf3c40ae">GitHub</a> as OsaSoft.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9532c3cf1850" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>