Comment désactiver la sécurité du spring pour une URL particulière

J’utilise une sécurité à ressort sans état, mais en cas d’inscription, je veux désactiver la sécurité du spring.

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

mais cela ne fonctionne pas, je reçois une erreur ci-dessous:

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

Je pense que cela signifie que les filtres de sécurité à ressort fonctionnent

L’ordre de mon URL sera toujours “/ api / v1”

Ma config de spring est

 @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); } 

Mon filtre d’authentification est

 @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = asHttp(request); HttpServletResponse httpResponse = asHttp(response); Ssortingng username = httpRequest.getHeader("X-Auth-Username"); Ssortingng password = httpRequest.getHeader("X-Auth-Password"); Ssortingng token = httpRequest.getHeader("X-Auth-Token"); Ssortingng 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, Ssortingng resourcePath) { return Constant.AUTHENTICATE_URL.equalsIgnoreCase(resourcePath) && httpRequest.getMethod().equals("POST"); } private void processUsernamePasswordAuthentication(HttpServletResponse httpResponse,Ssortingng username, Ssortingng 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().toSsortingng()); } private Authentication tryToAuthenticateWithUsernameAndPassword(Ssortingng username,Ssortingng password) { UsernamePasswordAuthenticationToken requestAuthentication = new UsernamePasswordAuthenticationToken(username, password); return tryToAuthenticate(requestAuthentication); } private void processTokenAuthentication(Ssortingng token) { Authentication resultOfAuthentication = tryToAuthenticateWithToken(token); SecurityContextHolder.getContext().setAuthentication(resultOfAuthentication); } private Authentication tryToAuthenticateWithToken(Ssortingng 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; } 

Mon contrôleur est

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

Je suis totalement nouveau au spring, aidez-moi s’il vous plaît comment le faire?

Lorsque vous utilisez permitAll cela signifie que chaque utilisateur authentifié, mais vous avez désactivé l’access anonyme afin que cela ne fonctionne pas.

Ce que vous voulez, c’est ignorer certaines URL pour que cette méthode remplace la méthode configure qui prend l’object WebSecurity et ignore le modèle.

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

Et supprimez cette ligne de la partie HttpSecurity . Cela indiquera à Spring Security d’ignorer cette URL et de ne lui appliquer aucun filtre.

  

Ou avec la configuration Java:

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

Au lieu de l’ancien:

   

pour exp. désactiver la sécurité pour une page de connexion:

   

J’ai un meilleur moyen:

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

Cela peut ne pas être la réponse complète à votre question, mais si vous cherchez un moyen de désactiver la protection csrf, vous pouvez le faire:

 @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/web/admin/**").hasAnyRole(ADMIN.toSsortingng(), GUEST.toSsortingng()) .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.toSsortingng()) .and() .withUser("guest").password("guest").roles(GUEST.toSsortingng()); } } 

J’ai inclus la configuration complète mais la ligne principale est la suivante:

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