当前位置: 首页 > 知识库问答 >
问题:

Spring+SpringSecurity-AuthenticationEntryPoint未

许沛
2023-03-14

在WAR的情况下,它试图将请求转发到/error页面,并寻找它的处理程序方法(请参见底部的日志)。

最后我得到以下回应:

{
    "timestamp": 1576064959206,
    "status": 500,
    "error": "Internal Server Error",
    "message": "Expired or invalid JWT token",
    "path": "/paymentapi-2.0.2.RELEASE/config/credit"
}

我该换什么才能得到401?

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

@Autowired
private JwtTokenProvider jwtTokenProvider;

@Autowired
private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
            .csrf().disable()
            .httpBasic().disable()
            .cors().disable()
            .headers().frameOptions().disable()
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            .antMatchers("/ping").permitAll()
            .antMatchers("/mock/**").permitAll()
            .antMatchers("/customers/**").permitAll()
            .antMatchers("/buyers/**").permitAll()
            .antMatchers("/user/**").hasIpAddress("127.0.0.1")
            .antMatchers("/helper/**").permitAll()
            .antMatchers("/v2/orders/**").permitAll()
            .antMatchers("/transactions/**").permitAll()
            .antMatchers("/paymentCollection/**").permitAll()
            .antMatchers("/paymentRequest").permitAll()
            .antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources", "/configuration/security",
                    "/swagger-ui.html", "/webjars/**", "/swagger-resources/configuration/ui", "/swagger-ui.html",
                    "/swagger-resources/configuration/security").permitAll()
            .anyRequest().authenticated()
            .and()
            .apply(new JwtConfigurer(jwtTokenProvider))
            .and().exceptionHandling().authenticationEntryPoint(paymentEngineAuthenticationEntryPoint);

}
}
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void commence(final HttpServletRequest request, final HttpServletResponse response,
            final AuthenticationException authException) throws IOException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        //response.addHeader("WWW-Authenticate", "Bearer");

        response.setContentType("application/json;charset=UTF-8");
        ResponseData responseData = new ResponseData();
        responseData.setMessage(authException.getMessage());
        responseData.setStatusCode(401);
        responseData.setSuccess(false);
        response.getWriter().write(objectMapper.writeValueAsString(responseData));
        response.flushBuffer();
    }

}

 2019-12-11 16:20:16,178 [DEBUG] [http-nio-8082-exec-7] [o.s.security.web.FilterChainProxy ] /config/credit at position 5 of 11 in additional filter chain; firing Filter: 'JwtTokenAuthenticationFilter' 
        2019-12-11 16:20:16,179 [DEBUG] [http-nio-8082-exec-7] [o.s.s.w.header.writers.HstsHeaderWriter ] Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@229d8736 
        2019-12-11 16:20:16,179 [DEBUG] [http-nio-8082-exec-7] [s.s.w.c.SecurityContextPersistenceFilter] SecurityContextHolder now cleared, as request processing completed 
2019-12-11 16:20:16,179 [DEBUG] [http-nio-8082-exec-7] [o.s.b.w.s.f.OrderedRequestContextFilter ] Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade@14816abd 
        2019-12-11 16:20:16,180 [ERROR] [http-nio-8082-exec-7] [o.s.b.w.servlet.support.ErrorPageFilter ] Forwarding to error page from request [/config/credit] due to exception [Expired or invalid JWT token] com.ril.vms.deadpool.exceptions.InvalidJwtAuthenticationException: Expired or invalid JWT token at com.ril.vms.deadpool.securitycore.JwtTokenProvider.validateToken(JwtTokenProvider.java:74) at com.ril.vms.deadpool.securitycore.JwtTokenAuthenticationFilter.doFilterInternal(JwtTokenAuthenticationFilter.java:31) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        ...
        2019-12-11 17:19:15,628 [DEBUG] [http-nio-8082-exec-7] [o.s.web.servlet.DispatcherServlet       ] DispatcherServlet with name 'dispatcherServlet' processing GET request for [/paymentapi-2.0.2.RELEASE/error]
        2019-12-11 17:19:17,556 [DEBUG] [http-nio-8082-exec-7] [s.b.a.e.w.s.WebMvcEndpointHandlerMapping] Looking up handler method for path /error
        2019-12-11 17:19:17,557 [DEBUG] [http-nio-8082-exec-7] [s.b.a.e.w.s.WebMvcEndpointHandlerMapping] Did not find handler method for [/error]
        2019-12-11 17:19:17,557 [DEBUG] [http-nio-8082-exec-7] [a.e.w.s.ControllerEndpointHandlerMapping] Looking up handler method for path /error
        2019-12-11 17:19:17,557 [DEBUG] [http-nio-8082-exec-7] [a.e.w.s.ControllerEndpointHandlerMapping] Did not find handler method for [/error]
        2019-12-11 17:19:17,557 [DEBUG] [http-nio-8082-exec-7] [s.w.s.m.m.a.RequestMappingHandlerMapping] Looking up handler method for path /error
        2019-12-11 17:19:17,558 [DEBUG] [http-nio-8082-exec-7] [s.w.s.m.m.a.RequestMappingHandlerMapping] Returning handler method [public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)]
        2019-12-11 17:19:17,558 [DEBUG] [http-nio-8082-exec-7] [o.s.b.f.s.DefaultListableBeanFactory    ] Returning cached instance of singleton bean 'basicErrorController'

