Spring Security возвращает 401, При отправке даты в качестве входных данных для остальных контроллера - PullRequest
0 голосов
/ 21 апреля 2020
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsInfoService userDetailsService;

    @Autowired
    private CustomLoginAuthenticationProvider authenticationProvider;


    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider);
        auth.userDetailsService(userDetailsService);

    }

    @Override
    public void configure(WebSecurity web) throws Exception {

        web.ignoring()
        .antMatchers("/api/user/authenticate/**")
        .antMatchers("/api/user/**")
        .antMatchers("/api/master/**")
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
    }

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

   /* @EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)
    private static class GlobalSecurityConfiguration extends GlobalMethodSecurityConfiguration {
        @Override
        protected MethodSecurityExpressionHandler createExpressionHandler() {
            return new OAuth2MethodSecurityExpressionHandler();
        }

    }*/

}

Это моя весенняя конфигурация безопасности в приложении. Он прекрасно работает большую часть сценария ios, но не может отследить одну проблему.

При каждом вызове веб-службы с форматом даты пружина безопасности возвращает ошибку 401.

http://localhost:9190/nazouki/api/master/create

с вводом

{"orgId":"11","birthDate":"2020-04-20T20:00:00.000Z"}

без даты он работает нормально.

Код контроллера

@RequestMapping(value = "master/create", method = RequestMethod.POST)
    public @ResponseBody ResultDecorator createMaster(@RequestBody  TuMasterDto tuMasterDto){       handler.resolveResult(masterService.createMaster(tuMasterDto), OperationEnum.SAVE);
    }

Исключение было сгенерировано из CustomAuthenticationEntryPoint в весенней безопасности.

@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private final Logger log = LoggerFactory.getLogger(CustomAuthenticationEntryPoint.class);

    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException ae) throws IOException, ServletException {

        log.info("Pre-authenticated entry point called. Rejecting access");
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access Denied");

    }
}

1 Ответ

0 голосов
/ 21 апреля 2020

Мы не можем сказать наверняка, если только мы не взглянем на методы handler.resolveResult() и masterService.createMaster().

Мое первоначальное предположение состояло бы в том, что у вас есть конфигурация GlobalMethodSecurity для одного или обоих этих методов (или путь кода, который используется ими), и, поскольку вы ignore безопасность для пути web.ignoring().antMatchers("/api/master/**"), SecurityContext не создано, и поэтому вы получите этот ответ.

Относительно того, почему при добавлении даты он ведет себя по-другому, я сам не уверен. Может быть, у вас есть 2 реализации? как то так

public void handleRequest(Dto dto) {
   if(dto.getDate() != null) {
      doSomethingWithTheDate(dto.getDate());
   }
   // handle normally
}

@PreAuthorize("hasRole('ROLE_USER')")
public void doSomethingWithTheDate(Date date) {
   ...
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...