Show Spring-Boot Auto-Configuration-Report When Running Via “mvn spring-boot:run”

There are a lot of explanations, how to turn on the Auto-Configuration-Report offered by Spring-Boot to debug the configuration of ones app.
For an good example take a look at this little Spring boot troubleshooting auto-configuration guide.
But most often, when I want to see the Auto-Configuration-Report, I am running my app via mvn:spring-boot:run.
And, unfortunatly, none of the guids you can find by google tells you, how to turn on the Auto-Configuration-Report in this case.
Hence, I hope I can help out, with this little tip.

How To Turn On The Auto-Configuration-Report When Running mvn spring-boot:run

The report is shown, if the logging for org.springframework.boot.autoconfigure.logging is set to DEBUG.
The most simple way to do that, is to add the following line to your src/main/resources/application.properties:

logging.level.org.springframework.boot.autoconfigure.logging=DEBUG

I was not able, to enable the logging via a command-line-switch.
The seemingly obvious way to add the property to the command line with a -D like this:

mvn spring-boot:run -Dlogging.level.org.springframework.boot.autoconfigure.logging=DEBUG

did not work for me.
If anyone could point out, how to do that in a comment to this post, I would be realy grateful!

Funded by the Europian Union

This article was published in the course of a
resarch-project,
that is funded by the European Union and the federal state Northrhine-Wetphalia.


Europäische Union: Investitionen in unsere Zukunft - Europäischer Fonds für regionale Entwicklung
EFRE.NRW 2014-2020: Invesitionen in Wachstum und Beschäftigung

Problems Deploying A Spring-Boot-App As WAR

Spring-Boot-App Is Not Started, When Deployed As WAR

Recently, I had a lot of trouble, deploying my spring-boot-app as war under Tomcat 8 on Debian Jessie.
The WAR was found and deployed by tomcat, but it was never started.
Browsing the URL of the app resulted in a 404.
And instead of the fancy Spring-Boot ASCII-art banner, the only matching entry that showed up in my log-file was:

INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log Spring WebApplicationInitializers detected on classpath: [org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration$JerseyWebApplicationInitializer@1fe086c]

A blog-post from Stefan Isle lead me to the solution, what was going wrong.
In my case, there was no wrong version of Spring on the classpath.
But my WebApplicationInitializer was not found, because I had it compiled with a version of Java, that was not available on my production system.

WebApplicationInitializer Not Found Because Of Wrong Java Version

On my development box, I had compiled and tested the WAR with Java 8.
But on my production system, running Debian 8 (Jessie), only Java 7 was available.
And because of that, my WebApplicationInitializer

After installing Java 8 from debian-backports on my production system, like described in this nice debian-upgrade note, the WebApplicationInitializer of my App was found and everything worked like a charme, again.

Funded by the Europian Union

This article was published in the course of a
resarch-project,
that is funded by the European Union and the federal state Northrhine-Wetphalia.


Europäische Union: Investitionen in unsere Zukunft - Europäischer Fonds für regionale Entwicklung
EFRE.NRW 2014-2020: Invesitionen in Wachstum und Beschäftigung

Develop a Facebook-App with Spring-Social – Part VII: What is Going On On The Wire

In this series of Mini-How-Tow’s I will describe how to develop a facebook app with the help of Spring-Social

In the last part of this series, I showed you, how you can sign-in your users through the signed_request, that is send to your canvas-page.

In this part, I will show you, how to turn on logging of the HTTP-requests, that your app sends to, and the -responses it recieves from the Facebook Graph-API.

The Source is With You

You can find the source-code on http://juplo.de/git/examples/facebook-app/
and browse it via gitweb.
Check out part-07 to get the source for this part of the series.

Why You Want To Listen On The Wire

If you are developing your app, you will often wonder, why something does not work as expected.
In this case, it is often very usefull to be able to debug the communitation between your app and the Graph-API.
But since all requests to the Graph-API are secured by SSL you can not simply listen in with tcpdump or wireshark.

Fortunately, you can turn on the debugging of the underling classes, that process theses requests, to sidestep this problem.

Introducing HttpClient

In its default-configuration, the Spring Framework will use the HttpURLConnection, which comes with the JDK, as http-client.
As described in the documentation, some advanced methods are not available, when using HttpURLConnection
Besides, the package HttpClient, which is part of Apaches HttpComponents is a much more mature, powerful and configurable alternative.
For example, you easily can plug in connection pooling, to speed up the connection handling, or caching to reduce the amount of requests that go through the wire.
In production, you should always use this implementation, instead of the default-one, that comes with the JDK.

Hence, we will switch our configuration to use the HttpClient from Apache, before turning on the debug-logging.

Switching From Apaches HttpCompnents To HttpClient

To siwtch from the default client, that comes with the JDK to Apaches HttpClient, you have to configure an instance of HttpComponentsClientHttpRequestFactory as HttpRequestFactory in your SocialConfig:

@Bean
public HttpComponentsClientHttpRequestFactory requestFactory(Environment env)
{
  HttpComponentsClientHttpRequestFactory factory =
      new HttpComponentsClientHttpRequestFactory();
  factory.setConnectTimeout(
      Integer.parseInt(env.getProperty("httpclient.timeout.connection"))
      );
  factory.setReadTimeout(
      Integer.parseInt(env.getProperty("httpclient.timeout.read"))
      );
  return factory;
}

