Oltu Authorization Server
With Oltu you can easily create OAuth 2.0 compliant applications.
End User Authorization Endpoint
Simplified implementation of the OAuth 2.0 End User Authorization Endpoint using Oltu:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { //dynamically recognize an OAuth profile based on request characteristic (params, // method, content type etc.), perform validation OAuthAuthzRequest oauthRequest = new OAuthAuthzRequest(request); validateRedirectionURI(oauthRequest) //build OAuth response OAuthResponse resp = OAuthASResponse .authorizationResponse(HttpServletResponse.SC_FOUND) .setCode(oauthIssuerImpl.authorizationCode()) .location(ex.getRedirectUri()) .buildQueryMessage(); response.sendRedirect(resp.getLocationUri()); //if something goes wrong } catch(OAuthProblemException ex) { final OAuthResponse resp = OAuthASResponse .errorResponse(HttpServletResponse.SC_FOUND) .error(ex) .location(redirectUri) .buildQueryMessage(); response.sendRedirect(resp.getLocationUri()); } }
With this way of building OAuth requests and responses, it does not matter if you are using Java servlets or the JAX-RS specification.
In JAX-RS endpoint, for example, you would do:
Response.status(resp.getResponseStatus()).location(resp.getLocationUri()).build();
Token Endpoint
Simplified implementation of the OAuth 2.0 Token Endpoint using Oltu:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { OAuthTokenRequest oauthRequest = null; OAuthIssuer oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator()); try { oauthRequest = new OAuthTokenRequest(request); validateClient(oauthRequest); String authzCode = oauthRequest.getCode(); // some code String accessToken = oauthIssuerImpl.accessToken(); String refreshToken = oauthIssuerImpl.refreshToken(); // some code OAuthResponse r = OAuthASResponse .tokenResponse(HttpServletResponse.SC_OK) .setAccessToken(accessToken) .setExpiresIn("3600") .setRefreshToken(refreshToken) .buildJSONMessage(); response.setStatus(r.getResponseStatus()); PrintWriter pw = response.getWriter(); pw.print(r.getBody()); pw.flush(); pw.close(); //if something goes wrong } catch(OAuthProblemException ex) { OAuthResponse r = OAuthResponse .errorResponse(401) .error(ex) .buildJSONMessage(); response.setStatus(r.getResponseStatus()); PrintWriter pw = response.getWriter(); pw.print(r.getBody()); pw.flush(); pw.close(); response.sendError(401); } }
If you need more advanced examples, then take a look at the integration-tests module which shows all possibilities provided by Oltu API.