Spring Security:org.springframework.security.core.userdetails.User无法强制转换为Person

时间:2014-10-27 10:48:22

标签: spring-mvc spring-security

我正在开发一个使用Spring-Security的Spring-MVC应用程序。在那里我需要获取当前经过身份验证的用户的对象,以便我可以使用setUser()方法。在下面提到的代码中,有一个名为getCurrentlyAuthenticatedUser()的方法,并且我在getPrincipal中有错误,因为它无法从springframework.security.core.userDetails.User转换为Person(我的类,其中包含所有人员详细信息)。我在互联网上检查了各种解决方案,但它们都没有工作/适合我已经完成的实施。我的身份验证实现与下面博客中提到的一致。我已经粘贴了所有可能有用的课程。

博客:

http://krams915.blogspot.de/2012/01/spring-security-31-implement_3065.html

人类:

@Entity
@Table(name="person")
public class Person implements UserDetails{

    private static final GrantedAuthority USER_AUTH = new SimpleGrantedAuthority("ROLE_USER");

    @Id
    @Column(name="id")
    @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "person_seq_gen")
    @SequenceGenerator(name = "person_seq_gen",sequenceName = "person_seq")
    private int id;


    @Column(name = "username")
    private String username;


    @Column(name = "password")
    private String password;

 @Transient
    private final String PERMISSION_PREFIX = "ROLE_USER";
    @Transient
    private List<GrantedAuthority> authorities;

    @Transient
    private String role;

@OneToMany(cascade = CascadeType.ALL,mappedBy = "person1")
  private Set<Notes> notes1;

    public Set<Notes> getNotes1() {
        return notes1;
    }

    public void setNotes1(Set<Notes> notes1) {
        this.notes1 = notes1;
    }
}

LoginServiceImpl:

@Transactional
@Service("userDetailsService")
public class LoginServiceImpl implements UserDetailsService{

    @Autowired private PersonDAO personDAO;
    @Autowired private Assembler assembler;

    private static final GrantedAuthority USER_AUTH = new SimpleGrantedAuthority("ROLE_USER");

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException,DataAccessException {
        Person person = personDAO.findPersonByUsername(username);

        return assembler.buildUserFromUserEntity(person);
    }
}

汇编程序类:

@服务( “汇编”)

public class Assembler {
    @Transactional(readOnly = true)
    User buildUserFromUserEntity(Person userEntity){
        String username = userEntity.getUsername();
        String password = userEntity.getPassword();

        // Long id = userEntity.getId();
        boolean enabled = userEntity.isActive();
        boolean accountNonExpired = userEntity.isAccountNonExpired();
        boolean credentialsNonExpired = userEntity.isCredentialsNonExpired();
        boolean accountNonLocked = userEntity.isAccountNonLocked();

        Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));

        User user = new User(username,password,enabled,accountNonExpired,credentialsNonExpired,accountNonLocked,authorities);
        return  user;
        }
}

//我在getPrincipal的下面的方法中遇到错误 PersonServiceImpl:

@Service
public class PersonServiceImpl implements PersonService {

    private PersonDAO personDAO;
 @Override
    public Person getCurrentlyAuthenticatedUser() throws Exception{
       Authentication a = SecurityContextHolder.getContext().getAuthentication();

 if(a == null) {
     System.out.println("Authentication Failure");
     return null;
 }else {
     System.out.println("Authentication is not null");  
     Person currentUser = (Person) a.getPrincipal();  // throws nullpointer exception here
     if(currentUser == null){
         System.out.println("Getauthenticcated User didnt find user");
         return null;
     }else {
         System.out.println("We have currently authenticated user");
         return currentUser;
     }
    }

Spring Security-xml

    <import resource="servlet-context.xml" />

    <!-- Global Security settings -->
    <security:global-method-security pre-post-annotations="enabled" />

    <security:http pattern="/" security="none" />

    <security:http create-session="ifRequired" use-expressions="true" auto-config="false" disable-url-rewriting="true">
         <security:port-mappings>
        <security:port-mapping http="80" https="443"/>

    </security:port-mappings>
           <security:session-management session-fixation-protection="migrateSession" invalid-session-url="/invalidSession.html">
            <security:concurrency-control max-sessions="3" error-if-maximum-exceeded="true" expired-url="/sessionExpired.html"/>
        </security:session-management>
           <security:form-login login-page="/login" default-target-url="/note/add" always-use-default-target="true" authentication-failure-url="/login?error"/>

    <security:authentication-manager alias="authenticationManager">
        <security:authentication-provider user-service-ref="LoginServiceImpl" />

    </security:authentication-manager>

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


</beans>

0 个答案:

没有答案