To use this configuration, you also have to add the dependency org.apache.httpcomonents:httpclient in your pom.xml.

As you can see, this would also be the right place to enable other specialized configuration-options.

Logging The Headers From HTTP-Requests And Responses

I configured a short-cut to enable the logging of the HTTP-headers of the communication between the app and the Graph-API.
Simply run the app with the additionally switch -Dhttpclient.logging.level=DEBUG

Take Full Control

If the headers are not enough to answer your questions, you can enable a lot more debugging messages.
You just have to overwrite the default logging-levels.
Read the original documentation of HttpClient, for more details.

For example, to enable logging of the headers and the content of all requests, you have to start your app like this:

mvn spring-boot:run \
    -Dfacebook.app.id=YOUR_ID \
    -Dfacebook.app.secret=YOUR_SECRET \
    -Dfacebook.app.canvas=https://apps.facebook.com/YOUR_NAMESPACE
    -Dlogging.level.org.apache.http=DEBUG \
    -Dlogging.level.org.apache.http.wire=DEBUG

The second switch is necessary, because I defined the default-level ERROR for that logger in our src/main/application.properties, to enable the short-cut for logging only the headers.

Funded by the Europian Union

This article was published in the course of a
resarch-project,
that is funded by the European Union and the federal state Northrhine-Wetphalia.


Europäische Union: Investitionen in unsere Zukunft - Europäischer Fonds für regionale Entwicklung
EFRE.NRW 2014-2020: Invesitionen in Wachstum und Beschäftigung

Develop a Facebook-App with Spring-Social – Part VI: Sign In Users Through The Canvas-Page

In this series of Mini-How-Tow’s I will describe how to develop a facebook app with the help of Spring-Social

In the last part of this series, we refactored our authentication-concept, so that it can be replaced by Spring Security later on more easy.

In this part, we will turn our app into a real Facebook-App, that is rendered inside Facebook and signs in users through the signed_request.

The Source is With You

You can find the source-code on http://juplo.de/git/examples/facebook-app/
and browse it via gitweb.
Check out part-06 to get the source for this part of the series.

What The *#&! Is a signed_request

If you add the platform Facebook Canvas to your app, you can present your app inside of Facebook.
It will be accessible on a URL like https://apps.facebook.com/YOUR_NAMESPACE then and if a (known!) user accesses this URL, facebook will send a signed_request, that already contains some data of this user an an authorization to retrieve more.

Sign In Users With signed_request In 5 Simple Steps

As I first tried to extend the simple example, this article-series is based on, I stumbled across multiple misunderstandings.
But now, as I guided you around all that obstacles, it is fairly easy to refine our app, so that is can sign in users through the signed_request, send to a Canvas-Page.

You just have to:

  1. Add the platform “Facebook Canvas” in the settings of your app and choose a canvas-URL.
  2. Reconfigure your app to support HTTPS, because Facebook requires the canvas-URL to be secured by SSL.
  3. Configure the CanvasSignInController.
  4. Allow the URL of the canvas-page to be accessed unauthenticated.
  5. Enable Sign-Up throw your canvas-page.

That is all, there is to do.
But now, step by step…

Step 1: Turn Your App Into A Canvas-Page

Go to the settings-panel of your app on https://developers.facebook.com/apps and click on Add Platform.
Choose Facebook Canvas.
Pick a secure URL, where your app will serve the canvas-page.

For example: https://localhost:8443.

Be aware, that the URL has to be publicly available, if you want to enable other users to access your app.
But that also counts for the Website-URL http://localhost:8080, that we are using already.

Just remember, if other people should be able to access your app later, you have to change these URL’s to something, they can access, because all the content of your app is served by you, not by Facebook.
A Canvas-App just embedds your content in an iFrame inside of Facebook.

Step 2: Reconfigure Your App To Support HTTPS

Add the following lines to your src/main/resources/application.properties:

server.port: 8443
server.ssl.key-store: keystore
server.ssl.key-store-password: secret

I have included a self-signed keystore with the password secret in the source, that you can use for development and testing.
But of course, later, you have to create your own keystore with a certificate that is signed by an official certificate authority, that is known by the browsers of your users.

Since your app now listens on 8443 an uses HTTPS, you have to change the URL, that is used for the platform “Website”, if you want your sign-in-page to continue to work in parallel to the sign-in through the canvas-page.

For now, you can simply change it to https://locahost:8443/ in the settings-panel of your app.

Step 3: Configure the CanvasSignInController

To actually enable the automatic handling of the signed_request, that is, decoding the signed_request and sign in the user with the data provided in the signed_request, you just have to add the CanvasSignInController as a bean in your SocialConfig:

@Bean
public CanvasSignInController canvasSignInController(
    ConnectionFactoryLocator connectionFactoryLocator,
    UsersConnectionRepository usersConnectionRepository,
    Environment env
    )
{
  return
      new CanvasSignInController(
          connectionFactoryLocator,
          usersConnectionRepository,
          new UserCookieSignInAdapter(),
          env.getProperty("facebook.app.id"),
          env.getProperty("facebook.app.secret"),
          env.getProperty("facebook.app.canvas")
          );
}

