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

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

Run Selenium automation tests on LambdaTest cloud grid

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

copy
1// Licensed to the Software Freedom Conservancy (SFC) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The SFC licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18package org.openqa.selenium.grid.security;
19
20import org.openqa.selenium.internal.Require;
21import org.openqa.selenium.remote.http.Filter;
22import org.openqa.selenium.remote.http.HttpHandler;
23import org.openqa.selenium.remote.http.HttpResponse;
24
25import java.net.HttpURLConnection;
26import java.util.Base64;
27import java.util.logging.Logger;
28
29import static java.nio.charset.StandardCharsets.UTF_8;
30
31public class BasicAuthenticationFilter implements Filter {
32
33  private static final Logger LOG = Logger.getLogger(BasicAuthenticationFilter.class.getName());
34  private final String passphrase;
35
36  public BasicAuthenticationFilter(String user, String password) {
37    passphrase = Base64.getEncoder().encodeToString((user + ":" + password).getBytes(UTF_8));
38  }
39
40  @Override
41  public HttpHandler apply(HttpHandler next) {
42    return req -> {
43      Require.nonNull("Request", req);
44
45      if (!isAuthorized(req.getHeader("Authorization"))) {
46        LOG.info("Unauthorized request to " + req);
47        return new HttpResponse()
48          .setStatus(HttpURLConnection.HTTP_UNAUTHORIZED)
49          .addHeader("WWW-Authenticate", "Basic realm=\"selenium-server\"");
50      }
51
52      return next.execute(req);
53    };
54  }
55
56  private boolean isAuthorized(String auth) {
57    if (auth != null) {
58      final int index = auth.indexOf(' ') + 1;
59
60      if (index > 0) {
61        return passphrase.equals(auth.substring(index));
62      }
63    }
64
65    return false;
66  }
67}
68
Full Screen
copy
1// Licensed to the Software Freedom Conservancy (SFC) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The SFC licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18package org.openqa.selenium.grid.router.httpd;
19
20import com.google.auto.service.AutoService;
21import com.google.common.collect.ImmutableMap;
22import com.google.common.collect.ImmutableSet;
23import org.openqa.selenium.BuildInfo;
24import org.openqa.selenium.UsernameAndPassword;
25import org.openqa.selenium.cli.CliCommand;
26import org.openqa.selenium.grid.TemplateGridServerCommand;
27import org.openqa.selenium.grid.config.Config;
28import org.openqa.selenium.grid.config.MapConfig;
29import org.openqa.selenium.grid.config.Role;
30import org.openqa.selenium.grid.distributor.Distributor;
31import org.openqa.selenium.grid.distributor.config.DistributorOptions;
32import org.openqa.selenium.grid.distributor.remote.RemoteDistributor;
33import org.openqa.selenium.grid.graphql.GraphqlHandler;
34import org.openqa.selenium.grid.log.LoggingOptions;
35import org.openqa.selenium.grid.router.ProxyCdpIntoGrid;
36import org.openqa.selenium.grid.router.Router;
37import org.openqa.selenium.grid.security.BasicAuthenticationFilter;
38import org.openqa.selenium.grid.security.Secret;
39import org.openqa.selenium.grid.security.SecretOptions;
40import org.openqa.selenium.grid.server.BaseServerOptions;
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.config.SessionMapOptions;
45import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;
46import org.openqa.selenium.grid.sessionqueue.config.NewSessionQueueOptions;
47import org.openqa.selenium.grid.sessionqueue.remote.RemoteNewSessionQueue;
48import org.openqa.selenium.grid.web.GridUiRoute;
49import org.openqa.selenium.internal.Require;
50import org.openqa.selenium.remote.http.HttpClient;
51import org.openqa.selenium.remote.http.HttpHandler;
52import org.openqa.selenium.remote.http.HttpResponse;
53import org.openqa.selenium.remote.http.Routable;
54import org.openqa.selenium.remote.http.Route;
55import org.openqa.selenium.remote.tracing.Tracer;
56
57import java.net.URL;
58import java.util.Collections;
59import java.util.Set;
60import java.util.logging.Logger;
61
62import static java.net.HttpURLConnection.HTTP_NO_CONTENT;
63import static org.openqa.selenium.grid.config.StandardGridRoles.DISTRIBUTOR_ROLE;
64import static org.openqa.selenium.grid.config.StandardGridRoles.HTTPD_ROLE;
65import static org.openqa.selenium.grid.config.StandardGridRoles.ROUTER_ROLE;
66import static org.openqa.selenium.grid.config.StandardGridRoles.SESSION_MAP_ROLE;
67import static org.openqa.selenium.grid.config.StandardGridRoles.SESSION_QUEUE_ROLE;
68import static org.openqa.selenium.net.Urls.fromUri;
69import static org.openqa.selenium.remote.http.Route.combine;
70import static org.openqa.selenium.remote.http.Route.get;
71
72@AutoService(CliCommand.class)
73public class RouterServer extends TemplateGridServerCommand {
74
75  private static final Logger LOG = Logger.getLogger(RouterServer.class.getName());
76
77  @Override
78  public String getName() {
79    return "router";
80  }
81
82  @Override
83  public String getDescription() {
84    return "Creates a router to front the selenium grid.";
85  }
86
87  @Override
88  public Set<Role> getConfigurableRoles() {
89    return ImmutableSet.of(
90        DISTRIBUTOR_ROLE,
91        HTTPD_ROLE,
92        ROUTER_ROLE,
93        SESSION_MAP_ROLE,
94        SESSION_QUEUE_ROLE);
95  }
96
97  @Override
98  public Set<Object> getFlagObjects() {
99    return Collections.emptySet();
100  }
101
102  @Override
103  protected String getSystemPropertiesConfigPrefix() {
104    return "router";
105  }
106
107  @Override
108  protected Config getDefaultConfig() {
109    return new MapConfig(ImmutableMap.of("server", ImmutableMap.of("port", 4444)));
110  }
111
112  @Override
113  protected Handlers createHandlers(Config config) {
114    LoggingOptions loggingOptions = new LoggingOptions(config);
115    Tracer tracer = loggingOptions.getTracer();
116
117    NetworkOptions networkOptions = new NetworkOptions(config);
118    HttpClient.Factory clientFactory = networkOptions.getHttpClientFactory(tracer);
119
120    BaseServerOptions serverOptions = new BaseServerOptions(config);
121    SecretOptions secretOptions = new SecretOptions(config);
122    Secret secret = secretOptions.getRegistrationSecret();
123
124    SessionMapOptions sessionsOptions = new SessionMapOptions(config);
125    SessionMap sessions = sessionsOptions.getSessionMap();
126
127    NewSessionQueueOptions sessionQueueOptions = new NewSessionQueueOptions(config);
128    URL sessionQueueUrl = fromUri(sessionQueueOptions.getSessionQueueUri());
129    NewSessionQueue queue = new RemoteNewSessionQueue(
130      tracer,
131      clientFactory.createClient(sessionQueueUrl),
132      secret);
133
134    DistributorOptions distributorOptions = new DistributorOptions(config);
135    URL distributorUrl = fromUri(distributorOptions.getDistributorUri());
136    Distributor distributor = new RemoteDistributor(
137      tracer,
138      clientFactory,
139      distributorUrl,
140      secret);
141
142    GraphqlHandler graphqlHandler = new GraphqlHandler(
143      tracer,
144      distributor,
145      queue,
146      serverOptions.getExternalUri(),
147      getServerVersion());
148
149    Routable ui = new GridUiRoute();
150    Routable routerWithSpecChecks = new Router(tracer, clientFactory, sessions, queue, distributor)
151      .with(networkOptions.getSpecComplianceChecks());
152
153    Routable route = Route.combine(
154      ui,
155      routerWithSpecChecks,
156      Route.prefix("/wd/hub").to(combine(routerWithSpecChecks)),
157      Route.options("/graphql").to(() -> graphqlHandler),
158      Route.post("/graphql").to(() -> graphqlHandler));
159
160    UsernameAndPassword uap = secretOptions.getServerAuthentication();
161    if (uap != null) {
162      LOG.info("Requiring authentication to connect");
163      route = route.with(new BasicAuthenticationFilter(uap.username(), uap.password()));
164    }
165
166    // Since k8s doesn't make it easy to do an authenticated liveness probe, allow unauthenticated access to it.
167    Routable routeWithLiveness = Route.combine(
168      route,
169      get("/readyz").to(() -> req -> new HttpResponse().setStatus(HTTP_NO_CONTENT)));
170
171    return new Handlers(routeWithLiveness, new ProxyCdpIntoGrid(clientFactory, sessions));
172  }
173
174  @Override
175  protected void execute(Config config) {
176    Require.nonNull("Config", config);
177
178    Server<?> server = asServer(config).start();
179
180    LOG.info(String.format(
181      "Started Selenium Router %s: %s", getServerVersion(), server.getUrl()));
182  }
183
184  private String getServerVersion() {
185    BuildInfo info = new BuildInfo();
186    return String.format("%s (revision %s)", info.getReleaseLabel(), info.getBuildRevision());
187  }
188}
189
Full Screen
copy
1// Licensed to the Software Freedom Conservancy (SFC) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The SFC licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18package org.openqa.selenium.grid.commands;
19
20import com.google.auto.service.AutoService;
21import com.google.common.collect.ImmutableSet;
22import org.openqa.selenium.BuildInfo;
23import org.openqa.selenium.UsernameAndPassword;
24import org.openqa.selenium.cli.CliCommand;
25import org.openqa.selenium.events.EventBus;
26import org.openqa.selenium.grid.TemplateGridServerCommand;
27import org.openqa.selenium.grid.config.Config;
28import org.openqa.selenium.grid.config.Role;
29import org.openqa.selenium.grid.distributor.Distributor;
30import org.openqa.selenium.grid.distributor.config.DistributorOptions;
31import org.openqa.selenium.grid.distributor.local.LocalDistributor;
32import org.openqa.selenium.grid.graphql.GraphqlHandler;
33import org.openqa.selenium.grid.log.LoggingOptions;
34import org.openqa.selenium.grid.node.Node;
35import org.openqa.selenium.grid.node.ProxyNodeCdp;
36import org.openqa.selenium.grid.node.config.NodeOptions;
37import org.openqa.selenium.grid.router.Router;
38import org.openqa.selenium.grid.security.BasicAuthenticationFilter;
39import org.openqa.selenium.grid.security.Secret;
40import org.openqa.selenium.grid.security.SecretOptions;
41import org.openqa.selenium.grid.server.BaseServerOptions;
42import org.openqa.selenium.grid.server.EventBusOptions;
43import org.openqa.selenium.grid.server.NetworkOptions;
44import org.openqa.selenium.grid.server.Server;
45import org.openqa.selenium.grid.sessionmap.SessionMap;
46import org.openqa.selenium.grid.sessionmap.local.LocalSessionMap;
47import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;
48import org.openqa.selenium.grid.sessionqueue.config.SessionRequestOptions;
49import org.openqa.selenium.grid.sessionqueue.local.LocalNewSessionQueue;
50import org.openqa.selenium.grid.web.CombinedHandler;
51import org.openqa.selenium.grid.web.GridUiRoute;
52import org.openqa.selenium.grid.web.RoutableHttpClientFactory;
53import org.openqa.selenium.internal.Require;
54import org.openqa.selenium.remote.http.Contents;
55import org.openqa.selenium.remote.http.HttpClient;
56import org.openqa.selenium.remote.http.HttpHandler;
57import org.openqa.selenium.remote.http.HttpResponse;
58import org.openqa.selenium.remote.http.Routable;
59import org.openqa.selenium.remote.http.Route;
60import org.openqa.selenium.remote.tracing.Tracer;
61
62import java.net.MalformedURLException;
63import java.net.URI;
64import java.net.URL;
65import java.util.Collections;
66import java.util.Set;
67import java.util.logging.Logger;
68
69import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;
70import static java.net.HttpURLConnection.HTTP_OK;
71import static org.openqa.selenium.grid.config.StandardGridRoles.DISTRIBUTOR_ROLE;
72import static org.openqa.selenium.grid.config.StandardGridRoles.HTTPD_ROLE;
73import static org.openqa.selenium.grid.config.StandardGridRoles.NODE_ROLE;
74import static org.openqa.selenium.grid.config.StandardGridRoles.ROUTER_ROLE;
75import static org.openqa.selenium.grid.config.StandardGridRoles.SESSION_QUEUE_ROLE;
76import static org.openqa.selenium.remote.http.Route.combine;
77
78@AutoService(CliCommand.class)
79public class Standalone extends TemplateGridServerCommand {
80
81  private static final Logger LOG = Logger.getLogger("selenium");
82
83  @Override
84  public String getName() {
85    return "standalone";
86  }
87
88  @Override
89  public String getDescription() {
90    return "The selenium server, running everything in-process.";
91  }
92
93  @Override
94  public Set<Role> getConfigurableRoles() {
95    return ImmutableSet.of(DISTRIBUTOR_ROLE, HTTPD_ROLE, NODE_ROLE, ROUTER_ROLE, SESSION_QUEUE_ROLE);
96  }
97
98  @Override
99  public Set<Object> getFlagObjects() {
100    return Collections.singleton(new StandaloneFlags());
101  }
102
103  @Override
104  protected String getSystemPropertiesConfigPrefix() {
105    return "selenium";
106  }
107
108  @Override
109  protected Config getDefaultConfig() {
110    return new DefaultStandaloneConfig();
111  }
112
113  @Override
114  protected Handlers createHandlers(Config config) {
115    LoggingOptions loggingOptions = new LoggingOptions(config);
116    Tracer tracer = loggingOptions.getTracer();
117
118    EventBusOptions events = new EventBusOptions(config);
119    EventBus bus = events.getEventBus();
120
121    BaseServerOptions serverOptions = new BaseServerOptions(config);
122    SecretOptions secretOptions = new SecretOptions(config);
123    Secret registrationSecret = secretOptions.getRegistrationSecret();
124
125    URI localhost = serverOptions.getExternalUri();
126    URL localhostUrl;
127    try {
128      localhostUrl = localhost.toURL();
129    } catch (MalformedURLException e) {
130      throw new IllegalArgumentException(e);
131    }
132
133    NetworkOptions networkOptions = new NetworkOptions(config);
134    CombinedHandler combinedHandler = new CombinedHandler();
135    HttpClient.Factory clientFactory = new RoutableHttpClientFactory(
136      localhostUrl,
137      combinedHandler,
138      networkOptions.getHttpClientFactory(tracer));
139
140    SessionMap sessions = new LocalSessionMap(tracer, bus);
141    combinedHandler.addHandler(sessions);
142
143    DistributorOptions distributorOptions = new DistributorOptions(config);
144    SessionRequestOptions sessionRequestOptions = new SessionRequestOptions(config);
145    NewSessionQueue queue = new LocalNewSessionQueue(
146      tracer,
147      bus,
148      distributorOptions.getSlotMatcher(),
149      sessionRequestOptions.getSessionRequestRetryInterval(),
150      sessionRequestOptions.getSessionRequestTimeout(),
151      registrationSecret);
152    combinedHandler.addHandler(queue);
153
154    Distributor distributor = new LocalDistributor(
155      tracer,
156      bus,
157      clientFactory,
158      sessions,
159      queue,
160      distributorOptions.getSlotSelector(),
161      registrationSecret,
162      distributorOptions.getHealthCheckInterval(),
163      distributorOptions.shouldRejectUnsupportedCaps());
164    combinedHandler.addHandler(distributor);
165
166    Routable router = new Router(tracer, clientFactory, sessions, queue, distributor)
167      .with(networkOptions.getSpecComplianceChecks());
168
169    HttpHandler readinessCheck = req -> {
170      boolean ready = sessions.isReady() && distributor.isReady() && bus.isReady();
171      return new HttpResponse()
172        .setStatus(ready ? HTTP_OK : HTTP_INTERNAL_ERROR)
173        .setContent(Contents.utf8String("Standalone is " + ready));
174    };
175
176    GraphqlHandler graphqlHandler = new GraphqlHandler(
177      tracer,
178      distributor,
179      queue,
180      serverOptions.getExternalUri(),
181      getFormattedVersion());
182
183    Routable ui = new GridUiRoute();
184
185    Routable httpHandler = combine(
186      ui,
187      router,
188      Route.prefix("/wd/hub").to(combine(router)),
189      Route.options("/graphql").to(() -> graphqlHandler),
190      Route.post("/graphql").to(() -> graphqlHandler));
191
192    UsernameAndPassword uap = secretOptions.getServerAuthentication();
193    if (uap != null) {
194      LOG.info("Requiring authentication to connect");
195      httpHandler = httpHandler.with(new BasicAuthenticationFilter(uap.username(), uap.password()));
196    }
197
198    // Allow the liveness endpoint to be reached, since k8s doesn't make it easy to authenticate these checks
199    httpHandler = combine(httpHandler, Route.get("/readyz").to(() -> readinessCheck));
200
201    Node node = new NodeOptions(config).getNode();
202    combinedHandler.addHandler(node);
203    distributor.add(node);
204
205    return new Handlers(httpHandler, new ProxyNodeCdp(clientFactory, node));
206  }
207
208  @Override
209  protected void execute(Config config) {
210    Require.nonNull("Config", config);
211
212    Server<?> server = asServer(config).start();
213
214    LOG.info(String.format(
215      "Started Selenium Standalone %s: %s",
216      getFormattedVersion(),
217      server.getUrl()));
218  }
219
220  private String getFormattedVersion() {
221    BuildInfo info = new BuildInfo();
222    return String.format("%s (revision %s)", info.getReleaseLabel(), info.getBuildRevision());
223  }
224}
225
Full Screen
copy
1public class AuthenticationFilter extends GenericFilterBean {
2    @Override
3    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
4        final String authTokenHeader = ((HttpServletRequest)request).getHeader(Constants.AUTH_HEADER_NAME);
5
6        if (authTokenHeader != null) {
7            SecurityContextHolder.getContext().setAuthentication(createAuthenticationToken(authTokenHeader));
8        }
9
10        chain.doFilter( request, response );
11    }
12}
13
Full Screen
copy
1@Configuration
2@EnableWebSecurity
3public class SecurityConfig extends WebSecurityConfigurerAdapter
4{
5
6    @Override
7    public void configure(final AuthenticationManagerBuilder auth) throws Exception
8    {
9        auth.userDetailsService(this.participantService).passwordEncoder(this.passwordEncoder());
10    }
11
12    @Override
13    protected void configure(final HttpSecurity http) throws Exception
14    {
15
16        //Implementing Token based authentication in this filter
17        final TokenAuthenticationFilter tokenFilter = new TokenAuthenticationFilter();
18        http.addFilterBefore(tokenFilter, BasicAuthenticationFilter.class);
19
20        //Creating token when basic authentication is successful and the same token can be used to authenticate for further requests
21        final CustomBasicAuthenticationFilter customBasicAuthFilter = new CustomBasicAuthenticationFilter(this.authenticationManager() );
22        http.addFilter(customBasicAuthFilter);
23
24    }
25}
26
Full Screen
copy
1    public class TokenAuthenticationFilter extends GenericFilterBean
2    {
3
4
5        @Override
6        public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
7                throws IOException, ServletException
8        {
9            final HttpServletRequest httpRequest = (HttpServletRequest)request;
10
11             //extract token from header
12            final String accessToken = httpRequest.getHeader("header-name");
13            if (null != accessToken) {
14           //get and check whether token is valid ( from DB or file wherever you are storing the token)
15
16          //Populate SecurityContextHolder by fetching relevant information using token
17               final User user = new User(
18                            "username",
19                            "password",
20                            true,
21                            true,
22                            true,
23                            true,
24                            authorities);
25                    final UsernamePasswordAuthenticationToken authentication =
26                            new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
27                    SecurityContextHolder.getContext().setAuthentication(authentication);
28
29            }
30
31            chain.doFilter(request, response);
32        }
33
34      }
35
Full Screen
copy
1@Component
2public class CustomBasicAuthenticationFilter extends BasicAuthenticationFilter {
3
4
5    @Autowired
6    public CustomBasicAuthenticationFilter(final AuthenticationManager authenticationManager) {
7        super(authenticationManager);
8    }
9
10    @Override
11    protected void onSuccessfulAuthentication(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response, final Authentication authResult) {
12        //Generate Token
13        //Save the token for the logged in user
14        //send token in the response
15        response.setHeader("header-name" , "token");
16
17
18    }
19
20}
21
Full Screen
copy
1public JWTAuthenticationFilter(AuthenticationManager authenticationManager, ApplicationContext ctx) {
2    this.authenticationManager = authenticationManager;
3    this.tokenService= ctx.getBean(TokenService.class);
4}
5
Full Screen
copy
1@Override
2protected void configure(HttpSecurity http) throws Exception {
3http.cors().and().csrf().disable()
4        // .. some settings
5        .addFilter(new JWTAuthenticationFilter(authenticationManager(), getApplicationContext()))
6        // some other settings    
7}
8
Full Screen
copy
1@Bean
2public JWTAuthenticationFilter jwtAuthFilter() throws Exception {
3    return new JWTAuthenticationFilter(authenticationManager(), getApplicationContext());
4}
5
Full Screen
copy
1<?xml version="1.0" encoding="UTF-8"?>
2<beans
3    xmlns="http://www.springframework.org/schema/beans"
4    xmlns:sec="http://www.springframework.org/schema/security"
5    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
6    xmlns:context="http://www.springframework.org/schema/context"
7    xmlns:p="http://www.springframework.org/schema/p"
8    xsi:schemaLocation="
9        http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
10        http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-3.0.xsd
11        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">
12
13    <!-- AspectJ pointcut expression that locates our "post" method and applies security that way
14    <protect-pointcut expression="execution(* bigbank.*Service.post*(..))" access="ROLE_TELLER"/>-->
15    <sec:global-method-security secured-annotations="enabled"/>
16
17    <bean id="basicAuthenticationFilter"
18          class="org.springframework.security.web.authentication.www.BasicAuthenticationFilter"
19          p:authenticationManager-ref="authenticationManager"
20          p:authenticationEntryPoint-ref="basicAuthenticationEntryPoint" />
21
22    <bean id="basicAuthenticationEntryPoint"
23          class="webapp.PlainTextBasicAuthenticationEntryPoint"
24          p:realmName="myWebapp"/>
25
26    <bean id="formAuthenticationEntryPoint"
27          class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint"
28          p:loginFormUrl="/login.jsp"/>
29
30    <bean id="daep" class="org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint">
31        <constructor-arg>
32            <map>
33                <entry key="hasHeader('User-Agent','Mozilla') or hasHeader('User-Agent','Opera') or hasHeader('User-Agent','Explorer')" value-ref="formAuthenticationEntryPoint" />
34            </map>
35        </constructor-arg>
36        <property name="defaultEntryPoint" ref="basicAuthenticationEntryPoint"/>
37    </bean>
38
39    <sec:http entry-point-ref="daep">
40        <sec:intercept-url pattern="/login.jsp*" filters="none"/>
41        <sec:intercept-url pattern="/json" access="ROLE_USER,ROLE_ADMIN"  />
42        <sec:intercept-url pattern="/json/*" access="ROLE_USER,ROLE_ADMIN"  />
43        <sec:logout
44            logout-url="/logout"
45            logout-success-url="/home.jsp"/>
46        <sec:form-login
47            login-page="/login.jsp"
48            login-processing-url="/login"
49            authentication-failure-url="/login.jsp?login_error=1" default-target-url="/home.jsp"/>
50        <sec:custom-filter position="BASIC_AUTH_FILTER" ref="basicAuthenticationFilter" />
51    </sec:http>
52
53    <sec:authentication-manager alias="authenticationManager">
54        <sec:authentication-provider>
55        ...
56        </sec:authentication-provider>
57    </sec:authentication-manager>
58
59</beans>
60
Full Screen
copy
1import java.io.IOException;
2import java.io.PrintWriter;
3import javax.servlet.ServletException;
4import javax.servlet.http.HttpServletRequest;
5import javax.servlet.http.HttpServletResponse;
6import org.springframework.security.core.AuthenticationException;
7import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
8
9public class PlainTextBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
10
11    @Override
12    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
13        response.addHeader("WWW-Authenticate", "Basic realm=\"" + getRealmName() + "\"");
14        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
15        PrintWriter writer = response.getWriter();
16        writer.println("HTTP Status " + HttpServletResponse.SC_UNAUTHORIZED + " - " + authException.getMessage());
17    }
18}
19
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Most used methods in BasicAuthenticationFilter

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)