2013-09-24 1 views
1

데이터베이스에서 보안 로그인을 생성하려고하는데 내 코드가 데이터베이스에서 올바른 사용자 이름과 암호를 가져 오지만 인증하지 않습니다. 이 내 코드스프링 보안 UserDetailsService 구현 및 보안 userdetails.User 인증되지 않음

@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!!!"); 
      } 

     } 

스프링 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 방법

@Override 공공 사용자 findUserByName (문자열 이름) {

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

}

사람이에 도움을 주시기 바랍니다 수 있을까?

+0

. 누구든지 그 plz에 대한 이유를 알고 있습니까? 내가 암호화 된 암호를 사용하기 전에 봄 3.2 최대 절전 모드 4 –

+0

을 사용하고 있는데 BadCredentialsException 또는 다른 문제가 발생 했습니까? – coder

답변

1

대체 인증 시도, 직접 Th 인증 공급자 사용 내가 <암호 인코더 해시 = "MD5">를 추가하고 MD5 그것이 잘 작동 암호화로 비밀 번호를 저장 한 후

<!-- 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); } } 
관련 문제