spring Security UserDetailsS​​ervice实现和安全性userdetails.User不进行身份验证

时间:2013-09-24 12:45:36

标签: spring-mvc spring-security

我正在尝试从数据库创建并弹出安全登录,我的代码从数据库中获取正确的用户名和密码,但它没有进行身份验证? 这是我的代码

@Transactional(readOnly = true)
   public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

            User user = userdao.findUserByName(username);


            if(user!=null){
                String password = user.getPassword();
                boolean enabled = true;
                boolean accountNonExpired = true;
                boolean credentialsNonExpired = true;
                boolean accountNonLocked = true;

                Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
                Role role = user.getUserrole();

                authorities.add(new GrantedAuthorityImpl("ROLE_USER"));
                //getting correct user name and password from the db
                System.out.print("User name" + user.getUsername() + "Password :" + password);

                org.springframework.security.core.userdetails.User securityUser = new 
                        org.springframework.security.core.userdetails.User(username,password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);


    //          String u = securityUser.getUsername();
    //          System.out.println("User name" + u);

                return securityUser;

            }else{
                throw new UsernameNotFoundException("User Not Found!!!");
            }

        }

spring-security.xml

<http use-expressions="true">
        <intercept-url pattern="/login" access="permitAll"/>
        <intercept-url pattern="/elearn/**" access="hasRole('ROLE_USER')" /> <!-- this means all URL in this app will be checked if user is authenticated -->
        <form-login login-page="/login" authentication-failure-url="/login"/>
        <logout logout-url="/logout" logout-success-url="/home"/> <!-- the logout url we will use in JSP -->
    </http>

    <beans:bean id="daoAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
        <beans:property name="userDetailsService" ref="userDetailsService" ></beans:property>
    </beans:bean>

    <beans:bean id="authenticationManager" class="org.springframework.security.authentication.ProviderManager">
        <beans:property name="providers">
            <beans:list>
                <beans:ref local="daoAuthenticationProvider"/>
            </beans:list>
        </beans:property>
    </beans:bean>

     <authentication-manager>
        <authentication-provider user-service-ref="userDetailsService">
    <!--         <user-service>
                <user name="admin" password="admin" authorities="ROLE_USER, ROLE_ADMIN" />
            </user-service> -->

        </authentication-provider>
    </authentication-manager>

用户类

@Entity
@Table(name="user")
public class User{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer userid;

    private String username;
    private String password;

    @OneToOne
    private Role userrole;

    public User(){

    }

    public Role getUserrole() {
        return userrole;
    }

    public void setUserrole(Role userrole) {
        this.userrole = userrole;
    }

    public Integer getUserid() {
        return userid;
    }

    public void setUserid(Integer userid) {
        this.userid = userid;
    }

    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;
    }
}

dao方法

@覆盖 public User findUserByName(String username){

User user = (User) sessionFactory.getCurrentSession().
        createCriteria(User.class).add(Restrictions.eq("username",username)).uniqueResult();
return user;

}

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

尝试替代方案,直接使用Th身份验证提供程序!!!

<!-- HTTP security configurations -->

<security:http auto-config="true" use-expressions="true">
    <security:form-login login-processing-url="/j_spring_security_check"
        login-page="/login" authentication-failure-url="/login?login_error=t"
        default-target-url="/index" always-use-default-target="false" />
    <security:logout logout-url="/j_spring_security_logout" />
    <!-- <security:intercept-url pattern="/login" requires-channel="https" 
        /> -->
    <security:intercept-url pattern="/login**"
        access="permitAll" />
    <security:intercept-url pattern="/resources/**"
        access="permitAll" />
    <security:intercept-url pattern="/"
        access="isAuthenticated()" />
    <security:intercept-url pattern="/**"
        access="isAuthenticated()" />
</security:http>


<!-- Configure Authentication mechanism -->

<bean class="com.ansell.crms.security.spring.RestAuthenticationProvider"
    id="restAuthenticationProvider" />

<security:authentication-manager alias="authenticationManager">
    <security:authentication-provider
        ref="restAuthenticationProvider" />
</security:authentication-manager>

其他身份验证提供程序,

/**  * http://www.baeldung.com/spring-security-authentication-provider
*   * @author Rakesh.Waghela  *   */

public class RestAuthenticationProvider implements AuthenticationProvider {

    private static final Logger LOGGER = LoggerFactory          .getLogger(RestAuthenticationProvider.class);


    public RestAuthenticationProvider() {       super();    }

    @Override   public Authentication authenticate(Authentication authentication)           throws AuthenticationException {

        String userName = authentication.getName();         String userPass = authentication.getCredentials().toString();

        // Credentials should not be null or blank      if( userName == null || userPass == null || userName.length() < 1 || userPass.length() < 1 )        {           throw new BadCredentialsException("Credential Missing !");      }



        try {
                //validate the user id & password here !

        }       
        throw new BadCredentialsException("When You Have Invalid Login !"); 

        // Fetch Roles And Generate Authorities         List<String> roles = userToken.getRoles();      // Add all the functions as well        roles.addAll(userToken.getFunctions());
                List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();         for (String role : roles) {             authorities.add(new SimpleGrantedAuthority(role));      }

        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                userToken.getUserId(), userToken.getTokenId(), authorities);


        return usernamePasswordAuthenticationToken;     }

    @Override   public boolean supports(Class<?> authentication) {      return authentication.equals(UsernamePasswordAuthenticationToken.class);    } }