Step 4: Allow the URL Of Your Canvas-Page To Be Accessed Unauthenticated

Since we have “secured” all of our pages except of our sign-in-page /signin*, so that they can only be accessed by an authenticated user, we have to explicitly allow unauthenticated access to our new special sign-in-page.

To achieve that, we have to refine our UserCookieInterceptor as follows.
First add a pattern for all pages, that are allowed to be accessed unauthenticated:

private final static Pattern PATTERN = Pattern.compile("^/signin|canvas");

Then match the requests against this pattern, instead of the fixed string /signin:

if (PATTERN.matcher(request.getServletPath()).find())
  return true;

Step 5: Enable Sign-Up Through Your Canvas-Page

Facebook always sends a signed_request to your app, if a user visits your app through the canvas-page.
But on the first visit of a user, the signed_request does not authenticate the user.
In this case, the only data that is presented to your page is the language and locale of the user and his or her age.

Because the data, that is needed to sign in the user, is missing, the CanvasSignInController will issue an explicit authentication-request to the Graph-API via a so called Server-Side Log-In.
This process includes a redirect to the Login-Dialog of Facebook and then a second redirect back to your app.
It requires the specification of a full absolute URL to redirect back to.

Since we are configuring the canvas-login-in, we want, that new users are redirected to the canvas-page of our app.
Hence, you should use the Facebook-URL of your app: https://apps.facebook.com/YOUR_NAMESPACE.
This will result in a call to your canvas-page with a signed_request, that authenticates the new user, if the user accepts to share the requested data with your app.

Any other page of your app would work as well, but the result would be a call to the stand-alone version of your app (the version of your app that is called the “Website”-platform of your app by Facebook), meaning, that your app is not rendered inside of Facebook.
Also it requires one more call of your app to the Graph-API to actually sign-in the new user, because Facebook sends the signed_request only the canvas-page of your app.

To specify the URL I have introduced a new attribute facebook.app.canvas that is handed to the CanvasSignInController.
You can specifiy it, when starting your app:

mvn spring-boot:run \
    -Dfacebook.app.id=YOUR_ID \
    -Dfacebook.app.secret=YOUR_SECRET \
    -Dfacebook.app.canvas=https://apps.facebook.com/YOUR_NAMESPACE

Be aware, that this process requires the automatic sign-up of new users, that we enabled in part 3 of this series.
Otherwise, the user would be redirected to the sign-up-page of your application, after he allowed your app to access the requested data.
Obviously, that would be very confusing for the user, so we really nead automati sign-up in this use-case!

Coming Next…

In the next part of this series, I will show you, how you can debug the calls, that Spring Social makes to the Graph-API, by turning on the debugging of the classes, that process the HTTP-requests and -responses, that your app is making.

Funded by the Europian Union

This article was published in the course of a
resarch-project,
that is funded by the European Union and the federal state Northrhine-Wetphalia.


Europäische Union: Investitionen in unsere Zukunft - Europäischer Fonds für regionale Entwicklung
EFRE.NRW 2014-2020: Invesitionen in Wachstum und Beschäftigung

Develop a Facebook-App with Spring-Social – Part V: Refactor The Redirect-Logic

In this series of Mini-How-Tow’s I will describe how to develop a facebook app with the help of Spring-Social

In the last part of this series, we reconfigured our app, so that users are signed in after an authentication against Facebook and new users are signed up automatically on the first visit.

In this part, we will refactor our redirect-logic for unauthenticated users, so that it more closely resembles the behavior of Spring Social, hence, easing the planed switch to that technology in a feature step.

The Source is With You

You can find the source-code on http://juplo.de/git/examples/facebook-app/
and browse it via gitweb.
Check out part-05 to get the source for this part of the series.

Mimic Spring Security

To stress that again: our simple authentication-concept is only meant for educational purposes. It is inherently insecure!
We are not refining it here, to make it better or more secure.
We are refining it, so that it can be replaced with Spring Security later on, without a hassle!

In our current implementation, a user, who is not yet authenticated, would be redirected to our sign-in-page only, if he visits the root of our webapp (/).
To move all redirect-logic out of HomeController and redirect unauthenicated users from all pages to our sign-in-page, we can simply modify our interceptor UserCookieInterceptor, which already intercepts each and every request.

We refine the method preHandle, so that it redirects every request to our sign-in-page, that is not authenticated:

@Override
public boolean preHandle(
    HttpServletRequest request,
    HttpServletResponse response,
    Object handler
    )
    throws
      Exception
{
  if (request.getServletPath().startsWith("/signin"))
    return true;

  String user = UserCookieGenerator.INSTANCE.readCookieValue(request);
  if (user != null)
  {
    if (!repository
        .findUserIdsConnectedTo("facebook", Collections.singleton(user))
        .isEmpty()
        )
    {
      LOG.info("loading user {} from cookie", user);
      SecurityContext.setCurrentUser(user);
      return true;
    }
    else
    {
      LOG.warn("user {} is not known!", user);
      UserCookieGenerator.INSTANCE.removeCookie(response);
    }
  }

  response.sendRedirect("/signin.html");
  return false;
}

