2016-06-03 3 views
0

Wenn ich mich mit Sicherheit angemeldet habe, kann ich die Methode request.isUserInRole() nicht verwenden. Ich denke, die Rollen der Benutzer wurden nicht festgelegt.Spring Security/Spring Boot - So stellen Sie ROLES für Benutzer ein

Das ist meine Sicherheitskonfiguration:

@Configuration 
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled=true) 
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 

@Autowired 
private DataSource dataSource; 

@Autowired 
private UserDetailsServiceImplementation userDetailsService; 

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http 
      .authorizeRequests() 
      .antMatchers("/signup").permitAll() 
      .antMatchers("/").permitAll() 
      //.antMatchers("/first").hasAuthority("Service_Center") 
      .antMatchers("/login").permitAll() 
      .anyRequest().fullyAuthenticated() 
    .and().formLogin() 
      .loginPage("/login") 
      .usernameParameter("email") 
      .passwordParameter("password") 
      .defaultSuccessUrl("/default") 
      .failureUrl("/login?error").permitAll() 
    .and().logout() 
      .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) 
      .logoutSuccessUrl("/login?logout") 
      .deleteCookies("JSESSIONID") 
      .invalidateHttpSession(true).permitAll(); 
} 

@Autowired 
public void configAuthentication(AuthenticationManagerBuilder auth) 
     throws Exception { 
    auth.userDetailsService(userDetailsService); 

} 

} 

Das ist mein User Einheit:

@Entity 
@Table(name="user") 
public class User implements Serializable{ 
/** 
* 
*/ 
private static final long serialVersionUID = 1L; 

@Id 
@GeneratedValue(strategy = GenerationType.AUTO) 
@Column(name="user_id") 
private Long userID; 

@Column(name="email_address", nullable = false, unique = true) 
private String emailAddress; 

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

@Column(name = "role", nullable = false) 
@Enumerated(EnumType.STRING) 
private Role role; 

public User() { 
    super(); 
} 

public User(String emailAddress, String password) { 
    this.emailAddress = emailAddress; 
    this.password = password; 
} 

public Long getUserID() { 
    return userID; 
} 

public void setUserID(Long userID) { 
    this.userID = userID; 
} 

public String getEmailAddress() { 
    return emailAddress; 
} 

public void setEmailAddress(String emailAddress) { 
    this.emailAddress = emailAddress; 
} 

public String getPassword() { 
    return password; 
} 

public void setPassword(String password) { 
    this.password = password; 
} 

public Role getRole() { 
    return role; 
} 

public void setRole(Role role) { 
    this.role = role; 
} 

@Override 
public String toString() { 
    return "User [userID=" + userID + ", emailAddress=" + emailAddress 
      + ", password=" + password + ", role=" + role + "]"; 
} 

public UserDetails toCurrentUserDetails() { 
    return CurrentUserDetails.create(this); 
} 
} 

Das ist mein Enum ist Role:

public enum Role { 

Fleet_Company, Service_Center, Admin 

} 

Das ist mein UserDetailsServiceImplementation:

@Component 
public class UserDetailsServiceImplementation implements UserDetailsService { 

@Autowired 
private UserRepository userRepository; 

@Override 
public UserDetails loadUserByUsername(String username) 
     throws UsernameNotFoundException { 
    if (username == null || username.isEmpty()){ 
     throw new UsernameNotFoundException("username is empty"); 
    } 

    User foundUser = userRepository.findByEmailAddress(username); 
    if(foundUser != null){ 
     System.out.println("FOUND"); 
     return foundUser.toCurrentUserDetails(); 

    } 
    throw new UsernameNotFoundException(username + "is not found"); 
} 
} 

Dies ist die Klasse, die UserDetails implementiert:

public class CurrentUserDetails implements UserDetails { 
private Long userID; 
private String emailAddress; 
private String password; 
private Role role; 


public CurrentUserDetails(Long userID, String emailAddress, String password, Role role) { 
    super(); 
    this.userID = userID; 
    this.emailAddress = emailAddress; 
    this.password = password; 
    this.role = role; 
} 


    /* public static UserDetails create(Users entity) { 
    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); 
    for(Authorities auth: entity.getAuthorities()){ 
     authorities.add(new SimpleGrantedAuthority(auth.getId().getAuthority())); 
    } 
    return new MyUserDetail(entity.getUserId(), entity.getLoginId(), entity.getPassword(), entity.getDisplayName(), authorities); 
}*/ 



public Long getUserID(){ 
    return this.userID; 
} 


public Role getRole(){ 
    return this.role; 
} 




@Override 
public String getPassword() { 
    return this.password; 
} 


public String getEmailAddress() { 
    return this.emailAddress; 
} 


@Override 
public boolean isAccountNonExpired() { 
    return true; 
} 

@Override 
public boolean isAccountNonLocked() { 
    return true; 
} 


@Override 
public boolean isCredentialsNonExpired() { 
    return true; 
} 


@Override 
public boolean isEnabled() { 
    return true; 
} 

public static UserDetails create(User entity) { 
    System.out.println(entity.getUserID()+ entity.getEmailAddress()+ entity.getPassword()+ entity.getRole()); 
    return new CurrentUserDetails(entity.getUserID(), entity.getEmailAddress(), entity.getPassword(), entity.getRole()); 
} 

@Override 
public Collection<? extends GrantedAuthority> getAuthorities() { 
    // TODO Auto-generated method stub 
    return null; 
} 

@Override 
public String getUsername() { 
    // TODO Auto-generated method stub 
    return null; 
} 
} 

Also im Grunde können wir sehen, dass ich eine Tabelle nur auf meine MySQL-Datenbank haben, hat es vier Spalten und einer von ihnen ist ‚Rolle‘ . Wenn ich request.isUserInRole("Service_Center") verwende, gibt es FALSE zurück. Und .antMatchers("/first").hasAuthority("Service_Center") funktioniert auch nicht.

+0

Was ist die 'UserDetailsServiceImplementation'? Ich glaube, das ist der Ort, der Ihre Entität mit dem Antragsprinzip verbinden sollte. – zapl

+0

@zapl Ich habe meinen Beitrag bearbeitet, um diese Klasse einzuschließen, – Lester

+0

Ok, das Verfolgen des Problems führt zu 'CurrentUserDetails.create (this)'. Was macht das? – zapl

Antwort

2

Sie sollten sich in dem Inhalt der Rolle ausfüllen, wenn Ihre Userdetails zu erstellen:

public class SecurityUser implements UserDetails{ 
    String ROLE_PREFIX = "ROLE_"; 

    String userName; 
    String password; 
    String role; 

    public SecurityUser(String username, String password, String role){ 
     this.userName = username; 
     this.password = password; 
     this.role = role; 
    } 

    @Override 
    public Collection<? extends GrantedAuthority> getAuthorities() { 
     List<GrantedAuthority> list = new ArrayList<GrantedAuthority>(); 

     list.add(new SimpleGrantedAuthority(ROLE_PREFIX + role)); 

     return list; 
    } 

Im Grunde, was Sie tun müssen, ist überschreiben Methode: getAuthorities, und in dem Inhalt Ihrer Rolle Feld in denen füllen GrantedAuthority Liste.

+0

neue Rolle bei getAuthorities-Methode hinzufügen? Sieht nicht so aus, als wäre es eine gute Idee ... Sie sollten 'SecurityContextHolder' verwenden und dies in einem separaten Dienst tun. – thorinkor

Verwandte Themen