Skip to content

Latest commit

 

History

History
74 lines (61 loc) · 2.88 KB

README.md

File metadata and controls

74 lines (61 loc) · 2.88 KB

java-webapp-authentication

Build Status Coverage Status Maven Central

https://github.com/achatain/java-webapp-authentication

#What is it? JWA (Java Webapp Authentication) assists in leveraging Google Sign-In for backend server applications built with Java. Despite being in its early days, JWA provides you with a bunch of robust and easy to use features:

  • authentication filter
  • sign-in and sign-out servlets
  • session management service
  • etc.

#How do I integrate it in my backend app?

  1. Add the dependency in your pom file
<dependency>
 <groupId>com.github.achatain</groupId>
 <artifactId>java-webapp-authentication</artifactId>
 <version>1.1.0</version>
</dependency>
  1. Install the AuthenticationModule to enable the dependency injection (suggested to use Google Guice)
 class AppConfig extends GuiceServletContextListener {
   @Override
   protected Injector getInjector() {
     return Guice.createInjector(
       new AuthenticationModule()
     );
   }
 }
  1. Filter your restricted API through the SessionFilter and serve the sign-in and sign-out servlets
 class AppServletModule extends ServletModule {
   @Override
   protected void configureServlets() {
     Map<String, String> initParams = new HashMap<>();
     initParams.put(SessionFilter.LOGIN_URL_REDIRECT, "https://myapp.com/google-sign-in/");
     filter("/api/*").through(SessionFilter.class, initParams);
     serve("/google-auth").with(GoogleSigninServlet.class);
     serve("/signout").with(SignOutServlet.class);
   }
 }

#How do I know who is logged-in? From any servlet filtered through the SessionFilter, you can get the current user thanks to the SessionService

public class MyServlet extends HttpServlet {

   private final transient SessionService sessionService;

   @Inject
   private MyServlet(final SessionService sessionService) {
       this.sessionService = sessionService;
   }

   @Override
   protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
       AuthenticatedUser user = sessionService.getUserFromSession(req.getSession());
       System.out.println("The logged-in user is " + user);
   }
}