简体   繁体   中英

Spring Boot 403 forbidden with POST request in Tomcat 9

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":"abcd@g.l",
    "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();
        }
    }

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);
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM