Class AbstractAuthorizationCodeServlet

  • All Implemented Interfaces:
    java.io.Serializable, javax.servlet.Servlet, javax.servlet.ServletConfig

    public abstract class AbstractAuthorizationCodeServlet
    extends javax.servlet.http.HttpServlet
    Thread-safe OAuth 2.0 authorization code flow HTTP servlet that manages and persists end-user credentials.

    This is designed to simplify the flow in which an end-user authorizes your web application to access their protected data. Your application then has access to their data based on an access token and a refresh token to refresh that access token when it expires. Your main servlet class should extend AbstractAuthorizationCodeServlet and implement the abstract methods. To get the persisted credential associated with the current request, call getCredential(). It is assumed that the end-user is authenticated by some external means by which a user ID is obtained. This user ID is used as the primary key for persisting the end-user credentials, and passed in via getUserId(HttpServletRequest). The first time an end-user arrives at your servlet, they will be redirected in the browser to an authorization page. Next, they will be redirected back to your site at the redirect URI selected in getRedirectUri(HttpServletRequest). The servlet to process that should extend AbstractAuthorizationCodeCallbackServlet, which should redirect back to this servlet on success.

    Although this implementation is thread-safe, it can only process one request at a time. For a more performance-critical multi-threaded web application, instead use AuthorizationCodeFlow directly.

    Sample usage:

    public class ServletSample extends AbstractAuthorizationCodeServlet {
    
      @Override
      protected void doGet(HttpServletRequest request, HttpServletResponse response)
          throws IOException {
        // do stuff
      }
    
      @Override
      protected String getRedirectUri(HttpServletRequest req) throws ServletException, IOException {
        GenericUrl url = new GenericUrl(req.getRequestURL().toString());
        url.setRawPath("/oauth2callback");
        return url.build();
      }
    
      @Override
      protected AuthorizationCodeFlow initializeFlow() throws IOException {
        return new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(),
            new NetHttpTransport(),
            new JacksonFactory(),
            new GenericUrl("https://server.example.com/token"),
            new BasicAuthentication("s6BhdRkqt3", "7Fjfp0ZBr1KtDRbnfVdmIw"),
            "s6BhdRkqt3",
            "https://server.example.com/authorize").setCredentialStore(
            new JdoCredentialStore(JDOHelper.getPersistenceManagerFactory("transactions-optional")))
            .build();
      }
    
      @Override
      protected String getUserId(HttpServletRequest req) throws ServletException, IOException {
        // return user ID
      }
    }
     
    Since:
    1.7
    See Also:
    Serialized Form
    • Field Summary

      Fields 
      Modifier and Type Field Description
      private Credential credential
      Persisted credential associated with the current request or null for none.
      private AuthorizationCodeFlow flow
      Authorization code flow to be used across all HTTP servlet requests or null before initialized in initializeFlow().
      private java.util.concurrent.locks.Lock lock
      Lock on the flow and credential.
      private static long serialVersionUID  
    • Method Summary

      All Methods Instance Methods Abstract Methods Concrete Methods 
      Modifier and Type Method Description
      protected Credential getCredential()
      Return the persisted credential associated with the current request or null for none.
      protected abstract java.lang.String getRedirectUri​(javax.servlet.http.HttpServletRequest req)
      Returns the redirect URI for the given HTTP servlet request.
      protected abstract java.lang.String getUserId​(javax.servlet.http.HttpServletRequest req)
      Returns the user ID for the given HTTP servlet request.
      protected abstract AuthorizationCodeFlow initializeFlow()
      Loads the authorization code flow to be used across all HTTP servlet requests (only called during the first HTTP servlet request).
      protected void onAuthorization​(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse resp, AuthorizationCodeRequestUrl authorizationUrl)
      Handles user authorization by redirecting to the OAuth 2.0 authorization server.
      protected void service​(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse resp)  
      • Methods inherited from class javax.servlet.http.HttpServlet

        doDelete, doGet, doHead, doOptions, doPost, doPut, doTrace, getLastModified, service
      • Methods inherited from class javax.servlet.GenericServlet

        destroy, getInitParameter, getInitParameterNames, getServletConfig, getServletContext, getServletInfo, getServletName, init, init, log, log
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Field Detail

      • lock

        private final java.util.concurrent.locks.Lock lock
        Lock on the flow and credential.
      • credential

        private Credential credential
        Persisted credential associated with the current request or null for none.
    • Constructor Detail

      • AbstractAuthorizationCodeServlet

        public AbstractAuthorizationCodeServlet()
    • Method Detail

      • service

        protected void service​(javax.servlet.http.HttpServletRequest req,
                               javax.servlet.http.HttpServletResponse resp)
                        throws java.io.IOException,
                               javax.servlet.ServletException
        Overrides:
        service in class javax.servlet.http.HttpServlet
        Throws:
        java.io.IOException
        javax.servlet.ServletException
      • initializeFlow

        protected abstract AuthorizationCodeFlow initializeFlow()
                                                         throws javax.servlet.ServletException,
                                                                java.io.IOException
        Loads the authorization code flow to be used across all HTTP servlet requests (only called during the first HTTP servlet request).
        Throws:
        javax.servlet.ServletException
        java.io.IOException
      • getRedirectUri

        protected abstract java.lang.String getRedirectUri​(javax.servlet.http.HttpServletRequest req)
                                                    throws javax.servlet.ServletException,
                                                           java.io.IOException
        Returns the redirect URI for the given HTTP servlet request.
        Throws:
        javax.servlet.ServletException
        java.io.IOException
      • getUserId

        protected abstract java.lang.String getUserId​(javax.servlet.http.HttpServletRequest req)
                                               throws javax.servlet.ServletException,
                                                      java.io.IOException
        Returns the user ID for the given HTTP servlet request.
        Throws:
        javax.servlet.ServletException
        java.io.IOException
      • getCredential

        protected final Credential getCredential()
        Return the persisted credential associated with the current request or null for none.
      • onAuthorization

        protected void onAuthorization​(javax.servlet.http.HttpServletRequest req,
                                       javax.servlet.http.HttpServletResponse resp,
                                       AuthorizationCodeRequestUrl authorizationUrl)
                                throws javax.servlet.ServletException,
                                       java.io.IOException
        Handles user authorization by redirecting to the OAuth 2.0 authorization server.

        Default implementation is to call resp.sendRedirect(authorizationUrl.build()). Subclasses may override to provide optional parameters such as the recommended state parameter. Sample implementation:

          @Override
          protected void onAuthorization(HttpServletRequest req, HttpServletResponse resp,
              AuthorizationCodeRequestUrl authorizationUrl) throws ServletException, IOException {
            authorizationUrl.setState("xyz");
            super.onAuthorization(req, resp, authorizationUrl);
          }
         
        Parameters:
        authorizationUrl - authorization code request URL
        req - HTTP servlet request
        Throws:
        javax.servlet.ServletException - servlet exception
        java.io.IOException
        Since:
        1.11