InsufficientAuthenticationException:访问此资源需要完全身份验证

时间:2019-12-05 12:39:01

标签: java spring security oauth-2.0 jwt

所以我通过Spring Boot安全性设置了一个相对简单的JWT身份验证。这包括3个过滤器(Jwt,Cors,JwtExceptionHandler)和一个注册到HttpSecurity的Exceptionhandler。 由于调试原因,我将doFilterInternal的{​​{1}}方法设为空。仅此一点就没有问题。但是,如果同一过滤器中的JwtRequestFilter方法返回shouldNotFilter(这意味着true将被跳过),我将收到指定的异常:

doFilterInternal

这是我的org.springframework.security.authentication.InsufficientAuthenticationException: Full authentication is required to access this resource at org.springframework.security.web.access.ExceptionTranslationFilter.handleSpringSecurityException(ExceptionTranslationFilter.java:189) at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:140) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:158) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:103) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at at.techsoft.cocos.security.ExceptionHandlerFilter.doFilterInternal(ExceptionHandlerFilter.java:20) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) 班:

WebSecurityConfig

这是有问题的JwtRequestFilter:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private static final Logger log = LoggerFactory.getLogger(WebSecurityConfig.class);

@Autowired
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

@Autowired
private UserDetailsService jwtUserDetailsService;

@Autowired
private ExceptionHandlerFilter exceptionHandlerFilter;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(jwtUserDetailsService).passwordEncoder(passwordEncoder());
}

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}



@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.cors().and().csrf().disable();
    httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    httpSecurity.exceptionHandling()
            .authenticationEntryPoint(jwtAuthenticationEntryPoint);

    httpSecurity.headers().frameOptions().disable();

    httpSecurity.authorizeRequests()
            .antMatchers(Path.ROOT + "/authentication/**", "/*","/share/**", "/css/**", "/img/**", "/js/**", "/console/**").permitAll()
            // Disallow everything else..
            .antMatchers(HttpMethod.OPTIONS).permitAll()
            .anyRequest().authenticated();

    httpSecurity.addFilterBefore(new CorsFilterConfig(), ChannelProcessingFilter.class);

    httpSecurity.addFilterBefore(new JwtRequestFilter(new StandardJwtValidator(tokenUtil, userRepository, jwtUserDetailsService)), UsernamePasswordAuthenticationFilter.class);

    httpSecurity
            .addFilterBefore(exceptionHandlerFilter, JwtRequestFilter.class);
}



@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring()
            .antMatchers(Path.ROOT + "/authentication/",  "/*", "/css/**", "/img/**", "/js/**", "/console/**")
            .antMatchers(HttpMethod.OPTIONS, "/**");

}

在搜索异常时,几乎所有答案都包括oauth2身份验证,但我不使用oauth2。

我应该补充一点,这种特殊情况永远都不会发生,但是我觉得有一些潜在的问题正在系统的其他部分中产生错误。

编辑: 根据请求,我将添加application.properties:

public class JwtRequestFilter extends OncePerRequestFilter {

private Logger log = LoggerFactory.getLogger(JwtRequestFilter.class);

final
IJwtValidator validator;

public JwtRequestFilter(IJwtValidator validator) {
    this.validator = validator;
}

@Override
public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {            

  //SecurityContextHolder.getContext().setAuthentication(validator.getAuthenticatioNToken(request));


}

@Override
protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
    return true;
}
}

请求标头:

jwt.secret=javainuse
logging.level.at=DEBUG
logging.level.org.springframework.web=DEBUG
spring.jpa.hibernate.ddl-auto= create-drop
spring.jpa.open-in-view=true #i know this shouldn't be used

#database location
#left out for post
# H2
spring.h2.console.enabled=true
spring.h2.console.path=/h2/
spring.datasource.url=#left out again

2 个答案:

答案 0 :(得分:0)

您可以参考以下提到的文章,可能会有所帮助

Spring Boot: Full authentication is required to access this resource

secure-your-spring-restful-apis-with-jwt-a-real-world-example

在spring-boot项目中,如果您还有application.properties文件或application.yml文件也共享它们。 是服务器到服务器认证还是客户端到服务器? 请也分享请求标头的详细信息

答案 1 :(得分:0)

对于在我之后寻找解决方案的任何人: 这是doFilterInternal方法中的一行代码。最后,我添加了

chain.doFilter(request, response);

这为我解决了这个问题。