Note that there are some explanatory texts on larger screens.

plurals
  1. POBadCredentialsException is spring-security
    primarykey
    data
    text
    <p>continue my projects I encountered a problem in the authorization for accounts in Spring setsurity - Problems in the query to the database, all the settings are correct, the database is created at the start of the project, there is no error in debug but at login message pops up in the log:</p> <pre><code>(UserAuthentication.java:authenticate:56) tradeManager.DAO.Impl.CustomHibernateDaoSupport.find(CustomHibernateDaoSupport.java:60) tradeManager.service.authentication.UserAuthentication.authenticate(UserAuthentication.java:45) ... Authentication request failed: org.springframework.security.authentication.BadCredentialsException: User does not exists! </code></pre> <p>I added few catches to get precise exception and got new NullPointerException</p> <pre><code>17:52:34.280:WARN::/tradeManager/j_spring_security_check java.lang.NullPointerException at tradeManager.DAO.Impl.CustomHibernateDaoSupport.find(CustomHibernateDaoSupport.java:60) at tradeManager.service.authentication.UserAuthentication.authenticate(UserAuthentication.java:48) </code></pre> <p>Can someone explain me what i'm doing wrong? Please help me.</p> <p>here's the code affected by the query:</p> <pre><code>@Service("userAuthentication") public class UserAuthentication implements AuthenticationManager { protected static Logger userAccessLogger = Logger.getLogger("userAccessLog"); private UserDAO userDAO = new UserDAOImpl(); private Md5PasswordEncoder passwordEncoder = new Md5PasswordEncoder(); public Authentication authenticate(Authentication auth) throws UsernameNotFoundException { User user = null; /* * Init a database user object */ try { // Retrieve user details from database //user = userDAO.find(auth.getName()); List&lt;User&gt; list = userDAO.findAllByParam("username", auth.getName()); user = (list.isEmpty()) ? null : list.get(0); } catch (Exception e) { StackTraceElement[] stack = e.getStackTrace(); String exception = ""; for (StackTraceElement s : stack) { exception = exception + s.toString() + "\n\t\t"; } userAccessLogger.error(exception); throw new BadCredentialsException("\n\tUser " + auth.getName() + " does not exists!\n"); } /* * Compare passwords * Make sure to encode the password first before comparing */ if (user != null) { if (passwordEncoder.isPasswordValid(user.getPassword(), (String) auth.getCredentials(), null)) { throw new BadCredentialsException("\n\tWrong password!\n"); } } /* * main logic of authentication manager * Username and password must be the same to authenticate */ if (auth.getName().equals(auth.getCredentials())) { throw new BadCredentialsException("Entered username and password are the same!"); } else { assert user != null; return new UsernamePasswordAuthenticationToken( auth.getName(), auth.getCredentials(), getAuthorities(user.getAccess())); } } /* * Retrieves the correct ROLE type depending on the access level */ public Collection&lt;GrantedAuthority&gt; getAuthorities(Integer access) { // Create a list of grants for this user List&lt;GrantedAuthority&gt; authList = new ArrayList&lt;GrantedAuthority&gt;(2); userAccessLogger.debug("Grant ROLE_USER to this user"); authList.add(new SimpleGrantedAuthority("ROLE_USER")); if (access.compareTo(1) == 0) { authList.add(new SimpleGrantedAuthority("ROLE_ADMIN")); userAccessLogger.debug("Grant ROLE_ADMIN to this user"); } // Return list of granted authorities return authList; } </code></pre> <p>here is CustomHibernateDaoSupport:</p> <pre><code>public class CustomHibernateDaoSupport&lt;T&gt; implements DAO&lt;T&gt; { protected static Logger daoSupportLogger = Logger.getLogger("daoSupportLog"); private Class&lt;T&gt; clazz; private SessionFactory sessionFactory; public CustomHibernateDaoSupport(Class&lt;T&gt; clazz) { this.clazz = clazz; } @Autowired public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } private SessionFactory getSessionFactory() { return sessionFactory; } @Override @Transactional public void save(T entity) { getSessionFactory().getCurrentSession().save(entity); } @Override @Transactional public void update(T entity) { getSessionFactory().getCurrentSession().update(entity); } @Override @Transactional public void delete(Serializable key) { Object entity = getSessionFactory().getCurrentSession().get(clazz, key); if (entity != null) { getSessionFactory().getCurrentSession().delete(entity); } } @Override @Transactional public T find(Serializable key) { return (T) getSessionFactory().getCurrentSession().get(clazz, key); } @Override @Transactional public List&lt;T&gt; findAll() { return getSessionFactory().getCurrentSession().createCriteria(clazz).list(); } @Override @Transactional public List&lt;T&gt; findAllByParam(final String paramName, final Object paramValue) { return getSessionFactory().getCurrentSession().createCriteria(clazz) .add(Restrictions.eq(paramName, paramValue)) .list(); } } </code></pre> <p>the security settings are like this:</p> <pre><code>&lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:security="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd"&gt; &lt;!-- excluded from Security &lt;security:http pattern="/resources/*" security="none" /&gt;--&gt; &lt;!-- Configuration of Spring-Security. Set to false to assign custom filters --&gt; &lt;security:http auto-config="false" use-expressions="true" access-denied-page="/crimea/auth/denied" entry-point-ref="authenticationEntryPoint" &gt; &lt;security:logout invalidate-session="true" logout-success-url="/crimea/auth/login" delete-cookies="SPRING_SECURITY_REMEMBER_ME_COOKIE" logout-url="/crimea/auth/logout"/&gt; &lt;security:intercept-url pattern="/crimea/auth/login" access="permitAll"/&gt; &lt;security:intercept-url pattern="/crimea/main/admin" access="hasRole('ROLE_ADMIN')"/&gt; &lt;security:intercept-url pattern="/crimea/main/common" access="hasRole('ROLE_ADMIN','ROLE_USER')"/&gt; &lt;security:custom-filter ref="authenticationFilter" position="FORM_LOGIN_FILTER"/&gt; &lt;/security:http&gt; &lt;!-- Custom filter for username and password --&gt; &lt;bean id="authenticationFilter" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter" p:authenticationManager-ref="userAuthentication" p:authenticationFailureHandler-ref="customAuthenticationFailureHandler" p:authenticationSuccessHandler-ref="customAuthenticationSuccessHandler" p:postOnly="false" /&gt; &lt;!-- Custom authentication manager. !!! Username and password must not be the same !!! --&gt; &lt;bean id="userAuthentication" class="tradeManager.service.authentication.UserAuthentication" /&gt; &lt;!-- default failure URL --&gt; &lt;bean id="customAuthenticationFailureHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler" p:defaultFailureUrl="/crimea/auth/login?error=true" /&gt; &lt;!-- default target URL --&gt; &lt;bean id="customAuthenticationSuccessHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler" p:defaultTargetUrl="/crimea/main/common" /&gt; &lt;!-- The AuthenticationEntryPoint --&gt; &lt;bean id="authenticationEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint" p:loginFormUrl="/crimea/auth/login" /&gt; &lt;!-- Spring Security autowire the parent property --&gt; &lt;security:authentication-manager/&gt; &lt;/beans&gt; </code></pre> <p>I'm not showing User model becouse it standart. Acess is managed by Integer var:</p> <pre><code> /** * Access level. * 1 = Admin role * 2 = Regular role */ @Column(name = "Access", nullable = false) private Integer access; </code></pre> <p>Ок, didn't get any helpful answer, so tried my best. First of all, this line got my attention:</p> <pre><code>&lt;security:intercept-url pattern="/crimea/main/common" access="hasRole('ROLE_ADMIN','ROLE_USER')" </code></pre> <p>I changed it to:</p> <pre><code>&lt;security:intercept-url pattern="/crimea/main/common" access="hasRole('ROLE_USER')" </code></pre> <p>OK, I did more and changed query to username and I writed direct access, from:</p> <pre><code>list = userDAO.findAllByParam("from username",auth.getName()); </code></pre> <p>to:</p> <pre><code>list = getSessionFactory().getCurrentSession().createCriteria(User.class) .add(Restrictions.eq("username", auth.getName())).list(); </code></pre> <p>and added the authentication session attributes to the class and start working He = (( So, can anyone explain to me why my CustomHibernateDaoSupport class does not work??</p> <p>OK. I solved my problem ))</p> <p>First of all? I changed location of @Repository("employeeDAOImpl")annotation. I changed SQL driver to com.jolbox.bonecp.BoneCPDataSource naw my datasourse config loks likr this:</p> <pre><code>&lt;!-- for database, imports the properties from database.properties --&gt; &lt;bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close"&gt; &lt;property name="driverClass" value="${jdbc.driverClassName}"/&gt; &lt;property name="jdbcUrl" value="${jdbc.url}"/&gt; &lt;property name="username" value="${jdbc.username}"/&gt; &lt;property name="password" value="${jdbc.password}"/&gt; &lt;property name="idleConnectionTestPeriod" value="60"/&gt; &lt;property name="idleMaxAge" value="240"/&gt; &lt;property name="maxConnectionsPerPartition" value="30"/&gt; &lt;property name="minConnectionsPerPartition" value="10"/&gt; &lt;property name="partitionCount" value="3"/&gt; &lt;property name="acquireIncrement" value="5"/&gt; &lt;property name="statementsCacheSize" value="100"/&gt; &lt;property name="releaseHelperThreads" value="3"/&gt; &lt;/bean&gt; </code></pre> <p>changed Spring shema to:</p> <pre><code>&lt;tx:annotation-driven transaction-manager="transactionManager"/&gt; &lt;mvc:annotation-driven /&gt; </code></pre> <p>in UserAuthentication class I added chek for NullPointer</p> <pre><code> if (entity == null) { throw new BadCredentialsException("User does not exists!"); } </code></pre> <p>added to pom.xml maven dep. for new sql driver:</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;com.jolbox&lt;/groupId&gt; &lt;artifactId&gt;bonecp&lt;/artifactId&gt; &lt;version&gt;0.8.0-rc1&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p>So My Authentication is working perfect naw =))</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload