我的mysql表中有一个有效用户,用户名= alex和密码= 123。 因此,当我尝试用错误的用户名登录时,例如bob,fred,pit等都可以 我收到身份验证错误。 但是当我尝试使用有效的用户名= alex进行身份验证时,无论我输入什么密码,它都将是“123”或“213”或“12afaf12”,我总是收到成功登录。我认为身份验证管理器不会检查密码。你能帮助我吗? 有我的来源:
security-config.xml
<security:http auto-config="true">
<security:form-login
login-page="/login.xhtml"
authentication-failure-url="/loginfailed.xhtml"
default-target-url="/succes.xhtml"
/>
<security:logout
logout-url="/app/logout"
logout-success-url="/app/main"
/>
</security:http>
<security:authentication-manager>
<security:authentication-provider user-service-ref="userService">
<!-- <security:password-encoder hash="md5" />-->
</security:authentication-provider>
<bean id="daoAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="userService" />
<property name="hideUserNotFoundExceptions" value="false" />
</bean>
<bean id="authenticationManager" class="org.springframework.security.authentication.ProviderManager">
<constructor-arg>
<ref local="daoAuthenticationProvider" />
</constructor-arg>
</bean>
自定义UserDetailsService类
import com.app.dao.UserDao;
import com.app.model.UserEntity;
import com.app.service.intf.UserServiceIntf;
@Service("userService")
public class UserService implements UserServiceIntf, UserDetailsService {
@Autowired
private UserDao userDao;
/**
* Construct UserDetails instance required by spring security
*/
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
UserEntity user = userDao.loadUserByUserName(userName);
if (user == null) {
throw new UsernameNotFoundException(String.format(getMessageBundle().getString("badCredentials"), userName));
}
Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
System.out.println("user.getUserName()"+ user.getUserName());
User userDetails = new User(user.getUserName(), user.getPassword(), authorities);
return userDetails;
}
/**
* Retrieves full User record from database by user name
*
* @param userName
* @return UserEntity
*/
public UserEntity loadUserEntityByUsername(String userName) {
return userDao.loadUserByUserName(userName);
}
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
userDAO的
@Repository
public class UserDao implements UserDaoIntf {
@PersistenceContext
private EntityManager entityManager;
protected EntityManager getEntityManager() {
return entityManager;
}
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
/**
* Queries user by username
*
* @param userName
* @return User entity
*/
public UserEntity loadUserByUserName(String userName) {
Assert.notNull(userName);
UserEntity user = null;
Query query = getEntityManager().createQuery("select u from UserEntity"
+ " u where u.userName = :userName").setParameter("userName", userName);
try {
user = (UserEntity) query.getSingleResult();
} catch(NoResultException e) {
//do nothing
}
return user;
}
}
身份验证服务:
@Service("userAuthenticationProviderServiceImpl")
public class UserAuthenticationProviderServiceImpl implements UserAuthenticationProviderService {
@Autowired
private AuthenticationManager authenticationManager;
/**
* Process user authentication
*
* @param user
* @return
*/
public boolean processUserAuthentication(UserEntity user) {
try {
Authentication request = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
Authentication authenticate = authenticationManager.authenticate(request);
if (authenticate.isAuthenticated()) {
SecurityContextHolder.getContext().setAuthentication(authenticate);
return true;
}
} catch(AuthenticationException e) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), "Sorry!"));
}
return false;
}
public AuthenticationManager getAuthenticationManager() {
return authenticationManager;
}
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
}
我认为 authenticate.isAuthenticated()中的问题总是返回true,无论我输入什么密码,如果用户名有效
UPDATE1: 添加我的用户实体
@Entity
@Table(name="appuser")
public class UserEntity {
@Id
@GeneratedValue
private Long id;
private String firstName;
private String lastName;
private String userName;
private String password;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
PasswordEncoder crypto = new Md5PasswordEncoder();
this.password = crypto.encodePassword(password, null);
}
}
UserManagedBean
@Component
@ViewScoped
public class UserManagedBean {
public UserManagedBean(){
System.out.println("Just for test, usermanagedbean nstantiated");
}
@Inject
private UserService userService;
@Inject
private UserAuthenticationProviderServiceImpl userAuth;
private UserEntity user;
private String userName;
private String password;
private String isAuth;
public UserEntity getUser() {
return user;
}
public void setUser(UserEntity user) {
this.user = user;
}
public String getUserName() {
return userName;
}
public String getIsAuth() {
return isAuth;
}
public void setIsAuth(String isAuth) {
this.isAuth = isAuth;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String doLogin() {
UserEntity user = userService.loadUserEntityByUsername(userName);
FacesContext context = FacesContext.getCurrentInstance();
if (user == null){
System.out.println("user == null");
context.addMessage("somekey", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid Username or Password", "Invalid username or Password"));
return null;
}
boolean result = userAuth.processUserAuthentication(user);
if (result) {
context.addMessage(null, new FacesMessage("Login Info", "Succesfully login!"));
isAuthenticated();
return "OK";
} else {
System.out.println("ERRRROR");
}
return null;
}
public void isAuthenticated() {
if(SecurityContextHolder.getContext().getAuthentication() != null &&
SecurityContextHolder.getContext().getAuthentication().isAuthenticated()){
setIsAuth("OK");
}
}
}
登录页面:
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
template="/WEB-INF/templates/general.xhtml">
<ui:define name="title"><h:outputText value="Please Sign In" /></ui:define>
<ui:define name="header"><h:outputText value="Please Sign In" /></ui:define>
<ui:define name="content">
<h:form id="loginForm" prependId="false">
<p:fieldset styleClass="fieldset" legend="Authentication Form">
<p:focus />
<p:messages id="messages" for="somekey" />
<p:growl id="growlMessages" showDetail="true" sticky="true" life="13000" globalOnly="true"/>
<h:panelGrid id="logPanelGrid" style="margin: 0 auto; margin-top: 25px; text-align: right" cellspacing="8" columns="3">
<h:panelGroup>
<h:outputText value="User Name:" />
<h:outputText style="color:red" value="* " />
</h:panelGroup>
<p:inputText id="userName" value="#{userManagedBean.userName}" required="true" label="User Name" title="Enter your User Name!" />
<h:panelGroup>
<p:message id="userNameMsg" for="userName" />
<p:tooltip for="userName" styleClass="tooltip" showEvent="focus" hideEvent="blur" />
</h:panelGroup>
<h:panelGroup>
<h:outputText value="Enter Password:" />
<h:outputText style="color:red" value="* " />
</h:panelGroup>
<p:password id="pass" value="#{userManagedBean.password}" required="true" label="Password" title="Please enter a password!" />
<h:panelGroup>
<p:message id="passMsg" for="pass" />
<p:tooltip for="pass" styleClass="tooltip" showEvent="focus" hideEvent="blur" />
</h:panelGroup>
<p:commandButton id="newUserButton" action="newUser" icon="ui-icon-plus" value="Sign Up" />
<p:commandButton id="submitButton" update="growlMessages,messages" action="#{userManagedBean.doLogin()}" value="SignIn" />
</h:panelGrid>
</p:fieldset>
</h:form>
</ui:define>
更新2:已解决 我通过替换 UserManagedBean
中的代码解决了我的问题UserEntity user = userService.loadUserEntityByUsername(userName);
带
UserEntity user = new UserEntity();
user.setPassword(password);
user.setUserName(userName);
你怎么看?