If the user, that is identified by the cookie, is not known to Spring Security, we send a redirect to our sign-in-page and flag the request as already handled, by returning false.
To prevent an endless loop of redirections, we must not redirect request, that were already redirected to our sign-in-page.
Since these requests hit our webapp as a new request for the different location, we can filter out and wave through at the beginning of this method.

Run It!

That is all there is to do.
Run the app and call the page http://localhost:8080/profile.html as first request.
You will see, that you will be redirected to our sigin-in-page.

Cleaning Up Behind Us…

As it is now not possible, to call any page except the sigin-up-page, without beeing redirected to our sign-in-page, if you are not authenticated, it is impossible to call any page without being authenticated.
Hence, we can (and should!) refine our UserIdSource, to throw an exception, if that happens anyway, because it has to be a sign for a bug:

public class SecurityContextUserIdSource implements UserIdSource
{

  @Override
  public String getUserId()
  {
    Assert.state(SecurityContext.userSignedIn(), "No user signed in!");
    return SecurityContext.getCurrentUser();
  }
}

Coming Next…

In the next part of this series, we will enable users to sign in through the canvas-page of our app.
The canvas-page is the page that Facebook embeds into its webpage, if we render our app inside of Facebook.

Funded by the Europian Union

This article was published in the course of a
resarch-project,
that is funded by the European Union and the federal state Northrhine-Wetphalia.


Europäische Union: Investitionen in unsere Zukunft - Europäischer Fonds für regionale Entwicklung
EFRE.NRW 2014-2020: Invesitionen in Wachstum und Beschäftigung

Develop a Facebook-App with Spring-Social – Part IV: Signing In Users

In this series of Mini-How-Tow’s I will describe how to develop a facebook app with the help of Spring-Social

In the last part of this series, we tried to teach Spring Social how to remember our signed in users and learned, that we have to sign in a user first.

In this part, I will show you, how you sign (and automatically sign up) users, that are authenticated via the Graph-API.

The Source is With You

You can find the source-code on http://juplo.de/git/examples/facebook-app/
and browse it via gitweb.
Check out part-04 to get the source for this part of the series.

In Or Up? Up And In!

In the last part of our series we ran in the problem, that we wanted to connect several (new) users to our application.
We tried to achieve that, by extending our initial configuration.
But the mistake was, that we tried to connect new users.
In the world of Spring Social we can only connect a known user to a new social service.

To know a user, Spring Social requires us to sign in that user.
But again, if you try to sign in a new user, Spring Social requires us to sign up that user first.
Because of that, we had already implemented a ConnectionSignUp and configured Spring Social to call it, whenever it does not know a user, that was authenticated by Facebook.
If you forget that (or if you remove the according configuration, that tells Spring Social to use our ConnectionSignUp), Spring Social will redirect you to the URL /signup — a Sign-Up page you have to implement — after a successfull authentication of a user, that Spring Social does not know yet.

The confusion — or, to be honest, my confusion — about sign in and sign up arises from the fact, that we are developing a Facebook-Application.
We do not care about signing up users.
Each user, that is known to Facebook — that is, who has signed up to Facebook — should be able to use our application.
An explicit sign-up to our application is not needed and not wanted.
So, in our use-case, we have to implement the automatically sign-up of new users.
But Spring Social is designed for a much wider range of use cases.
Hence, it has to distinguish between sign-in and sign-up.

Implementation Of The Sign-In

Spring Social provides the interface SignInAdapter, that it calls every time, it has authenticated a user against a social service.
This enables us, to be aware of that event and remember the user for subsequent calls.
Our implementation stores the user in our SecurityContext to sign him in and creates a cookie to remember him for subsequent calls:

public class UserCookieSignInAdapter implements SignInAdapter
{
  private final static Logger LOG =
      LoggerFactory.getLogger(UserCookieSignInAdapter.class);


  @Override
  public String signIn(
      String user,
      Connection connection,
      NativeWebRequest request
      )
  {
    LOG.info(
        "signing in user {} (connected via {})",
        user,
        connection.getKey().getProviderId()
        );
    SecurityContext.setCurrentUser(user);
    UserCookieGenerator
        .INSTANCE
        .addCookie(usSigning In Userser, request.getNativeResponse(HttpServletResponse.class));

    return null;
  }
}

It returns null, to indicate, that the user should be redirected to the default-URL after an successful sign-in.
This URL can be configured in the ProviderSignInController and defaults to /, which matches our use-case.
If you return a string here, for example /welcome.html, the controller would ignore the configured URL and redirect to that URL after a successful sign-in.

Configuration Of The Sign-In

To enable the Sign-In, we have to plug our SignInAdapter into the ProviderSignInController:

@Bean
public ProviderSignInController signInController(
    ConnectionFactoryLocator factoryLocator,
    UsersConnectionRepository repository
    )
{
  ProviderSignInController controller = new ProviderSignInController(
      factoryLocator,
      repository,
      new UserCookieSignInAdapter()
      );
  return controller;
}

