How to use JWTAuthenticationFilter class of com.testsigma.security package

Best Testsigma code snippet using com.testsigma.security.JWTAuthenticationFilter

Source:WebSecurityConfig.java Github

copy

Full Screen

...4 *****************************************************************************/5package com.testsigma.config;6import com.testsigma.security.AjaxLoginFailureHandler;7import com.testsigma.security.AjaxLoginSuccessHandler;8import com.testsigma.security.JWTAuthenticationFilter;9import com.testsigma.security.api.AgentJwtAuthenticationFilter;10import com.testsigma.security.api.RestAuthenticationEntryPoint;11import com.testsigma.service.AuthUserService;12import com.testsigma.service.JWTTokenService;13import lombok.RequiredArgsConstructor;14import org.apache.commons.lang3.StringUtils;15import org.springframework.beans.factory.annotation.Autowired;16import org.springframework.beans.factory.annotation.Value;17import org.springframework.context.annotation.Bean;18import org.springframework.context.annotation.Configuration;19import org.springframework.http.HttpMethod;20import org.springframework.http.HttpStatus;21import org.springframework.security.authentication.AuthenticationManager;22import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;23import org.springframework.security.config.annotation.web.builders.HttpSecurity;24import org.springframework.security.config.annotation.web.builders.WebSecurity;25import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;26import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;27import org.springframework.security.config.http.SessionCreationPolicy;28import org.springframework.security.config.oauth2.client.CommonOAuth2Provider;29import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;30import org.springframework.security.oauth2.client.registration.ClientRegistration;31import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;32import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;33import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository;34import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;35import org.springframework.security.web.AuthenticationEntryPoint;36import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;37import org.springframework.security.web.authentication.logout.HttpStatusReturningLogoutSuccessHandler;38import org.springframework.security.web.util.matcher.AntPathRequestMatcher;39import javax.validation.constraints.NotNull;40import static com.testsigma.config.AjaxLoginFormConfigurer.ajaxLogin;41@Configuration42@EnableWebSecurity43@RequiredArgsConstructor(onConstructor = @__(@Autowired))44public class WebSecurityConfig extends WebSecurityConfigurerAdapter {45 private final static String JSESSIONID_COOKIE = "JSESSIONID";46 private final AuthUserService authUserService;47 private final AuthenticationConfigProperties authenticationConfigProperties;48 private final AdditionalPropertiesConfig additionalPropertiesConfig;49 @Value("${testsigma.csrf.header:X-C}")50 String headerName;51 @Bean52 public BCryptPasswordEncoder bCryptPasswordEncoder() {53 return new BCryptPasswordEncoder();54 }55 @Autowired56 public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {57 BCryptPasswordEncoder bCryptPasswordEncoder = bCryptPasswordEncoder();58 auth.userDetailsService(authUserService).passwordEncoder(bCryptPasswordEncoder);59 authUserService.setBCryptPasswordEncoder(bCryptPasswordEncoder);60 }61 @Bean62 public AuthenticationEntryPoint authenticationEntryPoint() {63 return new RestAuthenticationEntryPoint();64 }65 @Bean66 @Override67 public AuthenticationManager authenticationManagerBean() throws Exception {68 return super.authenticationManagerBean();69 }70 @NotNull71 @Bean72 public AjaxLoginSuccessHandler ajaxLoginSuccessHandler() {73 return new AjaxLoginSuccessHandler();74 }75 @NotNull76 @Bean77 public AjaxLoginFailureHandler ajaxLoginFailureHandler() {78 return new AjaxLoginFailureHandler();79 }80 @Bean81 public JWTAuthenticationFilter jwtAuthenticationFilter() throws Exception {82 JWTAuthenticationFilter filter = new JWTAuthenticationFilter("/**/*");83 filter.setAuthenticationManager(super.authenticationManagerBean());84 return filter;85 }86 @Bean87 public com.testsigma.security.api.APIAuthenticationFilter apiJwtAuthenticationFilter() throws Exception {88 com.testsigma.security.api.APIAuthenticationFilter filter = new com.testsigma.security.api.APIAuthenticationFilter();89 filter.setAuthenticationManager(super.authenticationManagerBean());90 return filter;91 }92 @Bean93 public com.testsigma.security.PresignedAuthenticationFilter presignedJwtAuthenticationFilter() throws Exception {94 com.testsigma.security.PresignedAuthenticationFilter filter = new com.testsigma.security.PresignedAuthenticationFilter();95 filter.setAuthenticationManager(super.authenticationManagerBean());96 return filter;97 }98 @Bean99 public AgentJwtAuthenticationFilter agentJwtAuthorizationFilter() throws Exception {100 AgentJwtAuthenticationFilter filter = new AgentJwtAuthenticationFilter();101 filter.setAuthenticationManager(super.authenticationManagerBean());102 return filter;103 }104 @Bean105 public AuthorizationRequestRepository<OAuth2AuthorizationRequest> cookieAuthorizationRequestRepository() {106 return new com.testsigma.security.HttpCookieOAuth2AuthorizationRequestRepository();107 }108 @Bean109 public ClientRegistrationRepository clientRegistrationRepository() {110 return new InMemoryClientRegistrationRepository(this.googleClientRegistration());111 }112 private ClientRegistration googleClientRegistration() {113 String googleClientId = StringUtils.defaultIfEmpty(additionalPropertiesConfig.getGoogleClientId(),114 authenticationConfigProperties.getGoogleOAuthClientID());115 String googleClientSecret = StringUtils.defaultIfEmpty(additionalPropertiesConfig.getGoogleClientSecret(),116 authenticationConfigProperties.getGoogleOAuthClientSecret());117 return CommonOAuth2Provider.GOOGLE.getBuilder("google")118 .clientId(googleClientId)119 .clientSecret(googleClientSecret)120 .build();121 }122 @Override123 public void configure(WebSecurity web) {124 web.ignoring()125 .antMatchers(HttpMethod.GET, URLConstants.SESSION_RESOURCE_URL)126 .antMatchers((URLConstants.AGENT_CERTIFICATE_URL + URLConstants.ALL_SUB_URLS))127 .antMatchers(URLConstants.ASSETS_URL)128 .antMatchers("/servers")129 .antMatchers("/auth_config")130 .antMatchers("/onboarding/**")131 .antMatchers("/local/agents/**");132 }133 @Override134 protected void configure(HttpSecurity http) throws Exception {135 configureOauth2LoginHandlers(136 configureFilters(137 configureLoginHandlers(138 configureLogoutHandlers(139 configureExceptionHandling(140 configureUrlAuthorizations(141 configureCsrf(142 configureCors(143 basicConfig(http)144 )145 )146 )147 )148 )149 )150 )151 );152 }153 private HttpSecurity basicConfig(HttpSecurity http) throws Exception {154 return http.headers().frameOptions().disable().and()155 .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and();156 }157 private HttpSecurity configureCors(HttpSecurity http) throws Exception {158 return http.cors().and();159 }160 private HttpSecurity configureCsrf(HttpSecurity http) throws Exception {161 return http.csrf().disable();162 }163 private HttpSecurity configureUrlAuthorizations(HttpSecurity http) throws Exception {164 return http.authorizeRequests().antMatchers(URLConstants.ASSETS_URL).permitAll()165 .antMatchers(URLConstants.AGENT_CERTIFICATE_URL + URLConstants.ALL_SUB_URLS).permitAll()166 .antMatchers(HttpMethod.POST, URLConstants.LOGIN_URL).permitAll()167 .antMatchers(HttpMethod.GET, URLConstants.SESSION_RESOURCE_URL).permitAll()168 .antMatchers(URLConstants.ALL_URLS).access("isFullyAuthenticated()")169 .antMatchers(URLConstants.ALL_URLS).authenticated().and();170 }171 private HttpSecurity configureExceptionHandling(HttpSecurity http) throws Exception {172 return http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint()).and();173 }174 private HttpSecurity configureLogoutHandlers(HttpSecurity http) throws Exception {175 return http.logout()176 .logoutRequestMatcher(new AntPathRequestMatcher(URLConstants.LOGOUT_URL, HttpMethod.GET.name()))177 .logoutSuccessHandler((new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK)))178 .deleteCookies(JSESSIONID_COOKIE)179 .deleteCookies(JWTTokenService.JWT_COOKIE_NAME).invalidateHttpSession(true).and();180 }181 private HttpSecurity configureLoginHandlers(HttpSecurity http) throws Exception {182 return http.anonymous().disable().apply(ajaxLogin()).loginPage(URLConstants.LOGIN_URL)183 .successHandler(ajaxLoginSuccessHandler()).failureHandler(ajaxLoginFailureHandler()).and();184 }185 private HttpSecurity configureFilters(HttpSecurity http) throws Exception {186 return http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)187 .addFilterAfter(apiJwtAuthenticationFilter(), JWTAuthenticationFilter.class)188 .addFilterAfter(agentJwtAuthorizationFilter(), JWTAuthenticationFilter.class)189 .addFilterBefore(presignedJwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);190 }191 private HttpSecurity configureOauth2LoginHandlers(HttpSecurity http) throws Exception {192 return http.oauth2Login().redirectionEndpoint()193 .and().authorizationEndpoint()194 .authorizationRequestRepository(cookieAuthorizationRequestRepository()).and()195 .userInfoEndpoint()196 .oidcUserService(authUserService).and()197 .clientRegistrationRepository(clientRegistrationRepository())198 .successHandler(ajaxLoginSuccessHandler())199 .failureHandler(ajaxLoginFailureHandler()).and();200 }201}...