共有1个答案

葛炜
2023-03-14

我是这样解决这个问题的:

>

  • 在SpringBootServletInitializer中,我禁用了ErrorPageFilter

    @SpringBootApplication(exclude = {SecurityAutoConfiguration.class})
    public class MyApplication extends SpringBootServletInitializer {
    
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
    
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(MyApplication.class);
    }
    
    public PaymentapiApplication() {
        super();
        setRegisterErrorPageFilter(false);
    }} 
    

    我编写了一个自定义过滤器来捕捉特定的RunTimeException

    @Component
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public class ExceptionHandlerFilter extends OncePerRequestFilter {
    
    @Autowired
    private ObjectMapper objectMapper;
    
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse 
    response, FilterChain filterChain)
            throws ServletException, IOException {
    
        try {
            filterChain.doFilter(request, response);
        } catch (RuntimeException e) {
            // custom error response class used across my project
            if(e instanceof InvalidJwtAuthenticationException) {
                ResponseData responseData = new ResponseData(false, e.getMessage(), 401, 
    null);
                response.setStatus(HttpStatus.UNAUTHORIZED.value());
                response.getWriter().write(objectMapper.writeValueAsString(responseData));
            }
        }
    
    }}
    

  •  类似资料:
    • 我现在的问题是,这样做正确吗?AuthenticationEntryPoint和AuthenticationFailureHandler之间有什么区别?

    • 1.导入jar包 web.xml spring-security.xml

    • Spring Web Security中AuthenticationEntryPoint的目的是什么?文档没有提供太多细节。什么时候应该使用这个,它和Spring安全过滤链有什么关系吗。

    • 主要内容:1.入门,2.设置用户名和密码1.入门 1.启动一个SpringBoot项目 2.导入SpringSecurity相关依赖 3.编写Controller TestController.java 用户是user 密码是刚刚的 2.设置用户名和密码 1.在配置文件中设置 2.在配置类中设置 3.自定义实现类 2.1 配置文件中设置 2.2 在配置类中设置 设置用户名为zZZ,密码为root 2.3 自定义实现类 配置类: 业务类:

    • 嗨,Spring Security专家。 我的要求。 我有两套UI。其中一组是登录和注销,需要使用基本身份验证(使用用户名密码凭据)由spring security进行保护。我使用了实现,并实现了它。 第二个和其余的UI需要通过在HTTP Header中传递令牌来支持。我使用实现并且可以实现它。 现在我想做单Spring安全。xml实现上述两种功能。最终,我将一组UI页面组合在一起,在这些页面中,

    • 本文向大家介绍SpringSecurity 测试实战,包括了SpringSecurity 测试实战的使用技巧和注意事项,需要的朋友参考一下 引言 试题管理系统的安全模块使用Spring Security,代码从原华软仓库移植,在移植的过程中,发现原测试编写的不好,遂在新系统中对安全模块测试进行了重构。 Spring 测试 添加@SpringBootTest注解,意为这是一个基于SpringBoot