Monthly Archives: April 2014

RestTemplate and Proactive Basic Authentication

The Problem

Not that long ago we looked into how to use RestTemplate with http basic auth.

However, we might have some trouble with that code using the RestTemplate on some services. In particular, with services that anticipate proactive vs reactive authentication. The rest template does not send the Authentication header on the initial request, so if the service does not respond with a WWW-Authenticate header (as it should according to the HTTP spec) and the RestTemplate does not attempt to send the credentials after the initial response, then the call will simply fail on the intial 401 response.

The Solution

Fortunately, there is a solution: Tell the rest template to send the credentials on the initial request rather than waiting for a 401 with a WWW-Authenticate header.

The trick here is to override the request factory’s createHttpContext() method to take control over the HTTP context, and use this factory in constructing the RestTemplate. This code works, and uses the self-signed certificate that we set it up for in the previous post. You may of course restructure it to your taste…

public class BasicRequestFactory extends HttpComponentsClientHttpRequestFactory {

    public BasicRequestFactory(HttpClient httpClient) {
        super(httpClient);
    }

    @Override
    protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
        HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);
        BasicHttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
        return localContext;
    }

    private static HttpClient createSecureClient() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS().build();
        SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());
        return HttpClientBuilder.create().setSSLSocketFactory(connectionFactory).build();
    }

    private static HttpClient createSecureClient(String username, String password) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS().build();
        SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());
        return HttpClientBuilder.create().setSSLSocketFactory(connectionFactory).setDefaultCredentialsProvider(credentialsProvider).build();
    }

    public static RestTemplate createTemplate(String username, String password) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        RestTemplate template = new RestTemplate(new BasicRequestFactory(createSecureClient(username, password)));
        template.setErrorHandler(new NopResponseErrorHandler());
        return template;
    }

    public static RestTemplate createTemplate() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        RestTemplate template = new RestTemplate(new BasicRequestFactory(createSecureClient()));
        template.setErrorHandler(new NopResponseErrorHandler());
        return template;
    }

    private static class NopResponseErrorHandler implements ResponseErrorHandler {

        @Override
        public boolean hasError(ClientHttpResponse chr) throws IOException {
            return false;
        }

        @Override
        public void handleError(ClientHttpResponse chr) throws IOException {
        }
    }

}

Happy Authenticating!

Advertisements

Leave a comment

Filed under Software Engineering

Keeping the Train on Schedule

The Protagonist

Joe was a decent developer. He generally got his work done on time, kept skills up to date, helped out coworkers… all standard things that a developer should do.

The Situation

One day, Joe walked into his manager’s office to deliver some unpleasant news. Joe said “So, code complete is in two days, and I haven’t even started the foobar feature. I don’t know if it can even be done in time, it will be tight at best.” Manager furrowed his brow, this was unpleasant news indeed. Foobar had been promised to customers and other features were depending on it. Manager asked “What happened? Why is it running late?” Joe answered, “Well, on the last thing I was working on, the fizzbuzz feature, the designer kept coming up with changes. I kept on thinking it was just a small change here and there, it’s just another couple hours of work. But it kept happening and kept happening, and the next thing I knew, it was today and the rest of my work was at risk.”

To spare you the suspense, don’t worry: Joe busted his butt and got the foobar feature done in time and everybody was happy. But it didn’t have to be this way.

How Could This Happen

As a developer, there numerous forces trying to drive the priority (sometimes inappropriately) of what what you work on. Managers, co-workers, QA, customers and support… Many people can derail your attention and lead you to believe that their item is the most important. What happened in the situation above was scope creep (or perhaps just insufficient initial design) initiated by a fellow member of the team.

Prevention is the Best Cure

Obviously it’s best to not have to bring up uncomfortable news in the first place. Some ways we can avoid this kind of derailment:

  • Stronger definition of done: with a clearly defined scope, we can more easily recognize when we are being asked to do out of scope work, and we can more easily shift these requests to a later work item.
  • Recognizing scope creep: we should be able to say no (or defer to a higher decision maker) when someone asks for something that really is out of scope.
  • Daily standups: with high visibility into everybody’s progress, derailment can be recognized and mitigated earlier even if the developer does not recognize it.
  • Be cognizant of time spent: the hours for each task are estimated at the start of a sprint for a reason. When going over the estimated hours we should raise the issue with management as early as possible.

Conclusion

As software engineering professionals, it is our duty to be vigilant and recognize derailments and ensure that we are always working on the most important thing first.

Leave a comment

Filed under Software Engineering

Front End Development with Apache

The Apache web server is the single most popular web server on the planet, serving more than half of all website across all domains. Think about that for a minute. Impressive.

Not only is Apache good for serving the world, it’s also good for serving your html files in your personal development environment. Let’s set up Apache!

Installation

This post only deals with Linux, sorry Mac/Windows folks! Many modern Linux distributions come bundled with Apache, but if it is not already installed already, it is easily installable with

sudo apt-get install apache2

When installed, it is also usually set up to run automatically. We can check to see if it’s running with

ps -ef | grep apache2

If we want to control this and actually start or stop it manually, we can cycle Apache with these commands:

/etc/init.d/apache2 start
/etc/init.d/apache2 stop
/etc/init.d/apache2 restart

Serving Content

OK, Apache is up and running. How can we edit html files and have them served locally by Apache?

On the local file system, files are usually served from /var/www/
HTML files and other static content in this location are immediately accessible on port 80 at http://localhost Apache only serves static content, but can forward requests for dynamic content to an application server or servlet container with a reverse proxy.

The big step here is to link our development folder (where all of our html/css/js files are stored and being edited) to the folder where apache can serve them. We can link apache to a development folder like so

sudo ln -s /home/username/path/to/project   /var/www

That’s it!

At this point, a file like /home/username/path/to/project/index.html will be accessible via local web server as http://localhost/index.html. Apache will immediately pick up any changes and immediately serve them with a page refresh.

Happy Front-End-Developing!

Leave a comment

Filed under Uncategorized

Tips for Startup Weekend

If you are thinking of participating in Startup weekend, here are some tips for participants (particularly developers):

Items to Bring

  • Laptop, power cord, mouse
  • ergonomic keyboard (use backpack)
  • extension cord and power strip
  • paper pad and pens
  • cash
  • big headphones to block noise, you generally don’t get your own room
  • business cards
  • substantial or healthy food if you want it (one year they only served sandwiches and pasta, another year they catered and it was better)

General Notes

  • A big help for preparation would be having a RAD tool and being able to produce a shiny app from front to back very quickly, and having a starter app with users and database ready to modify
  • Big themes are mobile devices, should be able to write mobile app (not site) that’s location aware, has login options, etc. Can always do backend rest/json for mobile too
  • There are many online services and api’s you can use, be able to use a rest template or in some way make calls from your app. Leveraging google api’s or other free services can help you put up something very quickly that does something actually useful.
  • Follow the judging criteria carefully, they are there for a reason – specifically to make you think through what it takes to make your business viable. It is impressive when business people research the market validation, potential revenue, and are able to put it all together it in a nice presentation (say, with prezio or a video).
  • Make sure to network during dinner on friday night. You’ll find people you like or don’t like, and if you’re pitching, people you can connect with will be more likely to join your team.

 

These are just notes that I thought of, your mileage may vary. But if you want to check out startup weekend for the first time, these ideas will smooth your way!

Leave a comment

Filed under Uncategorized

Startup Weekend

I recently participated in Startup Weekend. For an entire weekend (friday night through sunday night) entrepreneurs, designers, and developers come together to build a business and build a technology product! It’s extremely intense and I highly recommend the experience.

Startup weekend is a global phenomenon, the one I attended this past weekend was the health edition in Philadelphia. The Philly startup weekend only happens once a year, but more often in New York City and San Francisco (as you might imagine!)

Why should every developer try startup weekend at least once? It gets you to do something different, you’ll network with great people, and get a chance at maybe starting something big! Go for it!

Leave a comment

Filed under Software Engineering