繁体   English   中英

Spring Boot 403禁止在Tomcat 9中使用POST请求

[英]Spring Boot 403 forbidden with POST request in Tomcat 9

我是Spring Boot的新手,正在创建一个Web应用程序。 我绕过没有JWT令牌认证的“ / auth / login” URL。

我创建了一个控制器,用于处理登录请求并给出响应。

当我使用URL http://localhost:9505/auth/login和body参数调用本地URL的Web服务时

{
    "username":"abcd@g.l",
    "password" : "newPassword"
}

它工作正常并且不检查令牌,但是当我导出它并创建WAR文件并部署在服务器上时,它给了我403 Forbidden错误。

以下是在tomcat 9服务器上部署后用于调用API的URL

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

您能指导我什么问题吗?

下面是我的安全配置方法。

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

下面是我的过滤器类

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

    }

下面是我的控制器

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

尝试在您的课程中添加以下提及的注释。

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

问题出在我的tomcat服务器中的CORS。

我已经在下面的代码中发表了评论,并且可以正常工作。

<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>

谢谢

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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