martes, mayo 10, 2011

To Seek Out New Life And New Civilizations, To Boldly Go Where No Man Has Gone Before (TNG Soundtrack - Star Trek)



From Wikipedia: OAuth (Open Authentication) is an open standard for authentication. It allows users to share their private resources (e.g. photos, videos, contact lists) stored on one site with another site without having to hand out their credentials, typically username and password.
There are a lot of posts talking about OAuth from Client Side, for example how to connect to service providers like Twitter or Facebook, but there are less posts about OAuth but from Server Side, more specificaly how to implement an authentication mechanism using OAuth for protecting resources, and not for accessing them (Client Side Part).

In this post I will talk about how to protect your resources, using Spring Security (Spring Security OAuth). The example will be simple enough to understand the basics for implementing an OAuth service provider.

I have found this post that explains with a simple example, what OAuth is and how it works. I think it is a good starting point with OAuth http://hueniverse.com/2007/10/beginners-guide-to-oauth-part-ii-protocol-workflow/

Now it is time to start writing our service provider. First of all I will explain what our Service Provider will offer.

Imagine you are developing a website (called CV) where users will register and after that they will be able to upload their Curriculum Vitae. Now we are going to transform this website to a Service Provider where OAuth will be used for protecting resources (Curriculm Vitae of registered users). Imagine again that some companies have agreed with CV people that when they publish job vacances, users will have the possibility of uploading their curriculum directly from CV site to HR department instead of sending by email or copy & paste from document. As you can see here is where OAuth starts managing security between CV website and Company RH site.

In summary we have a Curriculum Vitae Service Provider (CV) with protected resource (document itself). Companies that offer users the possibility of acquiring directly their Curriculum Vitae from CV are the Consumers. So when a user visits company job vacancies (in our example called fooCompany) and wants to apply for a job, he only has to authorize FooCompany "Job Vacancies" website with permissions to download its Curriculum Vitae from CV site.

Because we will use Spring Security for OAuth authentication, first of all we are going to configure Spring Security into SpringMVC CV application. Nothing special here:

In web.xml file we define Security Filter:



And in root-context.xml we define protected resources and authentication manager. In this case In memory apporoach is used:



Next step, create an Spring Controller that returns the Curriculum Vitae of logged user:



This controller returns directly a String, instead a ModelView object. This String is sent directly as HttpServletResponse.

Now we have got a simple website that returns the Curriculum Vitae of logged user. If you try to access to /cvs resource, if you are not authenticated, Spring Security will show you a login page, and if you are already logged, your job experience will be returned. Works as any other website that are using Spring Security.

Next step is modifing this project for allowing external sites can access to protected resources using OAuth 2 authentication protocol.

In root-context.xml:



First bean, is an OAuth2ProviderTokenServices interface implementation with id tokenServices. The OAuth2ProviderTokenServices interface defines operations that are necessary to manage OAuth 2.0 tokens. These tokens should be stored for subsequent access token can reference it. For this example InMemory store is enough.

Next bean is <oauth:provider>. This tag is used to configure the OAuth 2.0 provider mechanism. And in this case three parameters are configured; the first one is a reference to a bean that defines the client details service, explained in next paragraph. The second one is token service for providing tokens, explained in previous paragraph, and the last one is the URL at which a request for authorization token will be serviced. This is the typically Authorize/Denny page where service provider asks to user if it permits the Consumer (in our case fooCompany) accessing to protected resources (its Curriculum Vitae).

Last bean is <oauth:client-details-service>. In this tag you define which clients you authorize to access to protected resources with previous authentication. In this case because CV company has agreed with foo company that they can connect to its Curriculum Vitae Service, a client is defined with id foo.

Now we have our application configured with OAuth. Last step is creating a controller for taking requests from /oauth/confirm_access URL.



This controller returns a ModelAndView object with client information and which page should be shown for granting permission to protected resources. This JSP page is called access_confirmation.jsp and the most important part is:



