0

I am new to the spring boot and I am creating a web application. I am bypassing "/auth/login" URL without JWT token authentication.

I have created a controller which handle the login request and give the response.

When I call my web service with URL in my local using URL http://localhost:9505/auth/login with body param

{ "username":"[email protected]", "password" : "newPassword" } 

It is working fine and does not check for the token but When I export it and create WAR file and deployed on the server then it is giving me 403 Forbidden error.

Below is URL which I use to call API after deploying on tomcat 9 server

http://localhost:9505/myapplicationame/auth/login 

Can you please guide me what will be the problem?

Below is my security config method.

@Override protected void configure(HttpSecurity http) throws Exception { logger.info("SecurityConfig => configure : Configure in SecurityConfig"); logger.info("http Request Path : "); logger.info("servletContext.getContextPath()) : " + servletContext.getContextPath()); http .csrf() .disable() .exceptionHandling() .authenticationEntryPoint(unauthorizedHandler) .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .antMatchers("/", "/favicon.ico", "/**/*.png", "/**/*.gif", "/**/*.svg", "/**/*.jpg", "/**/*.html", "/**/*.css", "/**/*.js") .permitAll() .antMatchers("/auth/**") .permitAll() .antMatchers("/auth/login") .permitAll() .antMatchers("/permissions") .permitAll() .anyRequest() .authenticated(); // Add our custom JWT security filter http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); } 

Below is my filter class

@Configuration @CrossOrigin @EnableWebSecurity @EnableMBeanExport(registration=RegistrationPolicy.IGNORE_EXISTING) @EnableGlobalMethodSecurity(securedEnabled = true, jsr250Enabled = true, prePostEnabled = true) @Order(SecurityProperties.IGNORED_ORDER) public class JwtAuthenticationFilter extends OncePerRequestFilter { @Autowired JwtTokenProvider tokenProvider; @Autowired CustomUserDetailsService customUserDetailsService; @Autowired AdminPermissionRepository adminPermissionRepository; @Autowired PermissionMasterRepository permissionMasterRepository; @Autowired private ServletContext servletContext; @Override protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws IOException, ServletException { if (StringUtils.hasText(jwt) && isValidToken) { // Check user email and password UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( adminDetails, null, adminDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest)); SecurityContextHolder.getContext().setAuthentication(authentication); logger.info("Before finish doFilterInternal"); filterChain.doFilter(httpServletRequest, httpServletResponse); } filterChain.doFilter(httpServletRequest, httpServletResponse); } /** * To get JWT token from the request * * @param httpServletRequest * @return String */ private String getJwtFromRequest(HttpServletRequest httpServletRequest) { logger.info("JwtAuthenticationFilter => getJwtFromRequest"); String bearerToken = httpServletRequest.getHeader("Authorization"); if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) { logger.info("Have token"); return bearerToken.substring(7, bearerToken.length()); } logger.info("Does not have token"); return null; } } 

Below is my controller

@RestController @Transactional(rollbackFor=Exception.class) public class AuthController { @PostMapping("/auth/login") ResponseEntity login(@Valid @RequestBody LoginRequest request) throws DisabledException, InternalAuthenticationServiceException, BadCredentialsException { // My logic return ResponseEntity.ok(); } } 
2
  • One of the point that throws this exception is filterChain.doFilter(). I think that you missed some information in jwt payload when you made request, double check to see if they are there, username, sub, expiration time, scope. Commented Sep 11, 2018 at 8:55
  • I have handle exception globally so I don't think it is generating an exception. Commented Sep 11, 2018 at 9:36

2 Answers 2

3

The problem is with the CORS in my tomcat server.

I have commented below code and it works.

<filter> <filter-name>CorsFilter</filter-name> <filter-class>org.apache.catalina.filters.CorsFilter</filter-class> <init-param> <param-name>cors.allowed.origins</param-name> <param-value>http://localhost:9505, http://localhost, www.mydomain.io, http://mydomain.io, mydomain.io</param-value> </init-param> </filter> <filter-mapping> <filter-name>CorsFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> 

Thanks

Sign up to request clarification or add additional context in comments.

1 Comment

I also had to add corsConfiguration.setAllowedOrigins("*"); for FF. Even when accessing from same domain, requests for js.maps returned 403.
0

Try adding below mention annotations to your class.

@Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private ServletContext servletContext; @Override protected void configure(HttpSecurity http) throws Exception { logger.info("SecurityConfig => configure : Configure in SecurityConfig"); logger.info("http Request Path : "); logger.info("servletContext.getContextPath()) : " + servletContext.getContextPath()); http .csrf() .disable() .exceptionHandling() .authenticationEntryPoint(unauthorizedHandler) .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .antMatchers("/", "/favicon.ico", "/**/*.png", "/**/*.gif", "/**/*.svg", "/**/*.jpg", "/**/*.html", "/**/*.css", "/**/*.js") .permitAll() .antMatchers("/auth/**") .permitAll() .antMatchers("/auth/login") .permitAll() .antMatchers("/permissions") .permitAll() .anyRequest() .authenticated(); // Add our custom JWT security filter http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); } } 

3 Comments

Yes, I also tried this way but still, it is not working. I have added serverlet context path in my question. Thanks for reply
Please try adding annotations to your security class.
I have tried with annotations also but still, I am getting the same error. I have updated code also

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.