2017-07-21 11 views
11

मैं एक बाकी एपीआई नियंत्रक के लिए परीक्षण लिख रहा हूं। यह अंत बिंदु किसी भी प्राधिकरण के बिना पहुँचा जा सकता है:स्प्रिंग बूट परीक्षण वेब सुरक्षा कॉन्फ़िगरेशन का सम्मान नहीं करता

@EnableWebSecurity 
@Configuration 
@Import(AppConfig.class) 
class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

@Autowired 
private UserDetailsRepository accountRepository; 

@Autowired 
private CustomUserDetailsService customUserDetailsService; 

@Autowired 
private JWTAuthenticationFilter jwtAuthenticationFilter; 

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http 
     .csrf().disable() 
     .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class) 
     .authorizeRequests() 
      .anyRequest().authenticated().and() 
     .sessionManagement() 
      .sessionCreationPolicy(SessionCreationPolicy.STATELESS); 
} 

/* 
* Apparently, permitAll() doesn't work for custom filters, therefore we ignore the signup and login endpoints 
* here 
*/ 
@Override 
public void configure(WebSecurity web) 
     throws Exception { 
    web.ignoring() 
     .antMatchers(HttpMethod.POST, "/login") 
     .antMatchers(HttpMethod.POST, "/signup"); 
} 

/* 
* set user details services and password encoder 
*/ 
@Override 
protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
    auth.userDetailsService(userDetailsServiceBean()).passwordEncoder(passwordEncoder()); 
} 

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

/* Stopping spring from adding filter by default */ 
@Bean 
public FilterRegistrationBean rolesAuthenticationFilterRegistrationDisable(JWTAuthenticationFilter filter) { 
    FilterRegistrationBean registration = new FilterRegistrationBean(filter); 
    registration.setEnabled(false); 
    return registration; 
} 

}

JWTAuthenticationFilter वर्ग:

@Component 
public class JWTAuthenticationFilter extends AbstractAuthenticationProcessingFilter { 

    @Autowired 
    private UserDetailsService customUserDetailsService; 

    private static Logger logger = LoggerFactory.getLogger(JWTAuthenticationFilter.class); 
    private final static UrlPathHelper urlPathHelper = new UrlPathHelper(); 

    final static String defaultFilterProcessesUrl = "/**"; 

    public JWTAuthenticationFilter() { 
     super(defaultFilterProcessesUrl); 
     super.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher(defaultFilterProcessesUrl)); //Authentication will only be initiated for the request url matching this pattern 
     setAuthenticationManager(new NoOpAuthenticationManager()); 
    } 

    @Override 
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { 
     Authentication authentication = AuthenticationService.getAuthentication(request, customUserDetailsService); 
     return getAuthenticationManager().authenticate(authentication); 
    } 

    @Override 
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException { 
     logger.debug("failed authentication while attempting to access "+ urlPathHelper.getPathWithinApplication((HttpServletRequest) request)); 
     response.sendError(HttpServletResponse.SC_UNAUTHORIZED,"Authentication Failed"); 
    } 

    @Override 
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { 
     SecurityContextHolder.getContext().setAuthentication(authResult); 
     chain.doFilter(request, response); 
    } 

    @Override 
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { 
     super.doFilter(req, res, chain); 
    } 
} 

जब मैं एक अनुरोध (डाकिया का प्रयोग करके) 'साइनअप' के लिए कर endpoint यह ठीक काम करता है। लेकिन जब मैं परीक्षण चलाता हूं, तो यह doFilter हिट करता है और विफल रहता है, क्योंकि यह प्रमाणित नहीं होता है।

@RunWith(SpringRunner.class) 
@SpringBootTest 
@AutoConfigureMockMvc 
public class AuthenticationControllerFTest { 

    @Autowired 
    private MockMvc mockMvc; 

    @MockBean 
    private AuthenticationManager authenticationManager; 

    @Test 
    public void testCreate() throws Exception { 
     Authentication authentication = Mockito.mock(Authentication.class); 
     Mockito.when(authentication.getName()).thenReturn("DUMMY_USERNAME"); 
     Mockito.when(
       authenticationManager.authenticate(Mockito 
         .any(UsernamePasswordAuthenticationToken.class))) 
       .thenReturn(authentication); 

     String exampleUserInfo = "{\"name\":\"Test1234\",\"username\":\"[email protected]\",\"password\":\"Salam12345\"}"; 
     RequestBuilder requestBuilder = MockMvcRequestBuilders 
       .post("/signup") 
       .accept(MediaType.APPLICATION_JSON).content(exampleUserInfo) 
       .contentType(MediaType.APPLICATION_JSON); 

     MvcResult result = mockMvc.perform(requestBuilder).andReturn(); 

     MockHttpServletResponse response = result.getResponse(); 
     int status = response.getStatus(); 
     String content = response.getContentAsString(); 
     System.out.println(content); 
     Assert.assertEquals("http response status is wrong", 200, status); 
    } 
} 

इस मुद्दे को ठीक करने के तरीके पर कोई विचार?

उत्तर

8

मुद्दा परीक्षण वर्ग के लिए निम्न कोड जोड़कर हल किया गया था: कोड में टिप्पणी पर

@Autowired 
private WebApplicationContext context; 

@Autowired 
private Filter springSecurityFilterChain; 

@Before 
public void setup() { 
    mockMvc = MockMvcBuilders.webAppContextSetup(context) 
      .addFilters(springSecurityFilterChain).build(); 
} 
+0

यहां एक अच्छा पठन है: https://spring.io/blog/2014/05/23/preview-spring- सुरक्षा-परीक्षण-वेब-सुरक्षा –

-1
@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http.csrf().disable().authorizeRequests() 
      .antMatchers("/**").permitAll() 
      .anyRequest().authenticated(); 
} 
+0

देखो: '' '/ * * जाहिर है, permitAll() 'नहीं करता है टी कस्टम फिल्टर के लिए काम नहीं करते हैं, इसलिए हम साइनअप को अनदेखा करते हैं और लॉगिन अंतराल * यहां */'' –

संबंधित मुद्दे