总是返回错误302

我使用Spring 4创建一个简单的应用程序。 最近,我将Spring Security 3添加到项目中,但始终得到错误代码302(因此它总是重定向到主页 )。

这是我的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();
}

}

我有一个名为AccountController的Controller:

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

}

我的WEB-INF结构:

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

流程如下所示:

  • 用户通过http://mylocal:8080/moon =>访问该网站,它显示了home.jsp
  • 用户按下SignIn键,弹出一个子窗口,询问用户名和密码=>仍然在home.jsp中
  • 用户按提交按钮=>我假定它会去/ acct /登录并返回到/ demo,但我在Google Chrome中看到错误302,然后再次进入/ home
  • 有任何想法吗 ? 我整整呆了两天,现在我几乎陷入绝望......

    非常感谢大家看看我的问题

    ===================================第一次更新============= ======================

    更新: 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>
    

    ===================================第二次更新============= ======================

    我试图实现UserDetailsS​​ervice(不使用内存中的身份验证),但仍...同样的问题 - 错误302

    AppUserDetailsS​​erviceImpl.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;
                }
            };
        }
    

    日志显示:

    [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.springframework.security.authentication.UsernamePasswordAuthenticationToken@f1e4f742: Principal: com.moon.repository.AppUserDetailsServiceImpl$1@e3dc1b1; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@12afc: RemoteIpAddress: 127.0.0.1; SessionId: 023BC9A8B997ECBD826DD7C33AF55FC7; Granted Authorities: USER ========
    

    我相信Spring会将您重定向到/home因为您并未通过登录过程实际验证用户身份。

  • 您可以通过http://mylocal:8080/moon访问您的web应用程序,返回home.jsp视图
  • 您单击SignIn按钮,提交登录表单,因为没有明确声明表单登录,Spring Security将显示用户名和密码提示框,供最终用户输入凭证
  • 然后,将这些凭据发布到登录处理URL( /acct/signin ),您恰好与AccountControllersignin方法有映射
  • 这种控制器无法通过Spring方式对用户进行身份验证,但仍然通过返回字符串将请求重定向到/demo
  • /demo路径受保护( .anyRequest().authenticated() )给任何未经.anyRequest().authenticated()验证的用户,因为当前用户确实未经.anyRequest().authenticated()验证,Spring Security会自动将请求重定向到登录页面
  • 你最终在/home.loginPage("/home")
  • 使用InMemoryUserDetailsManagerConfigurer(请参阅inMemoryAuthentication javadoc),只能通过配置的凭证成功登录。 如果你想要一个完整的认证系统,你必须为你的Spring Security配置提供一个UserDetailsS​​ervice实现(通过userDetailsS​​ervice方法)。


    编辑:在与chialin.lin的对话之后,似乎缺少的配置是Spring Security的defaultSuccessfulUrl,以知道一旦通过身份验证后,用户将重定向到哪里。


    为了避免必须创建一个新的繁琐的SuccessHandler,请在您的Filter中重写successfulAuthentication方法,并在SecurityContext上设置Authentication之后调用chain.dofilter()。

    链接地址: http://www.djcxy.com/p/80955.html

    上一篇: always return error 302

    下一篇: Store global strings in iOS in Swift for app