2015-05-21 4 views
36

Sto usando la sicurezza primavera senza stato, ma in caso di iscrizione voglio disabilitare primavera security.I disattivato usandoCome disattivare la sicurezza molla per particolare url

antMatchers("/api/v1/signup").permitAll(). 

ma non funziona, sto ottenendo l'errore qui di seguito:

message=An Authentication object was not found in the SecurityContext, type=org.springframework.security.authentication.AuthenticationCredentialsNotFoundException 

penso che questo significa filtri di sicurezza primavera stanno lavorando

l'ordine di mia url sempre sarà "/ api/v1"

mio config primavera è

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

     http. 
     csrf().disable(). 
     sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS). 
     and(). 
     authorizeRequests(). 
     antMatchers("/api/v1/signup").permitAll(). 
     anyRequest().authenticated(). 
     and(). 
     anonymous().disable(); 
     http.addFilterBefore(new AuthenticationFilter(authenticationManager()), BasicAuthenticationFilter.class); 
    } 

mio filtro di autenticazione è

@Override 
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { 
     HttpServletRequest httpRequest = asHttp(request); 
     HttpServletResponse httpResponse = asHttp(response); 

     String username = httpRequest.getHeader("X-Auth-Username"); 
     String password = httpRequest.getHeader("X-Auth-Password"); 
     String token = httpRequest.getHeader("X-Auth-Token"); 

     String resourcePath = new UrlPathHelper().getPathWithinApplication(httpRequest); 

     try { 

      if (postToAuthenticate(httpRequest, resourcePath)) {    
       processUsernamePasswordAuthentication(httpResponse, username, password); 
       return; 
      } 

      if(token != null){ 
       processTokenAuthentication(token); 
      } 
      chain.doFilter(request, response); 
     } catch (InternalAuthenticationServiceException internalAuthenticationServiceException) { 
      SecurityContextHolder.clearContext(); 
      logger.error("Internal authentication service exception", internalAuthenticationServiceException); 
      httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); 
     } catch (AuthenticationException authenticationException) { 
      SecurityContextHolder.clearContext(); 
      httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, authenticationException.getMessage()); 
     } finally { 
     } 
    } 

    private HttpServletRequest asHttp(ServletRequest request) { 
      return (HttpServletRequest) request; 
     } 

     private HttpServletResponse asHttp(ServletResponse response) { 
      return (HttpServletResponse) response; 
     } 

     private boolean postToAuthenticate(HttpServletRequest httpRequest, String resourcePath) { 
      return Constant.AUTHENTICATE_URL.equalsIgnoreCase(resourcePath) && httpRequest.getMethod().equals("POST"); 
     } 

     private void processUsernamePasswordAuthentication(HttpServletResponse httpResponse,String username, String password) throws IOException { 
      Authentication resultOfAuthentication = tryToAuthenticateWithUsernameAndPassword(username, password); 
      SecurityContextHolder.getContext().setAuthentication(resultOfAuthentication); 
      httpResponse.setStatus(HttpServletResponse.SC_OK); 
      httpResponse.addHeader("Content-Type", "application/json"); 
      httpResponse.addHeader("X-Auth-Token", resultOfAuthentication.getDetails().toString()); 
     } 

     private Authentication tryToAuthenticateWithUsernameAndPassword(String username,String password) { 
      UsernamePasswordAuthenticationToken requestAuthentication = new UsernamePasswordAuthenticationToken(username, password); 
      return tryToAuthenticate(requestAuthentication); 
     } 

     private void processTokenAuthentication(String token) { 
      Authentication resultOfAuthentication = tryToAuthenticateWithToken(token); 
      SecurityContextHolder.getContext().setAuthentication(resultOfAuthentication); 
     } 

     private Authentication tryToAuthenticateWithToken(String token) { 
      PreAuthenticatedAuthenticationToken requestAuthentication = new PreAuthenticatedAuthenticationToken(token, null); 
      return tryToAuthenticate(requestAuthentication); 
     } 

     private Authentication tryToAuthenticate(Authentication requestAuthentication) { 
      Authentication responseAuthentication = authenticationManager.authenticate(requestAuthentication); 
      if (responseAuthentication == null || !responseAuthentication.isAuthenticated()) { 
       throw new InternalAuthenticationServiceException("Unable to authenticate Domain User for provided credentials"); 
      } 
      logger.debug("User successfully authenticated"); 
      return responseAuthentication; 
     } 

mio controller è

@RestController 
public class UserController { 

    @Autowired 
    UserService userService; 

    /** 
    * to pass user info to service 
    */ 
    @RequestMapping(value = "api/v1/signup",method = RequestMethod.POST) 
    public String saveUser(@RequestBody User user) { 
     userService.saveUser(user); 
     return "User registerted successfully"; 
    } 
} 

io sono totalmente nuovo a primavera, please help me come farlo?

+0

Dai un'occhiata a: http://stackoverflow.com/questions/4487249/how-do-i-ge t-allowall-in-spring-security-to-not-throw-authenticationcredentials –

risposta

61

Quando si utilizza permitAll che significa che ogni utente autenticato, tuttavia è disattivato l'accesso anonimo in modo che non funzionerà.

quello che vuoi è di ignorare certi URL per questo l'override del metodo configure che prende WebSecurity oggetto e ignore il modello.

@Override 
public void configure(WebSecurity web) throws Exception { 
    web.ignoring().antMatchers("/api/v1/signup"); 
} 

E rimuovere quella linea dalla parte HttpSecurity. Questo indicherà a Spring Security di ignorare questo URL e di non applicare alcun filtro a loro.

+3

in che file viene scritto? –

+1

@JacobZimmerman https://spring.io/blog/2013/07/03/spring-security-java-config-preview-web-security/ il configuratore per la classe di sicurezza Web –

+0

Mi rendo conto che questo è un vecchio post. Volevo solo dire grazie.La tua soluzione ha funzionato quando altri hanno fallito. Ho anche provato ad usare qualcosa di simile a questo: http .authorizeRequests() .antMatchers ("/ api/v1/signup/**"). AllowAll() .anyRequest(). Authenticated() – Carl

6
<http pattern="/resources/**" security="none"/> 

O con configurazione di Java:

web.ignoring().antMatchers("/resources/**"); 

Al posto del vecchio:

<intercept-url pattern="/resources/**" filters="none"/> 

per exp. disabilitare la protezione per una pagina di login:

<intercept-url pattern="/login*" filters="none" /> 
5

Ho un modo migliore:

http 
    .authorizeRequests() 
    .antMatchers("/api/v1/signup/**").permitAll() 
    .anyRequest().authenticated() 
5

Questo non può essere la risposta completa alla tua domanda, se siete alla ricerca di modo per disattivare la protezione CSRF si può fare:

@EnableWebSecurity 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http.authorizeRequests() 
       .antMatchers("/web/admin/**").hasAnyRole(ADMIN.toString(), GUEST.toString()) 
       .anyRequest().permitAll() 
       .and() 
       .formLogin().loginPage("/web/login").permitAll() 
       .and() 
       .csrf().ignoringAntMatchers("/contact-email") 
       .and() 
       .logout().logoutUrl("/web/logout").logoutSuccessUrl("/web/").permitAll(); 
    } 

    @Autowired 
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 
     auth.inMemoryAuthentication() 
       .withUser("admin").password("admin").roles(ADMIN.toString()) 
       .and() 
       .withUser("guest").password("guest").roles(GUEST.toString()); 
    } 

} 

Ho incluso la configurazione completa ma la linea chiave è:

.csrf().ignoringAntMatchers("/contact-email")