2017-01-07 2 views
0

Почему логин не запрашивается со следующей конфигурацией? Когда я пытаюсь получить доступ к /public/user, я получаю ошибку 403 (доступ запрещен). Однако, если я раскомментирую эти прокомментированные строки по адресу WebServiceSecurityConfiguration.configure, я, по желанию, перенаправлен на страницу входа. Почему эти строки необходимы для правильной настройки из-за-входа, поскольку antMatcher в первую очередь соответствует другому пути. Я предполагаю, что есть какой-то конфликт, который неправильно сконфигурировал AuthenticationEntryPoint, но я действительно не знаю, как это происходит. То, что я пытаюсь достичь, - это настроить две цепи безопасности: одну для логина, чтобы получить токен JWT, а другой - для веб-служб для аутентификации против токена. Все отлично работает с этими линиями без ранения, но я случайно заметил, что логин перестает работать без них, и я очень смущен, почему это так.Конфигурация конфигурации java конфигурации безопасности Spring

@Configuration 
@Profile("javasecurity") 
@Order(11) 
@EnableWebSecurity 
@EnableGlobalMethodSecurity(prePostEnabled = true) 
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 

    @Autowired 
    private TokenHandler tokenHandler; 

    @Override 
    protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
     auth.inMemoryAuthentication() 
      .withUser("user").password("password").authorities(new SimpleGrantedAuthority("ROLE_USER")).and() 
      .withUser("admin").password("password").authorities(
        new SimpleGrantedAuthority("ROLE_USER"), 
        new SimpleGrantedAuthority("ROLE_ADMIN")).and() 
      .withUser("guest").password("guest").authorities(new SimpleGrantedAuthority("ROLE_GUEST")); 
    } 

    @Override 
    @Bean 
    public UserDetailsService userDetailsServiceBean() throws Exception { 
     return super.userDetailsServiceBean(); 
    } 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
      .authorizeRequests() 
      .antMatchers("/public/**") 
       .permitAll() 
      .and() 
       .formLogin() 
       .successHandler(authenticationSuccessHandler()) 
       .and() 
       .logout(); 
    } 

    @Bean 
    public AuthenticationSuccessHandler authenticationSuccessHandler() { 
     return new AuthenticationSuccessHandler() { 

      public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, 
        Authentication authentication) throws IOException, ServletException { 
       tokenHandler.setToken(response, authentication.getName()); 
       response.getWriter().println("User authenticated and cookie sent"); 
       response.flushBuffer(); 
      } 
     }; 
    } 

    @Configuration 
    @Profile("javasecurity") 
    @Order(10) 
    public static class WebServiceSecurityConfiguration extends WebSecurityConfigurerAdapter { 

     @Autowired 
     private TestAuthenticationFilter testAuthenticationFilter; 

     @Override 
     protected void configure(HttpSecurity http) throws Exception { 
      http 
       .authorizeRequests() 
       .antMatchers("/secured/**") 
        .authenticated(); 
//    .and() 
//    .antMatcher("/secured/**") 
//     .securityContext().securityContextRepository(new NullSecurityContextRepository()) 
//     .and() 
//     .addFilterAt(testAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); 
     } 
    } 

-

@Component("TestAuthenticationFilter") 
public class TestAuthenticationFilter extends GenericFilterBean { 

    @Autowired 
    private TokenHandler tokenHandler; 

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
      throws IOException, ServletException { 
     System.out.println("TestAuthenticationFilter doFitler"); 
     attemptAuthentication((HttpServletRequest) request); 
     chain.doFilter(request, response); 
     clearAuthentication(); 
     System.out.println("doFitler end"); 
    } 

    public void attemptAuthentication(HttpServletRequest request) { 
     try { 
      UserDetails user = tokenHandler.loadUserFromToken(request); 
      UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user, user.getPassword()); 
      SecurityContextHolder.getContext().setAuthentication(auth); 
     } catch (Exception e) { 
      // Do nothing 
     } 
    } 

    public void clearAuthentication() { 
     SecurityContextHolder.getContext().setAuthentication(null); 
    } 

    @Configuration 
    public static class DisableFilterRegistration { 

     @Autowired 
     private TestAuthenticationFilter filter; 

     @Bean 
     public FilterRegistrationBean disablerBean() { 
      FilterRegistrationBean bean = new FilterRegistrationBean(filter); 
      bean.setEnabled(false); 
      return bean; 
     } 
    } 

} 

-

@Component("TokenHandler") 
public class TokenHandler { 

    @Autowired(required = false) 
    private UserDetailsService userDetailsService; 

    public void setToken(HttpServletResponse response, String username) { 
     response.addCookie(new Cookie("user", username)); 
    } 

    public UserDetails loadUserFromToken(HttpServletRequest request) throws BadCredentialsException { 

     Cookie[] cookies = request.getCookies(); 
     Cookie token = null; 
     for (Cookie c : cookies) { 
      if (c.getName().equals("user")) { 
       token = c; 
       break; 
      } 
     } 

     if (token == null) 
      return null; 

     else 
      return userDetailsService.loadUserByUsername(token.getValue()); 
    } 
} 

-

@RestController 
@RequestMapping("/public") 
public class PublicController { 

    @GetMapping("/norole") 
    public String noRole() { 
     return "no role"; 
    } 

    @GetMapping("/user") 
    @PreAuthorize("hasRole('ROLE_USER')") 
    public String roleUser() { 
     return "role_user"; 
    } 
} 

-

@RestController 
@RequestMapping("/secured") 
public class SecuredController { 

    @GetMapping("/user") 
    @PreAuthorize("hasRole('ROLE_USER')") 
    public String roleUser() { 
     return "role_user"; 
    } 

    @GetMapping("/admin") 
    @PreAuthorize("hasRole('ROLE_ADMIN')") 
    public String roleAdmin() { 
     return "role_admin"; 
    } 

    @GetMapping("/norole") 
    public String noRole() { 
     return "no role"; 
    } 
} 

ответ

-1

Логин: от получил функционал снова после объявления добавления

http.antMatcher("/secured/**") 

В качестве первого вызова в WebServiceSecurityConfiguration.configure. Означает ли это, что без него конфигурация отменяет форму-login, которая сконфигурирована после этой конкретной конфигурации? Кроме того, похоже, что позиция antMatcher может быть произвольной, так ли это? Может ли кто-нибудь объяснить, что на самом деле происходит там?

Смежные вопросы