As you can see Spring Security OAuth provides helper classes for creating confirmation form and deny form. When the result is submitted, URL /cv/oauth/user/authorize (internally managed) is called, there OAuth decides if returns protected resource (String returned by loadCV() method) to caller or not depending on what option user has chosen.

And that's all about creating an OAuth 2 system using Spring Security OAuth. But I suppose you are wondering how to test it, so for the same price I will explain how to write the client part (Consumer) using Spring Security OAuth too.

Client application (called fooCompany) is also a SpringMVC web application with Spring Security.

 Spring Security part will be ignored here.

The client application contains a home page (home.jsp) that has a link to Spring Controller that will be responsible to download Curriculum Vitae from CV site, and redirecting content to a view (show.jsp).



As you can see is a simple Controller that calls a Curriculum Vitae service. This service will be responsible to connect to CV website, and download required Curriculum Vitae. Of course it deals with OAuth communication protocol too.

Service looks:



The suggested method for accessing those resources is by using Rest. For this porpose Spring Security OAuth provides an extension of RestTemplate for dealing with OAuth protocol. This class (OAuth2RestTemplate) manages connection to required resources and also manages tokens, OAuth authorization protocol, ...

OAuth2RestTemplate is injected into CVService, and it is configured into root-context.xml:



See that OAuth2RestTemplate is created using an OAuth resource that contains all information about where to connect for authorizing access to protected resource, and in this case is CV website, see that we are referencing an external website, although in this example we are using localhost. Also service provider URL (http://localhost:8080/cvs/cv) is set, so RestTemplate can establish a connection to content provider, and in case that authorization process ends successful, retrieving  requested information.

<oauth:resource> defines OAuth resources, in this case, the name of the client (remember that this value was configured in server side client details tag for granting access to OAuth protocol). Also userAuthorizationUri is defined. This is the URI to which the user will be redirected if the user is ever needed to authorize access to the resource (this is an internal URI managed by Spring Security OAuth). And finally accessTokenUri, the URI OAuth provider endpoint that provides the access token (internal URI too).

Also creating a consumer using Spring Security OAuth is simple enough.

Now I will explain the sequence of events that happens when a user wants to give access to foo company for retrieving its Curriculum Vitae.

First of all user connects to foo website, and click on post curriculum vitae link. Then getCV method from controller is called. This method calls cvService, that at the same time creates a connection to resource URI (CV) using OAuth2RestTemplate. And this class acts as a black box, from client side, you don't know exactly what this class will do but it returns your Curriculum Vitae stored in CV website. As you can imagine this class manages all workflow related to OAuth, like managing tokens, executing required URL redirections to get permissions, ... and if all steps are performed successful, stored Curriculum Vitae in CV site will be sent to foo company site.

And that's all steps required to allow your site to act as Service Provider using OAuth2 authorization protocol. Thanks of Spring Security folks, it is much easier that you may think at first.

Hope you find it useful.

Download ServerSide (CV)
Download ClientSide (fooCompany)

6 comentarios:

Beto dijo...

very good post!
congratulations!

Anónimo dijo...

Hi Alex, A question...
how the provider protect its resources, how protect the CV information ?
Because if I acess directly the url http://localhost:8080/cv/cvs
I got the CV, since i have been logged on cv app.
It is not necessary pass the access_token to get CV info...
I think, the CV is not protected with oauth2, cause acess_token is not required to get CV info. Am I Right ?

thanks!

Alex dijo...

Well this behavior is expected, oauth only protect resources when external sites try to access protected resources, but not when you are logged into CV site and you are accessing directly to CV host.

Stephan Celis dijo...

Hello Alex,

I really loved your post. It's the only one with a step by step guide how to make a provider and client that I found. The rest only have clients or very basic.

But I have a question. I need to make an Android application which communicates with the provider. The class I need to use for this connection expects a request_token and access_token url which return the tokens. I can't find these url's declared in the code. How can I specify these url's?

Thx!

If needed you can also contact me through e-mail stephan.celis[at]gmail[dot]com

Wandi dijo...

ERROR => cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'oauth:provider'.

Wandi dijo...
Este comentario ha sido eliminado por el autor.