Since we are using Spring Boot, an alternative configuration would have been to just create a bean-instance of our implementation named signInAdapter.
Then, the auto-configuration of Spring Boot would discover that bean, create an instance of ProviderSignInController and plug in our implementation for us.
If you want to learn, how that works, take a look at the implementation of the auto-configuration in the class SocialWebAutoConfiguration, lines 112ff.

Run it!

If you run our refined example and visit it after impersonating different facebook-users, you will see that everything works as expected now.
If you visit the app for the first time (after a restart) with a new user, the user is signed up and in automatically and a cookie is generated, that stores the Facebook-ID of the user in the browser.
On subsequent calls, his ID is read from this cookie and the corresponding connection is restored from the persistent store by Spring Social.

Coming Next…

In the next part of this little series, we will move the redirect-if-unknown logic from our HomeController into our UserCookieInterceptor, so that the behavior of our so-called “security”-concept more closely resembles the behavior of Spring Security.
That will ease the migration to that solution in a later step.

Perhaps you want to skip that, rather short and boring step and jump to the part after the next, that explains, how to sign in users by the signed_request, that Facebook sends, if you integrate your app as a canvas-page.

Funded by the Europian Union

This article was published in the course of a
resarch-project,
that is funded by the European Union and the federal state Northrhine-Wetphalia.


Europäische Union: Investitionen in unsere Zukunft - Europäischer Fonds für regionale Entwicklung
EFRE.NRW 2014-2020: Invesitionen in Wachstum und Beschäftigung

Develop a Facebook-App with Spring-Social – Part III: Implementing a UserIdSource

In this series of Mini-How-Tow’s I will describe how to develop a facebook app with the help of Spring-Social

In the last part of this series, I explained, why the nice little example from the Getting-Started-Guide “Accessing Facebook Data” cannot function as a real facebook-app.

In this part, we will try to solve that problem, by implementing a UserIdSource, that tells Spring Social, which user it should connect to the API.

The Source is With You

You can find the source-code on http://juplo.de/git/examples/facebook-app/
and browse it via gitweb.
Check out part-03 to get the source for this part of the series.

Introducing UserIdSource

The UserIdSource is used by Spring Social to ask us, which user it should connect with the social net.
Clearly, to answer that question, we must remeber, which user we are currently interested in!

Remember Your Visitors

In order to remember the current user, we implement a simple mechanism, that stores the ID of the current user in a cookie and retrieves it from there for subsequent calls.
This concept was borrowed — again — from the official code examples.
You can find it for example in the quickstart-example.

It is crucial to stress, that this concept is inherently insecure and should never be used in a production-environment.
As the ID of the user is stored in a cookie, an attacker could simply take over control by sending the ID of any currently connected user, he is interested in.

The concept is implemented here only for educational purposes.
It will be replaced by Spring Security later on.
But for the beginning, it is easier to understand, how Spring Social works, if we implement a simple version of the mechanism ourself.

Pluging in Our New Memory

The internals of our implementation are not of interest.
You may explore them by yourself.
In short, it stores the ID of each new user in a cookie.
By inspecting that cookie, it can restore the ID of the user on subsequent calls.

What is from interest here is, how we can plug in this simple example-mechanism in Spring Social.

Mainly, there are two hooks to do that, that means: two interfaces, we have to implement:

  1. UserIdSource:
    Spring Social uses an instance of this interface to ask us, which users authorizations it should load from its persistent store of user/connection-mappings.
    We already have seen an implementation of that one in the last part of our series.
  2. ConnectionSignUp:
    Spring Social uses an instance of this interface, to ask us about the name it should use for a new user during sign-up.

Implementation

The implementation of ConnectionSignUp simply uses the ID, that is provided by the social network.
Since we are only signing in users from Facebook, these ID’s are guaranteed to be unique.

public class ProviderUserIdConnectionSignUp implements ConnectionSignUp
{
  @Override
  public String execute(Connection connection)
  {
    return connection.getKey().getProviderUserId();
  }
}

The implementation of UserIdSource retrieves the ID, that was stored in the SecurityContext (our simple implementation — not to be confused with the class from Spring Security).
If no user is stored in the SecurityContext, it falls back to the old behavior and returns the fix id anonymous.

public class SecurityContextUserIdSource implements UserIdSource
{
  private final static Logger LOG =
      LoggerFactory.getLogger(SecurityContextUserIdSource.class);


  @Override
  public String getUserId()
  {
    String user = SecurityContext.getCurrentUser();
    if (user != null)
    {
      LOG.debug("found user \"{}\" in the security-context", user);
    }
    else
    {
      LOG.info("found no user in the security-context, using \"anonymous\"");
      user = "anonymous";
    }
    return user;
  }
}

Actual Plumbing

To replace the AnonymousUserIdSource by our new implementation, we simply instantiate that instead of the old one in our configuration-class SocialConfig:

@Override
public UserIdSource getUserIdSource()
{
  return new SecurityContextUserIdSource();
}

There are several ways to plug in the ConnectionSignUp.
I decided, to plug it into the instance of InMemoryUsersConnectionRepository, that our configuration uses, because this way, the user will be signed up automatically on sign in, if it is not known to the application:

