弹簧安全 3 - 始终返回错误 302

2022-09-04 22:20:22

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

这是我的安全配置

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

}

我有一个名为帐户控制器的控制者

@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

流程如下:

  1. 用户访问网站时显示>主页.jsphttp://mylocal:8080/moon
  2. 用户按下按钮 SignIn 它会弹出一个子窗口,要求输入用户名和密码 = >仍然在家中.jsp
  3. 用户按提交按钮=>我假设它会转到/acct/signin并返回/demo,但我在Google Chrome中看到错误302,然后它再次转到/home

有什么想法吗?我被困在整整2天,现在我几乎绝望了...

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

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

更新:家庭中的表格.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>

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

我试图实现UserDetailsService(不使用内存中身份验证),但仍然...同样的问题 - 错误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;
            }
        };
    }

日志显示:

[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 ========

答案 1

我相信Spring正在将您重定向到,因为您实际上没有通过登录过程对用户进行身份验证。/home

  1. 您可以通过返回主页.jsp视图来访问您的 Web 应用程序http://mylocal:8080/moon
  2. 您单击“登录”按钮,提交登录表单,因为没有明确声明表单登录名,Spring Security将显示用户名和密码提示框,供最终用户输入其凭据
  3. 然后将这些凭据 POST 到登录处理 URL (),您碰巧与/acct/signinsigninAccountController
  4. 此类控制器无法以 Spring 方式对用户进行身份验证,但仍通过返回 String 将请求重定向到/demo
  5. 该路径是受保护的()给任何未经身份验证的用户,由于当前用户确实未经身份验证,Spring Security会自动将请求重定向到登录页面/demo.anyRequest().authenticated()
  6. 你最终在/home (.loginPage("/home"))

使用 InMemoryUserDetailsManagerConfigurer(请参阅 inMemoryAuthentication javadoc),您只能通过配置的凭据成功登录。如果您想要一个成熟的身份验证系统,则必须在Spring Security配置中提供UserDetailsService实现(通过userDetailsService方法)。


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


答案 2

为了避免必须创建新的 trivial ,请重写筛选器中的方法,并在安全上下文中设置对象后调用该方法。SuccessHandlersuccessfulAuthenticationchain.doFilter()Authentication


推荐