Spring Security 3-始终返回错误302

我使用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. 用户使用http://mylocal:8080/moon=> 访问该网站,该网站显示
  2. 用户按下按钮 ,它会弹出一个子窗口询问用户名和密码=>仍然
  3. 用户按“提交”按钮=>我认为它将进入/ acct / signin并返回到/ demo,但是我在Google Chrome浏览器中看到错误302,然后再次进入/ home

有任何想法吗 ?我被困了整整2天,现在我几乎绝望了…

非常感谢大家看我的问题

更新: *

<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

@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因为您实际上并未通过登录过程对用户进行身份验证。

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

使用InMemoryUserDetailsManagerConfigurer(请参阅inMemoryAuthentication

javadoc),您只能通过配置的凭据成功登录。如果您需要一个完整的身份验证系统,则必须为您的Spring

Security配置提供一个UserDetailsS​​ervice实现(通过userDetailsS​​ervice方法)。


编辑:在与chialin.lin进行对话之后,似乎缺少的配置是Spring Security

的defaultSuccessfulUrl,用于在身份验证后知道将用户重定向到何处。

以上是 Spring Security 3-始终返回错误302 的全部内容, 来源链接: utcz.com/qa/434031.html

回到顶部