问题描述
我使用Spring 4创建一个简单的应用程序。最近,我将Spring Security 3添加到项目中,但总是得到错误代码302(因此它总是重定向到主页页面)。
I use Spring 4 to create a simple application. Recently, I'm adding Spring Security 3 to the project but always get the Error Code 302 ( so it redirect to home page always ).
这是我的 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
@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 ("[email protected]".equalsIgnoreCase(username)) {
return "error";
} else {
return "demo";
}
}
}
我的网页-INF结构:
My WEB-INF structure:
WEB-INF
----views
--------home.jsp
--------demo.jsp
--------error.jsp
流程如下:
- 用户使用<$ c访问网站$ c> http:// mylocal:8080 / moon =>它显示 home.jsp
- 用户按下按钮登录并弹出一个子窗口,询问用户名和密码=>仍然在 home.jsp
- 用户按提交按钮=>我假设它将进入/ acct / signin并返回/ demo,但我在Google Chrome中看到错误302,然后再次进入/ home
- User access the web site with
http://mylocal:8080/moon
=> it shows home.jsp - User press the button SignIn and it pops a sub-window asked for username and password => still in home.jsp
- User press Submit button => I assume it will go /acct/signin and return to /demo, but I see Error 302 in Google Chrome and then it goes to /home again
任何想法?我被困在了整整两天,现在我几乎绝望了......
Any ideas ? I'm stuck in 2 full days and now i'm almost in despair...
非常感谢你们每个人看看我的问题
thank you very much every one to take a look at my problem
===================================第一次更新===================================
更新: 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>
================== =================第二次更新=============================== ====
我试图实现UserDetailsService(不使用内存中的auth)但仍然......同样的问题 - 错误302
I tried to implement UserDetailsService(not to use in-memory auth) 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;
}
};
}
日志显示:
[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
,因为您实际上并未通过登录过程对用户进行身份验证。
I believe Spring is redirecting you to /home
because you didn't actually authenticated a User through the login process.
- 您可以通过
http:// mylocal:8080 / moon
访问您的网络应用程序返回home.jsp视图 - 您单击SignIn按钮,提交您的登录表单
- 然后将这些凭据发布到登录处理URL(
/ acct / signin
),您碰巧与signin
AccountController中的方法
- 这样的控制器无法验证用户Spring方式,但仍然通过返回一个字符串将请求重定向到
/ demo
-
/ demo
路径受到保护(.anyRequest()。authenticated()
)任何未经身份验证的用户,因为当前用户确实未经身份验证,Spring Security会自动将请求重定向到登录页面 - 您最终在
/ home
(.loginPage(/ home)
)
- You access your web-app through
http://mylocal:8080/moon
returning the home.jsp view - You click the SignIn button, submitting your login form
- These credentials are then POSTed to the login processing URL (
/acct/signin
) for which you happen to have a mapping with thesignin
method in theAccountController
- Such controller fails to authenticate a User the Spring way, but still redirect the request to
/demo
by returning a String - The
/demo
path is protected (.anyRequest().authenticated()
) to any unauthenticated user, since the current user is indeed unauthenticated, Spring Security will automatically redirect the request to the login page - You end up on
/home
(.loginPage("/home")
)
使用(参见 javadoc),您只能通过配置的凭据成功登录。如果您想要一个成熟的身份验证系统,您必须提供实现到您的Spring Security配置(通过方法)。
Using a InMemoryUserDetailsManagerConfigurer (see inMemoryAuthentication javadoc), you can only successfully login through the configured credentials. If you want a fully-fledged Authentication system, you must provide an UserDetailsService implementation to your Spring Security configuration (through the userDetailsService method).
编辑:在与chialin.lin交谈之后,似乎缺少的配置是知道重定向的地方ct用户一旦通过身份验证。
EDIT : Following the conversation with chialin.lin, it seems the missing configuration was a defaultSuccessfulUrl for Spring Security to know where to redirect the user once authenticated.
这篇关于Spring Security 3 - 始终返回错误302的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!