Tomcat 9中禁止通过POST请求进行Spring Boot 403

时间:2018-09-11 08:18:08

标签: java spring spring-boot spring-security spring-security-rest

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

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

当我使用URL在本地使用URL调用Web服务时 http://localhost:9505/auth/login具有身体参数

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

1 个答案:

答案 0 :(得分:0)

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

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