0
У меня есть форма входа в систему, фаза входа в систему jsf и служба сведений о пользователе. Хотя пользователь аутентифицирован, он не перенаправляется на целевую страницу. Боб аутентифицирует пользователя через UserDetailsService без каких-либо проблем.Spring Security не перенаправляется на целевую страницу после успешного входа в систему через форму JSF
package com.emredincer.yetki.bean;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.security.sasl.AuthenticationException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import com.emredincer.yetki.entity.Kullanici;
import com.emredincer.yetki.service.IKullaniciService;
@ManagedBean(name = "loginBean")
@RequestScoped
public class LoginBean {
private String username = null;
private String password = null;
@ManagedProperty(value="#{authenticationManager}")
private AuthenticationManager authenticationManager = null;
@ManagedProperty("#{KullaniciServiceImpl}")
private IKullaniciService kullaniciServis;
private Kullanici kullanici = new Kullanici();
public String login(){
try{
Authentication request = new UsernamePasswordAuthenticationToken(this.getUsername(), this.getPassword());
Authentication result = authenticationManager.authenticate(request);
SecurityContextHolder.getContext().setAuthentication(result);
}
catch(Exception e){
e.printStackTrace();
return "incorrect";
}
return "correct";
}
public String logout(){
SecurityContextHolder.clearContext();
return "loggedout";
}
public AuthenticationManager getAuthenticationManager() {
return authenticationManager;
}
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public IKullaniciService getKullaniciServis() {
return kullaniciServis;
}
public void setKullaniciServis(IKullaniciService kullaniciServis) {
this.kullaniciServis = kullaniciServis;
}
public Kullanici getKullanici() {
return kullanici;
}
public void setKullanici(Kullanici kullanici) {
this.kullanici = kullanici;
}
}
<http auto-config="true">
<intercept-url pattern="/web/*" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<intercept-url pattern="/**" access="ROLE_USER" />
<form-login login-page="/web/login.xhtml"
authentication-success-handler-ref="successHandler"
/>
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="kullaniciDetayServisi" />
</authentication-manager>
</beans:beans>
public class CustomAuthSuccessHandler implements AuthenticationSuccessHandler {
public void onAuthenticationSuccess(HttpServletRequest arg0,
HttpServletResponse arg1, Authentication arg2) throws IOException,
ServletException {
arg1.sendRedirect(arg0.getContextPath() + "/main.xhtml");
}
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
</h:head>
<h:body>
<div align="center" style="">
<h:form id="loginFormId" prependId="false">
<div id="loginFieldsPnlId">
<div id="loginFieldUsrContId">
<h:outputText id="outTxtUserNameId" value="Username: " name="outTxtUserNameNm"></h:outputText>
<h:inputText id="userName" required="true" value="#{loginBean.username}" requiredMessage="Please enter username"></h:inputText>
<h:outputLabel id="outLblUserNameId" for="userName" name="outLblUserNameNm"></h:outputLabel>
</div>
<div id="loginFieldPassContId">
<h:outputText id="outTxtPasswordId" value="Password: " name="outTxtPasswordNm"></h:outputText>
<h:inputSecret id="password" required="true" value="#{loginBean.password}" requiredMessage="Please enter password" name="inTxtPasswordNm"></h:inputSecret>
<h:outputLabel id="outLblPasswordId" for="password" name="outLblPasswordNm"></h:outputLabel>
</div>
</div>
<div id="loginBtnPanelId">
<h:commandButton id="btnLoginId" value="Login" action="#{loginBean.login}" styleClass="loginPanelBtn" ajax="false"></h:commandButton>
<h:commandButton id="btnCancelId" value="Cancel" action="#{loginBean.cancel}" styleClass="loginPanelBtn" immediate="true" update="loginFormId"></h:commandButton>
</div>
</h:form>
</div>
<div>
<h:messages></h:messages>
</div>
</h:body>
</html>
Это приведет к переходу, а не к переадресации, что технически совсем другое. Основные технические требования для обоих способов навигации, безусловно, не подлежат обмену (idempotent vs non-idempotent). Надеюсь, вы понимаете его последствия для поведения клиентов и пользователей. Что касается вашей конкретной проблемы, причина не видна в представленной до сих пор информации, но вам нужно убедиться, что вы выполняете логин без ajax (например, удалите f: ajax, или если вы используете кнопку правки, установите ajax = "false «). – BalusC
спасибо за ваш ответ, а какая разница между переадресацией и перенаправлением с точки зрения пользователя? пожалуйста, дайте краткое объяснение. – desperado06
http://stackoverflow.com/q/15521451 – BalusC