Spring Security 3 - always returns error 302

I am using Spring 4 to create a simple application. Recently, I am adding Spring Security 3 to the project, but always get error code 302 (therefore it always redirects to the home page).

Here is my SecurityConfig :

@Configuration @EnableWebMvcSecurity @ComponentScan(basePackages = { "com.moon.repository" }) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("hello").password("world").roles("USER"); } @Override public void configure(WebSecurity web) throws Exception { web .ignoring().antMatchers("/resources/**", "/views/**"); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/","/home").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/home") .loginProcessingUrl("/acct/signin") .and() .logout() .permitAll(); } } 

I have a controller called AccountController :

 @Controller @RequestMapping(value = "/acct") public class AccountController { private final Logger logger = LoggerFactory.getLogger(AccountController.class); @RequestMapping(value = "/signin", method = RequestMethod.POST) public String signin(@RequestParam("username") String username, @RequestParam("password") String password) { logger.info("======== [username:{0}][password:{1}] ========", username, password); if (" error@1.1 ".equalsIgnoreCase(username)) { return "error"; } else { return "demo"; } } } 

My WEB-INF structure:

 WEB-INF ----views --------home.jsp --------demo.jsp --------error.jsp 

The stream looks like this:

  • The user accesses the website using http://mylocal:8080/moon => shows home.jsp
  • The user presses the SignIn button, and a pop-up window appears asking for the username and password => still in home.jsp
  • The user clicks the Submit button = = I assume that he will go / acct / signin and return to / demo, but I see Error 302 in Google Chrome and then he returns to / home again

Any ideas? I was stuck for 2 full days, and now I'm almost in despair ...

Thank you so much to take a look at my problem.

================================== First update =============== ==============

Update: form in home.jsp

 <form:form role="form" method="POST" action="acct/signin" class="form-signin"> <div class="row"> <div class="col-lg-5"> <input name="username" size="20" type="email" class="form-control" placeholder="Email address" required autofocus> <input name="password" type="password" class="form-control" placeholder="Password" required> <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button> </div> </div> </form:form> 

================================== Second update ======= ======== ======================

I tried to implement UserDetailsService (not use auth in memory), but still ... the same problem - Error 302

AppUserDetailsServiceImpl.java

 @Component public class AppUserDetailsServiceImpl implements UserDetailsService { private final Logger logger = LoggerFactory.getLogger(AppUserDetailsServiceImpl.class); @Override public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException { logger.info("loadUserByUsername username=" + username); logger.info("======== {} ========",SecurityContextHolder.getContext().getAuthentication()); if (!username.equals("hello")) { throw new UsernameNotFoundException(username + " not found"); } // creating dummy user details return new UserDetails() { private static final long serialVersionUID = 2059202961588104658L; @Override public boolean isEnabled() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isAccountNonExpired() { return true; } @Override public String getUsername() { return username; } @Override public String getPassword() { return "world"; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { List<SimpleGrantedAuthority> auths = new java.util.ArrayList<SimpleGrantedAuthority>(); auths.add(new SimpleGrantedAuthority("USER")); return auths; } }; } 

The log displays:

 [14/08/19 15:16:32:200][INFO ][com.moon.repository.AppUserDetailsServiceImpl][loadUserByUsername](24) loadUserByUsername username=hello [14/08/19 15:16:32:200][INFO ][com.moon.repository.AppUserDetailsServiceImpl][loadUserByUsername](25) ======== org.springframew ork.security.authentication.UsernamePasswordAuthenticationToken@ f1e4f742: Principal: com.moon.repository.AppUserDetailsServiceImpl$1@e3dc1b1 ; Credentials: [PROTECTED]; Authenticated: true; Details: org.sprin gframework.security.web.authentication.WebAuthenticationDetails@ 12afc: RemoteIpAddress: 127.0.0.1; SessionId: 023BC9A8B997ECBD826DD7C33AF55FC7; Granted Authorities: USER ======== 
+12
source share
3 answers

I believe Spring redirects you to /home because you did not actually authenticate the user through the login process.

  1. You http://mylocal:8080/moon access to your web application via http://mylocal:8080/moon returning the view home.jsp
  2. You click the Login button, submitting the login form since the login form is not explicitly declared, Spring Security will display a window asking you to enter your username and password so that the end user can enter their credentials
  3. These credentials are then sent to the login processing URL ( /acct/signin ) for which you have a mapping to the signin method in AccountController
  4. Such a controller cannot authenticate the Spring user, but still redirects the request to /demo , returning a string
  5. The /demo path is protected ( .anyRequest().authenticated() ) for any user, not .anyRequest().authenticated() authentication, since the current user really did not authenticate, Spring Security will automatically redirect the request to the login page
  6. You are in /home ( .loginPage("/home") )

Using InMemoryUserDetailsManagerConfigurer (see Javadoc inMemoryAuthentication ), you can only log in successfully using the configured credentials. If you need a complete authentication system, you must provide a UserDetailsService implementation for your Spring Security configuration (via the userDetailsService method).


EDIT: After talking to chialin.lin, it seems the missing configuration was defaultSuccessfulUrl for Spring Security to know where to redirect the user after authentication.

+7
source

For me, I came from a slightly different use case, but "suddenly" had the same problem before it worked perfectly.
My Setup Spring with ExtJs frontend, where I am now embedding the rest interface.
Everything worked very well, and suddenly I got an http 302 response (WTH?)

Since I implemented using code, following this example: https://octoperf.com/blog/2018/03/08/securing-rest-api-spring-security/
There is a SimpleUrlAuthenticationSuccessHandler declaration .
See 4.4 SecurityConfig, where a TokenAuthenticationFilter is created with the NoRedirectStrategy class; see 4.1 Redirection Strategy

In turn, if NoRedirectStrategy had not been configured in my AbstractAuthenticationProcessingFilter extension, an http 302 response would have been shown.

+1
source

In order to avoid creating a new trivial SuccessHandler , override the successfulAuthentication method in the filter and simply call the chain.doFilter() method after setting the Authentication object in the security context.

0
source

Source: https://habr.com/ru/post/973955/


All Articles