Spring Security 401在不安全的端点上未经授权

Sam*_*eos 6 java spring spring-security spring-boot postman

我正在尝试在Spring Boot应用程序上配置Spring Security,如下所示:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private RestAuthenticationEntryPoint unauthorizedHandler;

@Bean
public JwtAuthenticationFilter authenticationTokenFilterBean() throws Exception {
    JwtAuthenticationFilter authenticationTokenFilter = new JwtAuthenticationFilter();
    authenticationTokenFilter.setAuthenticationManager(authenticationManagerBean());
    return authenticationTokenFilter;
}

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {

    //@formatter:off
     httpSecurity
      .csrf()
        .disable()
      .exceptionHandling()
        .authenticationEntryPoint(this.unauthorizedHandler)
        .and()
      .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
      .authorizeRequests()
        .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
        .antMatchers("/login", "/singup", "/subscribers").permitAll()
        .anyRequest().authenticated();

        // Custom JWT based security filter 
    httpSecurity            
        .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);   

    //@formatter:on

}
}
Run Code Online (Sandbox Code Playgroud)

我的未经授权的处理程序是:

public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

private static final Logger LOGGER = LoggerFactory.getLogger(RestAuthenticationEntryPoint.class);

@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}

}
Run Code Online (Sandbox Code Playgroud)

最后,用于/ subscribers的REST控制器是:

@RestController
public class SubscriberRestController {

@Autowired
ISubscribersService subscribersService;

@RequestMapping(value = RequestMappingConstants.SUBSCRIBERS, method = RequestMethod.GET)
@ResponseBody
public Number subscriberCount() {

    return subscribersService.subscribersCount();
}

@RequestMapping(value = RequestMappingConstants.SUBSCRIBERS, method = RequestMethod.POST)
public String subscriberPost(@RequestBody SubscriberDocument subscriberDocument) {

    return subscribersService.subscribersInsert(subscriberDocument);
}

@RequestMapping(value = "/test", method = RequestMethod.GET)
public String test() {

    return "This is a test";
}

}
Run Code Online (Sandbox Code Playgroud)

我使用邮递员测试端点,当我对“ localhost:8080 / subscribers”执行POST时,得到:

邮递员结果

我想打开没有任何安全控制或凭据检查的端点(/订户),用于注册和登录的端点以及用于已认证用户的安全端点。

谢谢!:)

Sam*_*eos 6

Spring Boot 没有应用配置,因为找不到它。在Application.java配置包未包含在@ComponentScan注释中。