Full Screen

Full Screen

Source:JWTAuthenticationFilter.java Github

copy

Full Screen

...32import javax.servlet.http.HttpServletResponse;33import java.io.IOException;34import java.util.UUID;35@Log4j236public class JWTAuthenticationFilter extends AbstractAuthenticationProcessingFilter {37 private final RequestMatcher sessionRequestMatcher = new AntPathRequestMatcher(URLConstants.SESSION_RESOURCE_URL,38 HttpMethod.GET.toString());39 private final RequestMatcher loginRequestMatcher = new AntPathRequestMatcher(URLConstants.LOGIN_URL,40 HttpMethod.POST.toString());41 private final RequestMatcher apiRequestMatcher = new AntPathRequestMatcher(URLConstants.API_BASE_URL + "/**");42 private final RequestMatcher presignedStorageRequestMatcher = new AntPathRequestMatcher(URLConstants.PRESIGNED_BASE_URL + "/**");43 private final RequestMatcher agentApiRequestMatcher = new AntPathRequestMatcher(URLConstants.AGENT_API_BASE_URL + "/**");44 private final RequestMatcher oauthRequestMatcher = new AntPathRequestMatcher(URLConstants.OAUTH2_BASE_URL + "/**");45 private final RequestMatcher agentCertificateMatcher = new AntPathRequestMatcher(URLConstants.AGENT_CERTIFICATE_URL + "/**");46 private final RequestMatcher serverRequestMatcher = new AntPathRequestMatcher("/servers");47 private final RequestMatcher onboardingMatcher = new AntPathRequestMatcher("/onboarding/**");48 private final RequestMatcher authConfigMatcher = new AntPathRequestMatcher("/auth_config");49 private final RequestMatcher localAgentMatcher = new AntPathRequestMatcher("/local/agents/**");50 @Autowired51 AuthenticationManager authenticationManager;52 @Autowired53 JWTTokenService jwtTokenService;54 @Autowired55 AdditionalPropertiesConfig authenticationConfig;56 @Autowired57 UserPreferenceService userPreferenceService;58 @Autowired59 JWTTokenService tokenService;60 @Value("#{new Boolean('${server.servlet.session.cookie.http-only}')}")61 private Boolean httpOnly;62 @Value("#{new Boolean('${server.servlet.session.cookie.secure}')}")63 private Boolean secure;64 public JWTAuthenticationFilter(String string) {65 super(string);66 }67 @Override68 public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)69 throws AuthenticationException, IOException {70 Authentication auth = null;71 String jwtCookie = getJWTCookieValue(request);72 if (jwtCookie != null) {73 log.info("Identified authentication to be JWT Cookie...processing it for authentication");74 AuthUser authUser = jwtTokenService.parseAuthToken(jwtCookie);75 if((authUser != null)76 && ObjectUtils.defaultIfNull(tokenService.getServerUuid(), "").equals(authUser.getServerUuid())) {77 auth = new UsernamePasswordAuthenticationToken(authUser, null, authUser.getAuthorities());78 }...

Full Screen

Full Screen

JWTAuthenticationFilter

Using AI Code Generation

copy

Full Screen

1package com.testsigma.security;2import java.io.IOException;3import java.util.ArrayList;4import java.util.Date;5import java.util.List;6import javax.servlet.FilterChain;7import javax.servlet.ServletException;8import javax.servlet.http.HttpServletRequest;9import javax.servlet.http.HttpServletResponse;10import org.springframework.security.authentication.AuthenticationManager;11import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;12import org.springframework.security.core.Authentication;13import org.springframework.security.core.AuthenticationException;14import org.springframework.security.core.GrantedAuthority;15import org.springframework.security.core.authority.SimpleGrantedAuthority;16import org.springframework.security.core.userdetails.User;17import org.springframework.security.core.userdetails.UserDetails;18import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;19import com.fasterxml.jackson.databind.ObjectMapper;20import io.jsonwebtoken.Jwts;21import io.jsonwebtoken.SignatureAlgorithm;22public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {23private AuthenticationManager authenticationManager;24public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {25 this.authenticationManager = authenticationManager;26}27public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)28 throws AuthenticationException {29 try {30 com.testsigma.security.User appUser = new ObjectMapper().readValue(request.getInputStream(),31 com.testsigma.security.User.class);32 return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(appUser.getUsername(),33 appUser.getPassword(), new ArrayList<>()));34 } catch (IOException e) {35 throw new RuntimeException(e);36 }37}38protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,39 Authentication authResult) throws IOException, ServletException {40 UserDetails userDetails = (UserDetails) authResult.getPrincipal();41 List<String> roles = new ArrayList<>();42 for (GrantedAuthority authority : userDetails.getAuthorities()) {43 roles.add(authority.getAuthority());44 }45 String jwt = Jwts.builder().setSubject(userDetails.getUsername())46 .setExpiration(new Date(System.currentTimeMillis() + SecurityConstants.EXPIRATION_TIME))47 .claim("roles", roles).signWith(SignatureAlgorithm.HS256, SecurityConstants.SECRET).compact();48 response.addHeader(SecurityConstants.HEADER_STRING, SecurityConstants.TOKEN_PREFIX + jwt);49}50}51package com.testsigma.security;52import java.io.IOException;53import java.util.ArrayList;54import java.util.Collection;55import java.util.Collections;56import java.util.Date;57import java.util.List;58import javax.servlet.FilterChain;59import javax.servlet.ServletException;60import javax.servlet.http.HttpServletRequest

