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

Best Testsigma code snippet using com.testsigma.security.JWTAuthenticationFilter.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 java.util.stream.Collectors;7import javax.servlet.FilterChain;8import javax.servlet.ServletException;9import javax.servlet.http.HttpServletRequest;10import javax.servlet.http.HttpServletResponse;11import org.springframework.security.authentication.AuthenticationManager;12import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;13import org.springframework.security.core.Authentication;14import org.springframework.security.core.AuthenticationException;15import org.springframework.security.core.GrantedAuthority;16import org.springframework.security.core.userdetails.User;17import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;18import com.fasterxml.jackson.databind.ObjectMapper;19import com.testsigma.model.ApplicationUser;20import io.jsonwebtoken.Jwts;21import io.jsonwebtoken.SignatureAlgorithm;22public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {23 private AuthenticationManager authenticationManager;24 public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {25 this.authenticationManager = authenticationManager;26 }27 public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)28 throws AuthenticationException {29 try {30 ApplicationUser creds = new ObjectMapper().readValue(request.getInputStream(), ApplicationUser.class);31 return authenticationManager.authenticate(32 new UsernamePasswordAuthenticationToken(creds.getUsername(), creds.getPassword(), new ArrayList<>()));33 } catch (IOException e) {34 throw new RuntimeException(e);35 }36 }37 protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,38 Authentication auth) throws IOException, ServletException {39 String token = Jwts.builder().setSubject(((User) auth.getPrincipal()).getUsername())40 .setExpiration(new Date(System.currentTimeMillis() + SecurityConstants.EXPIRATION_TIME))41 .signWith(SignatureAlgorithm.HS512, SecurityConstants.SECRET.getBytes())42 .claim("roles", auth.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()))43 .compact();44 response.addHeader(SecurityConstants.HEADER_STRING, SecurityConstants.TOKEN_PREFIX + token);45 }46}47package com.testsigma.security;48import java.io.IOException;49import java.util.ArrayList;50import java.util.Collection;51import java.util.Collections;52import java.util.Date;53import java.util.List;54import java.util.stream.Collectors;55import javax.servlet.FilterChain;56import javax.servlet.ServletException;57import javax.servlet.http.HttpServletRequest;58import javax.servlet.http.HttpServletResponse;59import org.springframework.security.authentication.UsernamePassword

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.HashMap;6import java.util.List;7import java.util.Map;8import java.util.stream.Collectors;9import javax.servlet.FilterChain;10import javax.servlet.ServletException;11import javax.servlet.http.HttpServletRequest;12import javax.servlet.http.HttpServletResponse;13import org.springframework.security.authentication.AuthenticationManager;14import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;15import org.springframework.security.core.GrantedAuthority;16import org.springframework.security.core.authority.SimpleGrantedAuthority;17import org.springframework.security.core.context.SecurityContextHolder;18import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;19import io.jsonwebtoken.Claims;20import io.jsonwebtoken.Jwts;21import io.jsonwebtoken.SignatureAlgorithm;22public class JWTAuthorizationFilter extends BasicAuthenticationFilter {23 public JWTAuthorizationFilter(AuthenticationManager authManager) {24 super(authManager);25 }26 protected void doFilterInternal(HttpServletRequest req,27 FilterChain chain) throws IOException, ServletException {28 String header = req.getHeader(JWTProperties.HEADER_STRING);29 if (header == null || !header.startsWith(JWTProperties.TOKEN_PREFIX)) {30 chain.doFilter(req, res);31 return;32 }33 UsernamePasswordAuthenticationToken authentication = getAuthentication(req);34 SecurityContextHolder.getContext().setAuthentication(authentication);35 chain.doFilter(req, res);36 }37 private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {38 String token = request.getHeader(JWTProperties.HEADER_STRING);39 if (token != null) {40 Claims claims = Jwts.parser()41 .setSigningKey(JWTProperties.SECRET.getBytes())42 .parseClaimsJws(token.replace(JWTProperties.TOKEN_PREFIX, ""))43 .getBody();44 String user = claims.getSubject();45 List<Map<String, String>> rolesMap = (List<Map<String, String>>) claims.get("roles");46 List<GrantedAuthority> authorities = rolesMap.stream()47 .map(role -> new SimpleGrantedAuthority(role.get("authority")))48 .collect(Collectors.toList());49 if (user != null) {50 return new UsernamePasswordAuthenticationToken(user, null, authorities);51 }52 return null;53 }54 return null;55 }56}57package com.testsigma.security;58import java.io.IOException;59import java.util.ArrayList;60import java

