0

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

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

http://localhost:9505/auth/login当我在本地使用带有正文参数的 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();
        }
    }
4

2 回答 2

3

问题在于我的 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>

谢谢

于 2018-09-14T21:20:23.010 回答
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);
    }
}
于 2018-09-11T08:44:23.720 回答