Full Screen

Full Screen

JWTAuthenticationFilter

Using AI Code Generation

copy

Full Screen

1package com.testsigma.security;2import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;3import org.springframework.security.core.Authentication;4import org.springframework.security.core.context.SecurityContextHolder;5import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;6import org.springframework.web.filter.OncePerRequestFilter;7import io.jsonwebtoken.ExpiredJwtException;8import javax.servlet.FilterChain;9import javax.servlet.ServletException;10import javax.servlet.http.HttpServletRequest;11import javax.servlet.http.HttpServletResponse;12import java.io.IOException;13public class JWTAuthenticationFilter extends OncePerRequestFilter {14 protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {15 String header = request.getHeader("Authorization");16 String username = null;17 String authToken = null;18 if (header != null && header.startsWith("Bearer ")) {19 authToken = header.replace("Bearer ", "");20 try {21 username = JWTTokenUtil.getUsernameFromToken(authToken);22 } catch (IllegalArgumentException e) {23 System.out.println("an error occured during getting username from token");24 } catch (ExpiredJwtException e) {25 System.out.println("the token is expired and not valid anymore");26 }27 } else {28 System.out.println("couldn't find bearer string, will ignore the header");29 }30 if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {31 Authentication authentication = JWTTokenUtil.getAuthenticationToken(authToken);32 authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));33 System.out.println("authenticated user " + username + ", setting security context");34 SecurityContextHolder.getContext().setAuthentication(authentication);35 }36 filterChain.doFilter(request, response);37 }38}39package com.testsigma.security;40import org.springframework.security.core.AuthenticationException;41import org.springframework.security.web.AuthenticationEntryPoint;42import org.springframework.stereotype.Component;43import javax.servlet.ServletException;44import javax.servlet.http.HttpServletRequest;45import javax.servlet.http.HttpServletResponse;46import java.io.IOException;47public class JWTAuthenticationEntryPoint implements AuthenticationEntryPoint {48 public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {49 response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");50 }51}52package com.testsigma.security;53import io.jsonwebtoken.Claims;54import

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful