Callback Handlers
Learn how to create a callback handler with a code example.
We'll cover the following...
We will continue working on the same OAuth2 example from the previous lesson.
Create a callback handler
Let’s go ahead and create the CallbackServlet.java
in the Maven oauth2
directory src/main/java/be/rubus/workshop/oauth2
:
Press + to interact
package be.rubus.security.workshop.oauth2;import com.github.scribejava.core.model.OAuth2AccessToken;import com.github.scribejava.core.oauth.OAuth20Service;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import java.io.IOException;import java.util.concurrent.ExecutionException;@WebServlet(Constants.CALLBACK_SERVLET_PATH)public class CallbackServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {HttpSession session = request.getSession();String originalCsrfToken = session.getAttribute(Constants.CSRF_TOKEN).toString();String csrfToken = request.getParameter("state");if (!originalCsrfToken.equals(csrfToken)) {response.sendError(HttpServletResponse.SC_FORBIDDEN, "CSRF token doesn't match");}String code = request.getParameter("code"); // The Authentication codeOAuth20Service authService = AuthenticationFilter.getOAuthService();try {OAuth2AccessToken token = authService.getAccessToken(code);session.setAttribute(Constants.USER_TOKEN, token);String originalURL = session.getAttribute(Constants.ORIGINAL_URL).toString();// Redirect to original Page.response.sendRedirect(originalURL);} catch (InterruptedException | ExecutionException e) {response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());}}}
Explanation
Lines 1 and 2: We creates the
CallbackServlet
.Lines 25–31: Using the
doGet()
method, we check the CSRF token.Lines 33–46: We exchange the authorization code for an access token (using the
ScribeJava
packages for imports), store the token within the session, and redirect to the original user-requested page.
Create Bean to retrieve data
We create a CDI bean that can retrieve the ...