How to use BasicAuthenticationFilter class of org.openqa.selenium.grid.security package

Best Selenium code snippet using org.openqa.selenium.grid.security.BasicAuthenticationFilter

Source:Standalone.java Github

copy

Full Screen

...32import org.openqa.selenium.grid.node.Node;33import org.openqa.selenium.grid.node.ProxyNodeCdp;34import org.openqa.selenium.grid.node.config.NodeOptions;35import org.openqa.selenium.grid.router.Router;36import org.openqa.selenium.grid.security.BasicAuthenticationFilter;37import org.openqa.selenium.grid.security.Secret;38import org.openqa.selenium.grid.security.SecretOptions;39import org.openqa.selenium.grid.server.BaseServerOptions;40import org.openqa.selenium.grid.server.EventBusOptions;41import org.openqa.selenium.grid.server.NetworkOptions;42import org.openqa.selenium.grid.server.Server;43import org.openqa.selenium.grid.sessionmap.SessionMap;44import org.openqa.selenium.grid.sessionmap.local.LocalSessionMap;45import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;46import org.openqa.selenium.grid.sessionqueue.config.SessionRequestOptions;47import org.openqa.selenium.grid.sessionqueue.local.LocalNewSessionQueue;48import org.openqa.selenium.grid.web.CombinedHandler;49import org.openqa.selenium.grid.web.GridUiRoute;50import org.openqa.selenium.grid.web.RoutableHttpClientFactory;51import org.openqa.selenium.internal.Require;52import org.openqa.selenium.remote.http.Contents;53import org.openqa.selenium.remote.http.HttpClient;54import org.openqa.selenium.remote.http.HttpHandler;55import org.openqa.selenium.remote.http.HttpResponse;56import org.openqa.selenium.remote.http.Routable;57import org.openqa.selenium.remote.http.Route;58import org.openqa.selenium.remote.tracing.Tracer;59import java.net.MalformedURLException;60import java.net.URI;61import java.net.URL;62import java.util.Collections;63import java.util.Set;64import java.util.logging.Logger;65import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;66import static java.net.HttpURLConnection.HTTP_OK;67import static org.openqa.selenium.grid.config.StandardGridRoles.DISTRIBUTOR_ROLE;68import static org.openqa.selenium.grid.config.StandardGridRoles.HTTPD_ROLE;69import static org.openqa.selenium.grid.config.StandardGridRoles.NODE_ROLE;70import static org.openqa.selenium.grid.config.StandardGridRoles.ROUTER_ROLE;71import static org.openqa.selenium.grid.config.StandardGridRoles.SESSION_QUEUE_ROLE;72import static org.openqa.selenium.remote.http.Route.combine;73@AutoService(CliCommand.class)74public class Standalone extends TemplateGridServerCommand {75 private static final Logger LOG = Logger.getLogger("selenium");76 @Override77 public String getName() {78 return "standalone";79 }80 @Override81 public String getDescription() {82 return "The selenium server, running everything in-process.";83 }84 @Override85 public Set<Role> getConfigurableRoles() {86 return ImmutableSet.of(DISTRIBUTOR_ROLE, HTTPD_ROLE, NODE_ROLE, ROUTER_ROLE, SESSION_QUEUE_ROLE);87 }88 @Override89 public Set<Object> getFlagObjects() {90 return Collections.singleton(new StandaloneFlags());91 }92 @Override93 protected String getSystemPropertiesConfigPrefix() {94 return "selenium";95 }96 @Override97 protected Config getDefaultConfig() {98 return new DefaultStandaloneConfig();99 }100 @Override101 protected Handlers createHandlers(Config config) {102 LoggingOptions loggingOptions = new LoggingOptions(config);103 Tracer tracer = loggingOptions.getTracer();104 EventBusOptions events = new EventBusOptions(config);105 EventBus bus = events.getEventBus();106 BaseServerOptions serverOptions = new BaseServerOptions(config);107 SecretOptions secretOptions = new SecretOptions(config);108 Secret registrationSecret = secretOptions.getRegistrationSecret();109 URI localhost = serverOptions.getExternalUri();110 URL localhostUrl;111 try {112 localhostUrl = localhost.toURL();113 } catch (MalformedURLException e) {114 throw new IllegalArgumentException(e);115 }116 NetworkOptions networkOptions = new NetworkOptions(config);117 CombinedHandler combinedHandler = new CombinedHandler();118 HttpClient.Factory clientFactory = new RoutableHttpClientFactory(119 localhostUrl,120 combinedHandler,121 networkOptions.getHttpClientFactory(tracer));122 SessionMap sessions = new LocalSessionMap(tracer, bus);123 combinedHandler.addHandler(sessions);124 DistributorOptions distributorOptions = new DistributorOptions(config);125 SessionRequestOptions sessionRequestOptions = new SessionRequestOptions(config);126 NewSessionQueue queue = new LocalNewSessionQueue(127 tracer,128 bus,129 distributorOptions.getSlotMatcher(),130 sessionRequestOptions.getSessionRequestRetryInterval(),131 sessionRequestOptions.getSessionRequestTimeout(),132 registrationSecret);133 combinedHandler.addHandler(queue);134 Distributor distributor = new LocalDistributor(135 tracer,136 bus,137 clientFactory,138 sessions,139 queue,140 distributorOptions.getSlotSelector(),141 registrationSecret,142 distributorOptions.getHealthCheckInterval(),143 distributorOptions.shouldRejectUnsupportedCaps());144 combinedHandler.addHandler(distributor);145 Routable router = new Router(tracer, clientFactory, sessions, queue, distributor)146 .with(networkOptions.getSpecComplianceChecks());147 HttpHandler readinessCheck = req -> {148 boolean ready = sessions.isReady() && distributor.isReady() && bus.isReady();149 return new HttpResponse()150 .setStatus(ready ? HTTP_OK : HTTP_INTERNAL_ERROR)151 .setContent(Contents.utf8String("Standalone is " + ready));152 };153 GraphqlHandler graphqlHandler = new GraphqlHandler(154 tracer,155 distributor,156 queue,157 serverOptions.getExternalUri(),158 getFormattedVersion());159 Routable ui = new GridUiRoute();160 Routable httpHandler = combine(161 ui,162 router,163 Route.prefix("/wd/hub").to(combine(router)),164 Route.options("/graphql").to(() -> graphqlHandler),165 Route.post("/graphql").to(() -> graphqlHandler));166 UsernameAndPassword uap = secretOptions.getServerAuthentication();167 if (uap != null) {168 LOG.info("Requiring authentication to connect");169 httpHandler = httpHandler.with(new BasicAuthenticationFilter(uap.username(), uap.password()));170 }171 // Allow the liveness endpoint to be reached, since k8s doesn't make it easy to authenticate these checks172 httpHandler = combine(httpHandler, Route.get("/readyz").to(() -> readinessCheck));173 Node node = new NodeOptions(config).getNode();174 combinedHandler.addHandler(node);175 distributor.add(node);176 return new Handlers(httpHandler, new ProxyNodeCdp(clientFactory, node));177 }178 @Override179 protected void execute(Config config) {180 Require.nonNull("Config", config);181 Server<?> server = asServer(config).start();182 LOG.info(String.format(183 "Started Selenium Standalone %s: %s",...

Full Screen

Full Screen

Source:Hub.java Github

copy

Full Screen

...30import org.openqa.selenium.grid.graphql.GraphqlHandler;31import org.openqa.selenium.grid.log.LoggingOptions;32import org.openqa.selenium.grid.router.ProxyCdpIntoGrid;33import org.openqa.selenium.grid.router.Router;34import org.openqa.selenium.grid.security.BasicAuthenticationFilter;35import org.openqa.selenium.grid.security.Secret;36import org.openqa.selenium.grid.security.SecretOptions;37import org.openqa.selenium.grid.server.BaseServerOptions;38import org.openqa.selenium.grid.server.EventBusOptions;39import org.openqa.selenium.grid.server.NetworkOptions;40import org.openqa.selenium.grid.server.Server;41import org.openqa.selenium.grid.sessionmap.SessionMap;42import org.openqa.selenium.grid.sessionmap.local.LocalSessionMap;43import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;44import org.openqa.selenium.grid.sessionqueue.config.SessionRequestOptions;45import org.openqa.selenium.grid.sessionqueue.local.LocalNewSessionQueue;46import org.openqa.selenium.grid.web.CombinedHandler;47import org.openqa.selenium.grid.web.GridUiRoute;48import org.openqa.selenium.grid.web.RoutableHttpClientFactory;49import org.openqa.selenium.internal.Require;50import org.openqa.selenium.remote.http.Contents;51import org.openqa.selenium.remote.http.HttpClient;52import org.openqa.selenium.remote.http.HttpHandler;53import org.openqa.selenium.remote.http.HttpResponse;54import org.openqa.selenium.remote.http.Routable;55import org.openqa.selenium.remote.http.Route;56import org.openqa.selenium.remote.tracing.Tracer;57import java.net.MalformedURLException;58import java.net.URL;59import java.util.Collections;60import java.util.Set;61import java.util.logging.Logger;62import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;63import static java.net.HttpURLConnection.HTTP_OK;64import static org.openqa.selenium.grid.config.StandardGridRoles.DISTRIBUTOR_ROLE;65import static org.openqa.selenium.grid.config.StandardGridRoles.EVENT_BUS_ROLE;66import static org.openqa.selenium.grid.config.StandardGridRoles.HTTPD_ROLE;67import static org.openqa.selenium.grid.config.StandardGridRoles.ROUTER_ROLE;68import static org.openqa.selenium.grid.config.StandardGridRoles.SESSION_QUEUE_ROLE;69import static org.openqa.selenium.remote.http.Route.combine;70@AutoService(CliCommand.class)71public class Hub extends TemplateGridServerCommand {72 private static final Logger LOG = Logger.getLogger(Hub.class.getName());73 @Override74 public String getName() {75 return "hub";76 }77 @Override78 public String getDescription() {79 return "A grid hub, composed of sessions, distributor, and router.";80 }81 @Override82 public Set<Role> getConfigurableRoles() {83 return ImmutableSet.of(84 DISTRIBUTOR_ROLE,85 EVENT_BUS_ROLE,86 HTTPD_ROLE,87 SESSION_QUEUE_ROLE,88 ROUTER_ROLE);89 }90 @Override91 public Set<Object> getFlagObjects() {92 return Collections.emptySet();93 }94 @Override95 protected String getSystemPropertiesConfigPrefix() {96 return "selenium";97 }98 @Override99 protected Config getDefaultConfig() {100 return new DefaultHubConfig();101 }102 @Override103 protected Handlers createHandlers(Config config) {104 LoggingOptions loggingOptions = new LoggingOptions(config);105 Tracer tracer = loggingOptions.getTracer();106 EventBusOptions events = new EventBusOptions(config);107 EventBus bus = events.getEventBus();108 CombinedHandler handler = new CombinedHandler();109 SessionMap sessions = new LocalSessionMap(tracer, bus);110 handler.addHandler(sessions);111 BaseServerOptions serverOptions = new BaseServerOptions(config);112 SecretOptions secretOptions = new SecretOptions(config);113 Secret secret = secretOptions.getRegistrationSecret();114 URL externalUrl;115 try {116 externalUrl = serverOptions.getExternalUri().toURL();117 } catch (MalformedURLException e) {118 throw new IllegalArgumentException(e);119 }120 NetworkOptions networkOptions = new NetworkOptions(config);121 HttpClient.Factory clientFactory = new RoutableHttpClientFactory(122 externalUrl,123 handler,124 networkOptions.getHttpClientFactory(tracer));125 DistributorOptions distributorOptions = new DistributorOptions(config);126 SessionRequestOptions sessionRequestOptions = new SessionRequestOptions(config);127 NewSessionQueue queue = new LocalNewSessionQueue(128 tracer,129 bus,130 distributorOptions.getSlotMatcher(),131 sessionRequestOptions.getSessionRequestRetryInterval(),132 sessionRequestOptions.getSessionRequestTimeout(),133 secret);134 handler.addHandler(queue);135 Distributor distributor = new LocalDistributor(136 tracer,137 bus,138 clientFactory,139 sessions,140 queue,141 distributorOptions.getSlotSelector(),142 secret,143 distributorOptions.getHealthCheckInterval(),144 distributorOptions.shouldRejectUnsupportedCaps());145 handler.addHandler(distributor);146 Router router = new Router(tracer, clientFactory, sessions, queue, distributor);147 GraphqlHandler graphqlHandler = new GraphqlHandler(148 tracer,149 distributor,150 queue,151 serverOptions.getExternalUri(),152 getServerVersion());153 HttpHandler readinessCheck = req -> {154 boolean ready = router.isReady() && bus.isReady();155 return new HttpResponse()156 .setStatus(ready ? HTTP_OK : HTTP_INTERNAL_ERROR)157 .setContent(Contents.utf8String("Router is " + ready));158 };159 Routable ui = new GridUiRoute();160 Routable routerWithSpecChecks = router.with(networkOptions.getSpecComplianceChecks());161 Routable httpHandler = combine(162 ui,163 routerWithSpecChecks,164 Route.prefix("/wd/hub").to(combine(routerWithSpecChecks)),165 Route.options("/graphql").to(() -> graphqlHandler),166 Route.post("/graphql").to(() -> graphqlHandler));167 UsernameAndPassword uap = secretOptions.getServerAuthentication();168 if (uap != null) {169 LOG.info("Requiring authentication to connect");170 httpHandler = httpHandler.with(new BasicAuthenticationFilter(uap.username(), uap.password()));171 }172 // Allow the liveness endpoint to be reached, since k8s doesn't make it easy to authenticate these checks173 httpHandler = combine(httpHandler, Route.get("/readyz").to(() -> readinessCheck));174 return new Handlers(httpHandler, new ProxyCdpIntoGrid(clientFactory, sessions));175 }176 @Override177 protected void execute(Config config) {178 Require.nonNull("Config", config);179 Server<?> server = asServer(config).start();180 LOG.info(String.format("Started Selenium Hub %s: %s", getServerVersion(), server.getUrl()));181 }182 private String getServerVersion() {183 BuildInfo info = new BuildInfo();184 return String.format("%s (revision %s)", info.getReleaseLabel(), info.getBuildRevision());...

Full Screen

Full Screen

Source:RouterServer.java Github

copy

Full Screen

...31import org.openqa.selenium.grid.graphql.GraphqlHandler;32import org.openqa.selenium.grid.log.LoggingOptions;33import org.openqa.selenium.grid.router.ProxyCdpIntoGrid;34import org.openqa.selenium.grid.router.Router;35import org.openqa.selenium.grid.security.BasicAuthenticationFilter;36import org.openqa.selenium.grid.security.Secret;37import org.openqa.selenium.grid.security.SecretOptions;38import org.openqa.selenium.grid.server.BaseServerOptions;39import org.openqa.selenium.grid.server.NetworkOptions;40import org.openqa.selenium.grid.server.Server;41import org.openqa.selenium.grid.sessionmap.SessionMap;42import org.openqa.selenium.grid.sessionmap.config.SessionMapOptions;43import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;44import org.openqa.selenium.grid.sessionqueue.config.NewSessionQueueOptions;45import org.openqa.selenium.grid.sessionqueue.remote.RemoteNewSessionQueue;46import org.openqa.selenium.grid.web.GridUiRoute;47import org.openqa.selenium.internal.Require;48import org.openqa.selenium.remote.http.HttpClient;49import org.openqa.selenium.remote.http.HttpHandler;50import org.openqa.selenium.remote.http.HttpResponse;51import org.openqa.selenium.remote.http.Routable;52import org.openqa.selenium.remote.http.Route;53import org.openqa.selenium.remote.tracing.Tracer;54import java.net.URL;55import java.util.Collections;56import java.util.Set;57import java.util.logging.Logger;58import static java.net.HttpURLConnection.HTTP_NO_CONTENT;59import static org.openqa.selenium.grid.config.StandardGridRoles.DISTRIBUTOR_ROLE;60import static org.openqa.selenium.grid.config.StandardGridRoles.HTTPD_ROLE;61import static org.openqa.selenium.grid.config.StandardGridRoles.ROUTER_ROLE;62import static org.openqa.selenium.grid.config.StandardGridRoles.SESSION_MAP_ROLE;63import static org.openqa.selenium.grid.config.StandardGridRoles.SESSION_QUEUE_ROLE;64import static org.openqa.selenium.net.Urls.fromUri;65import static org.openqa.selenium.remote.http.Route.combine;66import static org.openqa.selenium.remote.http.Route.get;67@AutoService(CliCommand.class)68public class RouterServer extends TemplateGridServerCommand {69 private static final Logger LOG = Logger.getLogger(RouterServer.class.getName());70 @Override71 public String getName() {72 return "router";73 }74 @Override75 public String getDescription() {76 return "Creates a router to front the selenium grid.";77 }78 @Override79 public Set<Role> getConfigurableRoles() {80 return ImmutableSet.of(81 DISTRIBUTOR_ROLE,82 HTTPD_ROLE,83 ROUTER_ROLE,84 SESSION_MAP_ROLE,85 SESSION_QUEUE_ROLE);86 }87 @Override88 public Set<Object> getFlagObjects() {89 return Collections.emptySet();90 }91 @Override92 protected String getSystemPropertiesConfigPrefix() {93 return "router";94 }95 @Override96 protected Config getDefaultConfig() {97 return new MapConfig(ImmutableMap.of("server", ImmutableMap.of("port", 4444)));98 }99 @Override100 protected Handlers createHandlers(Config config) {101 LoggingOptions loggingOptions = new LoggingOptions(config);102 Tracer tracer = loggingOptions.getTracer();103 NetworkOptions networkOptions = new NetworkOptions(config);104 HttpClient.Factory clientFactory = networkOptions.getHttpClientFactory(tracer);105 BaseServerOptions serverOptions = new BaseServerOptions(config);106 SecretOptions secretOptions = new SecretOptions(config);107 Secret secret = secretOptions.getRegistrationSecret();108 SessionMapOptions sessionsOptions = new SessionMapOptions(config);109 SessionMap sessions = sessionsOptions.getSessionMap();110 NewSessionQueueOptions sessionQueueOptions = new NewSessionQueueOptions(config);111 URL sessionQueueUrl = fromUri(sessionQueueOptions.getSessionQueueUri());112 NewSessionQueue queue = new RemoteNewSessionQueue(113 tracer,114 clientFactory.createClient(sessionQueueUrl),115 secret);116 DistributorOptions distributorOptions = new DistributorOptions(config);117 URL distributorUrl = fromUri(distributorOptions.getDistributorUri());118 Distributor distributor = new RemoteDistributor(119 tracer,120 clientFactory,121 distributorUrl,122 secret);123 GraphqlHandler graphqlHandler = new GraphqlHandler(124 tracer,125 distributor,126 queue,127 serverOptions.getExternalUri(),128 getServerVersion());129 Routable ui = new GridUiRoute();130 Routable routerWithSpecChecks = new Router(tracer, clientFactory, sessions, queue, distributor)131 .with(networkOptions.getSpecComplianceChecks());132 Routable route = Route.combine(133 ui,134 routerWithSpecChecks,135 Route.prefix("/wd/hub").to(combine(routerWithSpecChecks)),136 Route.options("/graphql").to(() -> graphqlHandler),137 Route.post("/graphql").to(() -> graphqlHandler));138 UsernameAndPassword uap = secretOptions.getServerAuthentication();139 if (uap != null) {140 LOG.info("Requiring authentication to connect");141 route = route.with(new BasicAuthenticationFilter(uap.username(), uap.password()));142 }143 // Since k8s doesn't make it easy to do an authenticated liveness probe, allow unauthenticated access to it.144 Routable routeWithLiveness = Route.combine(145 route,146 get("/readyz").to(() -> req -> new HttpResponse().setStatus(HTTP_NO_CONTENT)));147 return new Handlers(routeWithLiveness, new ProxyCdpIntoGrid(clientFactory, sessions));148 }149 @Override150 protected void execute(Config config) {151 Require.nonNull("Config", config);152 Server<?> server = asServer(config).start();153 LOG.info(String.format(154 "Started Selenium Router %s: %s", getServerVersion(), server.getUrl()));155 }...

Full Screen

Full Screen

Source:CdpFacadeTest.java Github

copy

Full Screen

...22import org.openqa.selenium.By;23import org.openqa.selenium.HasAuthentication;24import org.openqa.selenium.UsernameAndPassword;25import org.openqa.selenium.environment.webserver.NettyAppServer;26import org.openqa.selenium.grid.security.BasicAuthenticationFilter;27import org.openqa.selenium.remote.http.Contents;28import org.openqa.selenium.remote.http.HttpResponse;29import org.openqa.selenium.remote.http.Route;30import org.openqa.selenium.support.devtools.NetworkInterceptor;31import org.openqa.selenium.testing.NotYetImplemented;32import org.openqa.selenium.testing.drivers.Browser;33import static java.nio.charset.StandardCharsets.UTF_8;34import static org.assertj.core.api.Assertions.assertThat;35import static org.assertj.core.api.Assumptions.assumeThat;36import static org.openqa.selenium.remote.http.Contents.utf8String;37import static org.openqa.selenium.testing.Safely.safelyCall;38public class CdpFacadeTest extends DevToolsTestBase {39 private static NettyAppServer server;40 @BeforeClass41 public static void startServer() {42 server = new NettyAppServer(43 new BasicAuthenticationFilter("test", "test")44 .andFinally(req ->45 new HttpResponse()46 .addHeader("Content-Type", MediaType.HTML_UTF_8.toString())47 .setContent(Contents.string("<h1>authorized</h1>", UTF_8))));48 server.start();49 }50 @AfterClass51 public static void stopServer() {52 safelyCall(() -> server.stop());53 }54 @Test55 @NotYetImplemented(value = Browser.FIREFOX, reason = "Network interception not yet supported")56 public void networkInterceptorAndAuthHandlersDoNotFight() {57 assumeThat(driver).isInstanceOf(HasAuthentication.class);...

Full Screen

Full Screen

Source:HandlersForTests.java Github

copy

Full Screen

...16// under the License.17package org.openqa.selenium.environment.webserver;18import com.google.common.net.MediaType;19import org.openqa.selenium.build.InProject;20import org.openqa.selenium.grid.security.BasicAuthenticationFilter;21import org.openqa.selenium.grid.web.PathResource;22import org.openqa.selenium.grid.web.ResourceHandler;23import org.openqa.selenium.remote.http.Contents;24import org.openqa.selenium.remote.http.HttpRequest;25import org.openqa.selenium.remote.http.HttpResponse;26import org.openqa.selenium.remote.http.Routable;27import org.openqa.selenium.remote.http.Route;28import java.io.UncheckedIOException;29import java.nio.file.Path;30import static java.nio.charset.StandardCharsets.UTF_8;31import static org.openqa.selenium.remote.http.HttpMethod.GET;32public class HandlersForTests implements Routable {33 private static final String TEMP_SRC_CONTEXT_PATH = "/temp";34 private final Route delegate;35 public HandlersForTests(String hostname, int port, Path tempPageDir) {36 CreatePageHandler createPageHandler = new CreatePageHandler(37 tempPageDir,38 hostname,39 port,40 TEMP_SRC_CONTEXT_PATH);41 Routable generatedPages = new ResourceHandler(new PathResource(tempPageDir));42 Path webSrc = InProject.locate("common/src/web");43 Route route = Route.combine(44 Route.get("/basicAuth").to(() -> req ->45 new HttpResponse()46 .addHeader("Content-Type", MediaType.HTML_UTF_8.toString())47 .setContent(Contents.string("<h1>authorized</h1>", UTF_8)))48 .with(new BasicAuthenticationFilter("test", "test")),49 Route.get("/echo").to(EchoHandler::new),50 Route.get("/cookie").to(CookieHandler::new),51 Route.get("/encoding").to(EncodingHandler::new),52 Route.matching(req -> req.getUri().startsWith("/generated/")).to(() -> new GeneratedJsTestHandler("/generated")),53 Route.matching(req -> req.getUri().startsWith("/page/") && req.getMethod() == GET).to(PageHandler::new),54 Route.post("/createPage").to(() -> createPageHandler),55 Route.get("/redirect").to(RedirectHandler::new),56 Route.get("/sleep").to(SleepingHandler::new),57 Route.post("/upload").to(UploadHandler::new),58 Route.matching(req -> req.getUri().startsWith("/utf8/")).to(() -> new Utf8Handler(webSrc, "/utf8/")),59 Route.prefix(TEMP_SRC_CONTEXT_PATH).to(Route.combine(generatedPages)),60 new CommonWebResources());61 delegate = Route.combine(62 route,...

Full Screen

Full Screen

Source:BasicAuthenticationFilter.java Github

copy

Full Screen

...22import java.net.HttpURLConnection;23import java.util.Base64;24import java.util.logging.Logger;25import static java.nio.charset.StandardCharsets.UTF_8;26public class BasicAuthenticationFilter implements Filter {27 private static final Logger LOG = Logger.getLogger(BasicAuthenticationFilter.class.getName());28 private final String passphrase;29 public BasicAuthenticationFilter(String user, String password) {30 passphrase = Base64.getEncoder().encodeToString((user + ":" + password).getBytes(UTF_8));31 }32 @Override33 public HttpHandler apply(HttpHandler next) {34 return req -> {35 Require.nonNull("Request", req);36 if (!isAuthorized(req.getHeader("Authorization"))) {37 LOG.info("Unauthorized request to " + req);38 return new HttpResponse()39 .setStatus(HttpURLConnection.HTTP_UNAUTHORIZED)40 .addHeader("WWW-Authenticate", "Basic realm=\"selenium-server\"");41 }42 return next.execute(req);43 };...

Full Screen

Full Screen

Source:BasicAuthenticationFilterTest.java Github

copy

Full Screen

...23import java.util.Base64;24import static java.nio.charset.StandardCharsets.UTF_8;25import static org.assertj.core.api.Assertions.assertThat;26import static org.openqa.selenium.remote.http.HttpMethod.GET;27public class BasicAuthenticationFilterTest {28 @Test29 public void shouldAskAnUnauthenticatedRequestToAuthenticate() {30 HttpHandler handler = new BasicAuthenticationFilter("cheese", "cheddar").apply(req -> new HttpResponse());31 HttpResponse res = handler.execute(new HttpRequest(GET, "/"));32 assertThat(res.getStatus()).isEqualTo(HttpURLConnection.HTTP_UNAUTHORIZED);33 assertThat(res.getHeader("Www-Authenticate")).startsWith("Basic ");34 assertThat(res.getHeader("Www-Authenticate")).contains("Basic ");35 }36 @Test37 public void shouldAllowAuthenticatedTrafficThrough() {38 HttpHandler handler = new BasicAuthenticationFilter("cheese", "cheddar").apply(req -> new HttpResponse());39 HttpResponse res = handler.execute(40 new HttpRequest(GET, "/")41 .setHeader("Authorization", "Basic " + Base64.getEncoder().encodeToString("cheese:cheddar".getBytes(UTF_8))));42 assertThat(res.isSuccessful()).isTrue();43 }44}...

Full Screen

Full Screen

BasicAuthenticationFilter

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.grid.security.BasicAuthenticationFilter;2import javax.servlet.*;3import javax.servlet.http.HttpServletRequest;4import javax.servlet.http.HttpServletResponse;5import java.io.IOException;6import java.util.Base64;7import java.util.HashMap;8import java.util.Map;9import java.util.Objects;10import java.util.logging.Logger;11public class BasicAuthFilter implements Filter {12 private static final Logger LOG = Logger.getLogger(BasicAuthFilter.class.getName());13 private final Map<String, String> users = new HashMap<>();14 public BasicAuthFilter(Map<String, String> users) {15 this.users.putAll(Objects.requireNonNull(users));16 }17 public void init(FilterConfig filterConfig) throws ServletException {18 }19 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {20 HttpServletRequest req = (HttpServletRequest) request;21 HttpServletResponse resp = (HttpServletResponse) response;22 String header = req.getHeader("Authorization");23 if (header == null || !header.startsWith("Basic ")) {24 unauthorized(resp, "Missing or invalid Authorization header");25 return;26 }27 String[] tokens = extractAndDecodeHeader(header, resp);28 if (tokens == null) {29 return;30 }31 String username = tokens[0];32 String password = tokens[1];33 if (users.containsKey(username) && users.get(username).equals(password)) {34 chain.doFilter(request, response);35 } else {36 unauthorized(resp, "Invalid authentication token");37 }38 }39 private String[] extractAndDecodeHeader(String header, HttpServletResponse response) throws IOException {40 byte[] base64Token = header.substring(6).getBytes("UTF-8");41 byte[] decoded;42 try {43 decoded = Base64.getDecoder().decode(base64Token);44 } catch (IllegalArgumentException e) {45 unauthorized(response, "Failed to decode basic authentication token");46 return null;47 }48 String token = new String(decoded, "UTF-8");49 int delim = token.indexOf(":");50 if (delim == -1) {51 unauthorized(response, "Invalid basic authentication token");52 return null;53 }54 return new String[]{token.substring(0, delim), token.substring(delim + 1)};55 }56 private void unauthorized(HttpServletResponse response, String message) throws IOException {57 response.addHeader("WWW-Authenticate", "Basic realm=\"Selenium Grid\"");58 response.sendError(HttpServletResponse.SC_UNAUTHORIZED,

Full Screen

Full Screen

BasicAuthenticationFilter

Using AI Code Generation

copy

Full Screen

1package com.selenium.grid;2import org.openqa.selenium.grid.security.BasicAuthenticationFilter;3import org.openqa.selenium.grid.security.BasicCredentials;4import org.openqa.selenium.grid.web.HttpHandler;5import org.openqa.selenium.grid.web.HttpRequest;6import org.openqa.selenium.grid.web.HttpResponse;7import org.openqa.selenium.remote.http.HttpMethod;8import java.io.IOException;9import java.util.Collections;10import java.util.Optional;11public class CustomAuthenticationFilter implements HttpHandler {12 private final HttpHandler handler;13 public CustomAuthenticationFilter(HttpHandler handler) {14 this.handler = handler;15 }16 public HttpResponse execute(HttpRequest req) throws IOException {17 if (req.getMethod() == HttpMethod.GET) {18 return handler.execute(req);19 }20 Optional<BasicCredentials> creds = BasicAuthenticationFilter.getCredentials(req);21 if (!creds.isPresent()) {22 return BasicAuthenticationFilter.unauthorizedResponse();23 }24 if (creds.get().getUsername().equals("foo") &&25 creds.get().getPassword().equals("bar")) {26 return handler.execute(req);27 }28 return BasicAuthenticationFilter.unauthorizedResponse();29 }30}31public class CustomAuthenticationFilterTest {32 public static void main(String[] args) {33 HttpHandler handler = new CustomAuthenticationFilter(new HttpHandler() {34 public HttpResponse execute(HttpRequest req) throws IOException {35 return new HttpResponse().setContent("Hello, world!");36 }37 });38 HttpRequest req = new HttpRequest(HttpMethod.GET, "/foo");39 HttpResponse resp = handler.execute(req);40 System.out.println(resp.getContentString());41 req = new HttpRequest(HttpMethod.GET, "/foo", Collections.singletonMap("Authorization", "Basic " + BasicAuthenticationFilter.encode("foo", "bar")));42 resp = handler.execute(req);43 System.out.println(resp.getContentString());44 req = new HttpRequest(HttpMethod.GET, "/foo", Collections.singletonMap("Authorization", "Basic " + BasicAuthenticationFilter.encode("foo", "baz")));45 resp = handler.execute(req);46 System.out.println(resp.getContentString());47 }48}

Full Screen

Full Screen

BasicAuthenticationFilter

Using AI Code Generation

copy

Full Screen

1@ContextConfiguration(classes = {BasicAuthenticationFilter.class})2public class BasicAuthenticationFilterTest {3 private HttpServletRequest request;4 private HttpServletResponse response;5 private FilterChain chain;6 private BasicAuthenticationFilter filter;7 public void shouldNotSetCredentialsIfNoAuthorizationHeader() throws IOException, ServletException {8 filter.doFilter(request, response, chain);9 verify(request, never()).setAttribute(anyString(), any());10 verify(chain).doFilter(request, response);11 }12 public void shouldNotSetCredentialsIfNoBasicAuthorizationHeader() throws IOException, ServletException {13 when(request.getHeader("Authorization")).thenReturn("Digest foo");14 filter.doFilter(request, response, chain);15 verify(request, never()).setAttribute(anyString(), any());16 verify(chain).doFilter(request, response);17 }18 public void shouldNotSetCredentialsIfNoBase64BasicAuthorizationHeader() throws IOException, ServletException {19 when(request.getHeader("Authorization")).thenReturn("Basic foo");20 filter.doFilter(request, response, chain);21 verify(request, never()).setAttribute(anyString(), any());22 verify(chain).doFilter(request, response);23 }24 public void shouldNotSetCredentialsIfNoUsernamePassword() throws IOException, ServletException {25 when(request.getHeader("Authorization")).thenReturn("Basic " + Base64.getEncoder().encodeToString(":".getBytes(UTF_8)));26 filter.doFilter(request, response, chain);27 verify(request, never()).setAttribute(anyString(), any());28 verify(chain).doFilter(request, response);29 }30 public void shouldNotSetCredentialsIfNoUsername() throws IOException, ServletException {31 when(request.getHeader("Authorization")).thenReturn("Basic " + Base64.getEncoder().encodeToString(":password".getBytes(UTF_8)));32 filter.doFilter(request, response, chain);33 verify(request, never()).setAttribute(anyString(), any());34 verify(chain).doFilter(request, response);35 }36 public void shouldNotSetCredentialsIfNoPassword() throws IOException, ServletException {37 when(request.getHeader("Authorization")).thenReturn("Basic " + Base64.getEncoder().encodeToString("username:".getBytes(UTF_8)));38 filter.doFilter(request, response, chain);39 verify(request, never()).setAttribute(anyString(), any());40 verify(chain).doFilter(request, response);41 }

Full Screen

Full Screen

BasicAuthenticationFilter

Using AI Code Generation

copy

Full Screen

1> import org.openqa.selenium.grid.security.BasicAuthenticationFilter;2> import org.openqa.selenium.remote.http.Filter;3> import org.openqa.selenium.remote.http.HttpHandler;4> import java.util.Collections;5> public class Example {6> public static void main(String[] args) {7> Filter filter = new BasicAuthenticationFilter(8> Collections.singletonList("user:password"),9> "Selenium Grid");10> handler = filter.apply(handler);11> }12> }

Full Screen

Full Screen
copy
1public static class StopwatchTest {2 private static final Logger logger = Logger.getLogger("");34 private static void logInfo(Description description, String status, long nanos) {5 String testName = description.getMethodName();6 logger.info(String.format("Test %s %s, spent %d microseconds",7 testName, status, TimeUnit.NANOSECONDS.toMicros(nanos)));8 }910 @Rule11 public Stopwatch stopwatch = new Stopwatch() {12 @Override13 protected void succeeded(long nanos, Description description) {14 logInfo(description, "succeeded", nanos);15 }1617 @Override18 protected void failed(long nanos, Throwable e, Description description) {19 logInfo(description, "failed", nanos);20 }2122 @Override23 protected void skipped(long nanos, AssumptionViolatedException e, Description description) {24 logInfo(description, "skipped", nanos);25 }2627 @Override28 protected void finished(long nanos, Description description) {29 logInfo(description, "finished", nanos);30 }31 };3233 @Test34 public void succeeds() {35 }3637 @Test38 public void fails() {39 fail();40 }4142 @Test43 public void skips() {44 assumeTrue(false);45 }4647 @Test48 public void performanceTest() throws InterruptedException {49 // An example to assert runtime:50 long delta = 30;51 Thread.sleep(300L);52 assertEquals(300d, stopwatch.runtime(MILLISECONDS), delta);53 Thread.sleep(500L);54 assertEquals(800d, stopwatch.runtime(MILLISECONDS), delta);55 }56}57
Full Screen
copy
1import com.google.common.base.Stopwatch;23final Stopwatch stopwatch = Stopwatch.createStarted();4//dostuff5System.out.println("Time of execution in seconds:" + stopwatch.stop().elapsed(TimeUnit.SECONDS));6
Full Screen
copy
1Stopwatch stopwatch = createStarted();2firstCommandToBeTimed();3secondCommandToBeTimed();4assertThat(stopwatch.elapsed(TimeUnit.MILLISECONDS)).isLessThan(500);5
Full Screen

Selenium 4 Tutorial:

LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.

Chapters:

  1. Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.

  2. What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.

  3. Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.

  4. Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.

  5. How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.

  6. Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.

  7. Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.

Selenium 101 certifications:

LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used methods in BasicAuthenticationFilter

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful