我SRING申請後有以下春季安全配置:春季安全返回到登錄頁面登錄成功
@Configuration
@ComponentScan(value="org.webapp")
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource restDataSource;
@Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.jdbcAuthentication()
.dataSource(restDataSource)
.usersByUsernameQuery(getUserQuery())
.authoritiesByUsernameQuery(getAuthoritiesQuery());
}
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.authorizeRequests()
.antMatchers("/css/**", "/fonts/**", "/image/**", "/js/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/spring/index").permitAll()
.loginProcessingUrl("/spring/login").permitAll()
.usernameParameter("login")
.passwordParameter("senha")
.successHandler(new CustomAuthenticationSuccessHandler())
.failureHandler(new CustomAuthenticationFailureHandler())
.and()
.logout()
.logoutUrl("/spring/logout")
.logoutSuccessUrl("/spring/index").permitAll();
}
private String getUserQuery() {
return "SELECT login as username, senha as password "
+ "FROM usuario "
+ "WHERE login = ?";
}
private String getAuthoritiesQuery() {
return "SELECT DISTINCT usuario.login as username, autorizacao.descricao as authority "
+ "FROM usuario, autorizacao_usuario, autorizacao "
+ "WHERE usuario.id = autorizacao_usuario.fk_usuario "
+ "AND autorizacao.id = autorizacao_usuario.fk_autorizacao "
+ "AND usuario.login = ? ";
}
}
但我有一個問題是:當我告知登錄credencials,系統返回到登錄頁面而不是目標頁面(/ spring/home)。我查看堆棧軌道,沒有顯示錯誤。
有人可以看到有什麼問題嗎?
UPDATE
CustomAuthenticationSuccessHandler
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication auth) throws IOException, ServletException {
System.out.println("CustomAuthenticationSuccessHandler");
HttpSession session = request.getSession();
SavedRequest savedReq = (SavedRequest) session.getAttribute(WebAttributes.ACCESS_DENIED_403);
if (savedReq == null) {
response.sendRedirect(request.getContextPath() + "/spring/home");
}
else {
response.sendRedirect(savedReq.getRedirectUrl());
}
}
}
CustomAuthenticationFailureHandler
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException auth) throws IOException, ServletException {
System.out.println("CustomAuthenticationFailureHandler");
response.sendRedirect(request.getContextPath() + "/spring/erro-login");
}
}
UPDATE 2
項目的完整的源代碼可以在這裏看到:https://github.com/klebermo/webapp1
你肯定認證成功好不好? (你是否已經通過調試來檢查用戶是否經過了身份驗證)。還需要查看自定義成功/失敗處理程序的代碼,以查看重定向 – rhinds
將它們添加到主題中的情況,但我認爲這不是問題。在stacktrace中,我可以看到應用程序到達它們(如果是failureHandler),但它仍然返回到登錄頁面,而不是主頁或錯誤頁面。當我有inMemory身份驗證時,它工作正常。 –