Full Screen

Full Screen

JWTAuthenticationFilter

Using AI Code Generation

copy

Full Screen

1import com.testsigma.security.JWTAuthenticationFilter;2import com.testsigma.security.JWTAuthorizationFilter;3import com.testsigma.security.JWTLoginFilter;4import com.testsigma.security.SecurityConstants;5import org.springframework.beans.factory.annotation.Autowired;6import org.springframework.context.annotation.Bean;7import org.springframework.context.annotation.Configuration;8import org.springframework.http.HttpMethod;9import org.springframework.security.authentication.AuthenticationManager;10import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;11import org.springframework.security.config.annotation.web.builders.HttpSecurity;12import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;13import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;14import org.springframework.security.config.http.SessionCreationPolicy;15import org.springframework.security.core.userdetails.UserDetailsService;16import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;17import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;18public class WebSecurityConfig extends WebSecurityConfigurerAdapter {19 private UserDetailsService userDetailsService;20 public BCryptPasswordEncoder bCryptPasswordEncoder() {21 return new BCryptPasswordEncoder();22 }23 protected void configure(HttpSecurity http) throws Exception {24 http.csrf().disable().authorizeRequests()25 .antMatchers(HttpMethod.POST, SecurityConstants.SIGN_UP_URL).permitAll()26 .anyRequest().authenticated()27 .and()28 .addFilterBefore(new JWTLoginFilter("iapimlogin", authentipationManager()),29 .addFilterBefore(new JWTAuthenticationFilter(),30 UsernamePasswordAuthenticationFilter.class);31 }32 public void configure(AuthenticationManagerBuilder auth) throws Exception {33 auth.inMemoryAuthentication()34 .withUser("admin")35 .password("password")36 .roles("ADMIN");37 }38 public AuthenticationManager authenticationManagerBean() throws Exception {39 return super.authenticationManagerBean();40 }41}42import com.testsigma.security.SecurityConstants;43import org.springframework.security.authentication.AuthenticationManager;44import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;45import org.springframework.security.core.Authentication;46import org.springframework.security.core.AuthenticationException;47import org.springframework.security.core.authority.SimpleGrantedAuthority;48import org.springframework.security.core.userdetails.User;49import org

Full Screen

Full Screen

JWTAuthenticationFilter

Using AI Code Generation

copy

Full Screen

1import com.testsigma.security.JWTAuthorizationFilter;2import com.testsigma.security.JWTLoginFilter;3import com.testsigma.security.SecurityConstants;4import org.springframework.beans.factory.annotation.Autowired;5import org.springframework.context.annotation.Bean;6import org.springframework.context.annotation.Configuration;7import org.springframework.http.HttpMethod;8import org.springframework.security.authentication.AuthenticationManager;9import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;10import org.springframework.security.config.annotation.web.builders.HttpSecurity;11import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;12import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;13import org.springframework.security.config.http.SessionCreationPolicy;14import org.springframework.security.core.userdetails.UserDetailsService;15import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;16import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;17public class WebSecurityConfig extends WebSecurityConfigurerAdapter {18 private UserDetailsService userDetailsService;19 public BCryptPasswordEncoder bCryptPasswordEncoder() {20 return new BCryptPasswordEncoder();21 }22 protected void configure(HttpSecurity http) throws Exception {23 http.csrf().disable().authorizeRequests()24 .antMatchers(HttpMethod.POST, SecurityConstants.SIGN_UP_URL).permitAll()25 .anyRequest().authenticated()26 .and()27 .addFilterBefore(new JWTLoginFilter("/api/login", authenticationManager()),28 .addFilterBefore(new JWTAuthenticationFilter(),29 UsernamePasswordAuthenticationFilter.class);30 }31 public void configure(AuthenticationManagerBuilder auth) throws Exception {32 auth.inMemoryAuthentication()33 .withUser("admin")34 .password("password")35 .roles("ADMIN");36 }37 public AuthenticationManager authenticationManagerBean() throws Exception {38 return super.authenticationManagerBean();39 }40}41import com.testsigma.security.SecurityConstants;42import org.springframework.security.authentication.AuthenticationManager;43import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;44import org.springframework.security.core.Authentication;45import org.springframework.security.core.AuthenticationException;46import org.springframework.security.core.authority.SimpleGrantedAuthority;47import org.springframework.security.core.userdetails.User;48import org

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