@Override public Optional<HelloAccount> authenticate(BasicCredentials credentials) throws AuthenticationException { if (credentials.getUsername().equals("moxie") && credentials.getPassword().equals("insecure")) { return Optional.of(new HelloAccount("moxie")); } return Optional.empty(); } }
@GET @Path("/named") @Timed @Produces("text/plain") public String saySpecialHello(@Auth HelloAccount account) { return "Hello " + account.getUsername(); }
@Override public AuthenticationResult<HelloAccount> authenticate(UpgradeRequest request) throws AuthenticationException { try { Map<String, List<String>> parameters = request.getParameterMap(); List<String> usernames = parameters.get("login"); List<String> passwords = parameters.get("password"); if (usernames == null || usernames.size() == 0 || passwords == null || passwords.size() == 0) { return new AuthenticationResult<>(Optional.empty(), false); } BasicCredentials credentials = new BasicCredentials(usernames.get(0), passwords.get(0)); return new AuthenticationResult<>(basicAuthenticator.authenticate(credentials), true); } catch (io.dropwizard.auth.AuthenticationException e) { throw new AuthenticationException(e); } }
@Override public void run(ServerConfiguration serverConfiguration, Environment environment) throws Exception { WebSocketEnvironment webSocketEnvironment = new WebSocketEnvironment(environment, serverConfiguration.getWebSocketConfiguration()); HelloResource helloResource = new HelloResource(serverConfiguration.getHelloResponse()); HelloAccountBasicAuthenticator helloBasicAuthenticator = new HelloAccountBasicAuthenticator(); environment.jersey().register(helloResource); environment.jersey().register(new AuthDynamicFeature(new BasicCredentialAuthFilter.Builder<HelloAccount>() .setAuthenticator(helloBasicAuthenticator) .setPrincipal(HelloAccount.class) .buildAuthFilter())); environment.jersey().register(new AuthValueFactoryProvider.Binder()); webSocketEnvironment.jersey().register(helloResource); webSocketEnvironment.setAuthenticator(new HelloAccountWebSocketAuthenticator(helloBasicAuthenticator)); WebSocketResourceProviderFactory servlet = new WebSocketResourceProviderFactory(webSocketEnvironment); ServletRegistration.Dynamic websocket = environment.servlets().addServlet("WebSocket", servlet); websocket.addMapping("/websocket/*"); websocket.setAsyncSupported(true); servlet.start(); }
@GET @Path("/optional") @Timed @Produces("text/plain") public String sayOptionalHello(@Auth Optional<HelloAccount> account) { if (account.isPresent()) return account.get().getUsername(); else return "missing"; }