@Override
public UsersConnectionRepository getUsersConnectionRepository(
    ConnectionFactoryLocator connectionFactoryLocator
    )
{
  InMemoryUsersConnectionRepository repository =
      new InMemoryUsersConnectionRepository(connectionFactoryLocator);
  repository.setConnectionSignUp(new ProviderUserIdConnectionSignUp());
  return repository;
}

This makes sense, because our facebook-app uses Facebook, to sign in its users, and, because of that, does not have its own user-model.
It can just reuse the user-data provided by facebook.

The other approach would be, to officially sign up users, that are not known to the app.
This is achieved, by redirecting to a special URL, if a sign-in fails, because the user is unknown.
These URL then presents a formular for sign-up, which can be prepopulated with the user-data provided by the social network.
You can read more about this approach in the official documentation.

Run It!

So, let us see, if our refinement works. Run the following command and log into your app with at least two different users:

git clone http://juplo.de/git/examples/facebook-app/
cd facebook-app
checkout part-00
mvn spring-boot:run \
    -Dfacebook.app.id=YOUR_ID \
    -Dfacebook.app.secret=YOUR_SECRET \
    -Dlogging.level.de.juplo.yourshouter=debug

(The last part of the command turns on the DEBUG logging-level, to see in detail, what is going on.

But What The *#! Is Going On There?!?

Unfortunately, our application shows exactly the same behavior as, before our last refinement.
Why that?

If you run the application in a debugger and put a breakpoint in our implementation of ConnectionSignUp, you will see, that this code is never called.
But it is plugged in in the right place and should be called, if a new user signs in!

The solution is, that we are using the wrong mechanism.
We are still using the ConnectController which was configured in the simple example, we extended.
But this controller is meant to connect a known user to one or more new social services.
This controller assumes, that the user is already signed in to the application and can be retrieved via the configured UserIdSource.


To sign in a user to our application, we have to use the ProviderSignInController instead!

Coming next…

In the next part of this series, I will show you, how to change the configuration, so that the ProviderSignInController is used to sign in (and automatically sign up) users, that were authenticated through the Graph-API from Facebook.

Funded by the Europian Union

This article was published in the course of a
resarch-project,
that is funded by the European Union and the federal state Northrhine-Wetphalia.


Europäische Union: Investitionen in unsere Zukunft - Europäischer Fonds für regionale Entwicklung
EFRE.NRW 2014-2020: Invesitionen in Wachstum und Beschäftigung

Develop a Facebook-App with Spring-Social – Part II: How Spring Social Works

In this series of Mini-How-Tow’s I will describe how to develop a facebook app with the help of Spring-Social.

In the last part of this series, we took control of the autoconfiguration, that Spring Boot had put in place for us.
But there is still a lot of magic in our little example, that was borrowed from the offical “Getting Started”-guides or at least, it looks so.

First Time In The Electric-Wonder-Land

When I first run the example, I wondered like “Wow, how does this little piece of code figures out which data to fetch? How is Spring Social told, which data to fetch? That must be stored in the session, or so! But where is that configured?” and so on and so on.

When we connect to Facebook, Facebook tells Spring Social, which user is logged in and if this user authorizes the requested access.
We get an access-token from facebook, that can be used to retrieve user-related data from the Graph-API.
Our application has to manage this data.

Spring Social assists us on that task.
But in the end, we have to make the decisions, how to deal with it.

Whom Are You Intrested In?

Spring Social provides the concept of a ConnectionRepository, which is used to persist the connections of specific user.
Spring Social also provides the concept of a UsersConnectionRepository, which stores, whether a user is connected to a specific social service or not.
As described in the official documentation, Spring Social uses the UsersConnectionRepository to create a request-scoped ConnectionRepository bean (the bean named facebook in our little example), that is used by us to access the Graph-API.

But to be able to do so, it must know which user we are interested in!

Hence, Spring Social requires us to configure a UserIdSource.
Every time, when it prepares a request for us, Spring Social will ask this source, which user we are interested in.

Attentive readers might have noticed, that we have configured such a source, when we were explicitly rebuilding the automatic default-configuration of Spring Boot:

public class AnonymousUserIdSource implements UserIdSource
{
  @Override
  public String getUserId()
  {
    return "anonymous";
  }
}

No One Special…

But what is that?!?
All the time we are only interested in one and the same user, whose connections should be stored under the key anonymous?

And what will happen, if a second user connects to our app?

Let’s Test That!

To see what happens, if more than one user connects to your app, you have to create a test user.
This is very simple.
Just go to the dashboard of your app, select the menu-item “Roles” and click on the tab “Test Users”.
Select a test user (or create a new one) and click on the “Edit”-button.
There you can select “Log in as this test user”.

If you first connect to the app as yourself and afterwards as test user, you will see, that your data is presented to the test user.

That is, because we are telling Spring Social that every user is called anonymous.
Hence, every user is the same for Spring Social!
When the test user fetches the page, after you have connected to Facebook as yourself, Spring-Social is thinking, that the same user is returning and serves your data.

Coming next…

In the next part of this series, we will try to teach Spring Social to distinguish between several users.

Funded by the Europian Union

This article was published in the course of a
resarch-project,
that is funded by the European Union and the federal state Northrhine-Wetphalia.


Europäische Union: Investitionen in unsere Zukunft - Europäischer Fonds für regionale Entwicklung
EFRE.NRW 2014-2020: Invesitionen in Wachstum und Beschäftigung

Develop a Facebook-App with Spring-Social – Part I: Behind the Scenes

In this series of Mini-How-Tow’s I will describe how to develop a facebook app with the help of Spring-Social.

In the last and first part of this series, I prepared you for our little course.

In this part we will take a look behind the scenes and learn more about the autoconfiguration performed by Spring-Boot, which made our first small example so automagically.

The Source is With You

You can find the source-code on http://juplo.de/git/examples/facebook-app/
and browse it via gitweb.
Check out part-01 to get the source for this part of the series.

Our Silent Servant Behind the Scenes: Spring-Boot

While looking at our simple example from the last part of this series, you may have wondered, how all this is wired up.
You can log in a user from facebook, access his public profile and all this without one line of configuration.


This is achieved via Spring-Boot autoconfiguration.

What comes in very handy in the beginning, sometimes get’s in your way, when your project grows.
This may happen, because these parts of the code are not under your control and you do not know what the autoconfiguration is doing on your behalf.
Because of that, in this part of our series, we will rebuild the most relevant parts of the configuration by hand.
As you will see later, this is not only an exercise, but will lead us to the first improvement of our little example.

What Is Going On Here?

In our case, two Spring-Boot configuration-classes are defining the configuration.
These two classes are SocialWebAutoConfiguration and FacebookAutoConfiguration.
Both classes are located in the package spring-boot-autoconfigure.

The first one configures the ConnectController, sets up an instance of InMemoryUsersConnectionRepository as persitent store for user/connection-mappings and sets up a UserIdService on our behalf, that always returns the user-id anonymous.

The second one adds an instance of FacebookConnectionFactory to the list of available connection-factories, if the required properties (spring.social.facebook.appId and spring.social.facebook.appSecret) are available.
It also configures, that a request-scoped bean of the type Connection<Facebook> is created for each request, that has a known user, who is connected to the Graph-API.

Rebuild This Configuration By Hand

The following class rebuilds the same configuration explicitly:

@Configuration
@EnableSocial
public class SocialConfig extends SocialConfigurerAdapter
{
  /**
   * Add a {@link FacebookConnectionFactory} to the configuration.
   * The factory is configured through the keys <code>facebook.app.id</code>
   * and &lt,code>facebook.app.secret</code>.
   *
   * @param config
   * @param env 
   */
  @Override
  public void addConnectionFactories(
      ConnectionFactoryConfigurer config,
      Environment env
      )
  {
    config.addConnectionFactory(
        new FacebookConnectionFactory(
            env.getProperty("facebook.app.id"),
            env.getProperty("facebook.app.secret")
            )
        );
  }

  /**
   * Configure an instance of {@link InMemoryUsersConnection} as persistent
   * store of user/connection-mappings.
   *
   * At the moment, no special configuration is needed.
   *
   * @param connectionFactoryLocator
   *     The {@link ConnectionFactoryLocator} will be injected by Spring.
   * @return
   *     The configured {@link UsersConnectionRepository}.
   */
  @Override
  public UsersConnectionRepository getUsersConnectionRepository(
      ConnectionFactoryLocator connectionFactoryLocator
      )
  {
    InMemoryUsersConnectionRepository repository =
        new InMemoryUsersConnectionRepository(connectionFactoryLocator);
    return repository;
  }

  /**
   * Configure a {@link UserIdSource}, that is equivalent to the one, that is
   * created by Spring-Boot.
   *
   * @return
   *     An instance of {@link AnonymousUserIdSource}.
   *
   * @see {@link AnonymousUserIdSource}
   */
  @Override
  public UserIdSource getUserIdSource()
  {
    return new AnonymousUserIdSource();
  }


  /**
   * Configuration of the controller, that handles the authorization against
   * the Facebook-API, to connect a user to Facebook.
   *
   * At the moment, no special configuration is needed.
   *
   * @param factoryLocator
   *     The {@link ConnectionFactoryLocator} will be injected by Spring.
   * @param repository
   *     The {@link ConnectionRepository} will be injected by Spring.
   * @return
   *     The configured controller.
   */
  @Bean
  public ConnectController connectController(
      ConnectionFactoryLocator factoryLocator,
      ConnectionRepository repository
      )
  {
    ConnectController controller =
        new ConnectController(factoryLocator, repository);
    return controller;
  }

  /**
   * Configure a scoped bean named <code>facebook</code>, that enables
   * access to the Graph-API in the name of the current user.
   *
   * @param repository
   *     The {@link ConnectionRepository} will be injected by Spring.
   * @return
   *     A {@Connection}, that represents the authorization of the
   *     current user against the Graph-API, or null, if the
   *     current user is not connected to the API.
   */
  @Bean
  @Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
  public Facebook facebook(ConnectionRepository repository)
  {
    Connection connection =
        repository.findPrimaryConnection(Facebook.class);
    return connection != null ? connection.getApi() : null;
  }
}

If you run this refined version of our app, you will see, that it behaves in exact the same way, as the initial version.

Coming next

You may ask, why we should rebuild the configuration by hand, if it does the same thing.
This is, because the example, so far, would not work as a real app.
The first step, to refine it, is to take control of the configuration.

In the next part of this series, I will show you, why this is necessary.
But, first, we have to take a short look into Spring Social.

Funded by the Europian Union

This article was published in the course of a
resarch-project,
that is funded by the European Union and the federal state Northrhine-Wetphalia.


Europäische Union: Investitionen in unsere Zukunft - Europäischer Fonds für regionale Entwicklung
EFRE.NRW 2014-2020: Invesitionen in Wachstum und Beschäftigung

Develop a Facebook-App with Spring-Social – Part 0: Prepare

In this series of Mini-How-Tow’s I will describe how to develop a facebook app with the help of Spring-Social.

The goal of this series is not, to show how simple it is to set up your first social app with Spring Social.
Even though the usual getting-started guides, like the one this series is based on, are really simple at first glance, they IMHO tend to be confusing, if you try to move on.
I started with the example from the original Getting-Started guide “Accessing Facebook Data” and planed to extend it to handle a sign-in via the canvas-page of facebook, like in the Spring Social Canvas-Example.
But I was not able to achieve that simple refinement and ran into multiple obstacles.

Because of that, I wanted to show the refinement-process from a simple example up to a full-fledged facebook-app.
My goal is, that you should be able to reuse the final result of the last part of this series as blueprint and starting-point for your own project.
At the same time, you should be able to jump back to earlier posts and read all about the design-decisions, that lead up to that result.

This part of my series will handle the preconditions of our first real development-steps.

The Source is With You

The source-code can be found on http://juplo.de/git/examples/facebook-app/
and browsed via gitweb.
For every part I will add a corresponding tag, that denotes the differences between the earlier and the later development steps.

Keep it Simple

We will start with the most simple app possible, that just displays the public profile data of the logged in user.
This app is based on the code of the original Getting-Started guide “Accessing Facebook Data” from Spring-Social.

But it is simplified and cleand a little.
And I fixed some small bugs: the original code from
https://github.com/spring-guides/gs-accessing-facebook.git
produces a
NullPointerException and won’t work with the current version 2.0.3.RELEASE of spring-social-facebook, because it uses the depreceated scope read_stream.

The code for this.logging.level.de.juplo.yourshouter= part is tagged with part-00.
Appart from the HTML-templates, the attic for spring-boot and the build-definitions in the pom.xml it mainly consists of one file:

@Controller
@RequestMapping("/")
public class HomeController
{
  private final static Logger LOG = LoggerFactory.getLogger(HomeController.class);


  private final Facebook facebook;


  @Inject.logging.level.de.juplo.yourshouter=
  public HomeController(Facebook facebook)
  {
    this.facebook = facebook;
  }


  @RequestMapping(method = RequestMethod.GET)
  public String helloFacebook(Model model)
  {
    boolean authorized = true;
    try
    {
      authorized = facebook.isAuthorized();
    }
    catch (NullPointerException e)
    {
      LOG.debug("NPE while acessing Facebook: {}", e);
      authorized = false;
    }
    if (!authorized)
    {
      LOG.info("no authorized user, redirecting to /connect/facebook");
      return "redirect:/connect/facebook";
    }

    User user = facebook.userOperations().getUserProfile();
    LOG.info("authorized user {}, id: {}", user.getName(), user.getId());
    model.addAttribute("user", user);
    return "home";
  }
}

I removed every unnecessary bit, to clear the view for the relevant part.
You can add your styling and stuff by yourself later…

Automagic

The magic of Spring-Social is hidden in the autoconfiguration of Spring-Boot, which will be revealed and refined/replaced in the next parts of this series.

Run it!

You can clone the repository, checkout the right version and run it with the following commands:

git clone http://juplo.de/git/examples/facebook-app/
cd facebook-app
checkout part-00
mvn spring-boot:run \
    -Dfacebook.app.id=YOUR_ID \
    -Dfacebook.app.secret=YOUR_SECRET

Of course, you have to replace YOUR_ID and YOUR_SECRET with the ID and secret of your Facebook-App.
What you have to do to register as a facebook-developer and start your first facebook-app is described in this “Getting Started”-guide from Spring-Social.

In addition to what is described there, you have to configure the URL of your website.
To do so, you have to navigate to the Settings-panel of your newly registered facebook-app.
Click on Add Platform and choose Website.
Then, enter http://localhost:8080/ as the URL of your website.

After maven has downloaded all dependencies and started the Spring-Boot application in the embedded tomcat, you can point your browser to http://localhost:8080, connect, go back to the welcome-page and view the public data of the account you connected with your app.

Coming next…

Now, you are prepared to learn Spring-Social and develop your first app step by step.
I will guide you through the process in the upcoming parts of this series.

In the next part of this series I will explain, why this example from the “Getting Started”-guide would not work as a real application and what has to be done, to fix that.

Funded by the Europian Union

This article was published in the course of a
resarch-project,
that is funded by the European Union and the federal state Northrhine-Wetphalia.


Europäische Union: Investitionen in unsere Zukunft - Europäischer Fonds für regionale Entwicklung
EFRE.NRW 2014-2020: Invesitionen in Wachstum und Beschäftigung