23 Mayıs 2018 Çarşamba

SpringSecurity UserDetails Arayüzü - Bir Kullanıcıyı Temsil Eder

Giriş
Şu satırı dahil ederiz.
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
İskeleti şöyle
public interface UserDetails extends Serializable {
  Collection<? extends GrantedAuthority> getAuthorities();

  String getPassword();

  String getUsername();

  boolean isAccountNonExpired();

  boolean isAccountNonLocked();

  boolean isCredentialsNonExpired();

  boolean isEnabled();
}
Açıklaması şöyle. Aslında Principal nesnesini temsil eder.
First we will talk about a user. This is a username and password as well as some type of authorization information. In Spring Security we have an interface called a UserDetails to store that information. A UserDetails implementation will store a String for the username as well as a String for the password, and it will have a collection of objects called GrantedAuthority. A GrantedAuthority object is just a holder class to hold a String for each role that the UserDetails/user has. So if I have a user Bob who has ROLE_ADMIN and ROLE_USER assigned to them in a database, then Bob’s UserDetails instance will have two GrantedAuthority instances in its collection. There are a couple of other boolean properties that also need to be set with the UserDetails interface, one of these for instance is used to say whether the user is still active or enabled.
Bu arayüzü yaratmak için User sınıfı kullanılabilir.
constructor
Şöyle yaparız.
UserDetails springU = org.springframework.security.core.userdetails.User
  .withUsername(...)
  .password(...)
  .authorities("USER", "write")
  .build();
getAuthorities metodu
Şöyle yaparız.
public class MyUserPrincipal implements UserDetails {
  private final User user;
  @Override
  public Collection<? extends GrantedAuthority> getAuthorities() {
    return user.getRoles();
  }
  public Long getUserId() {
    return user.getId();
  }

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

  @Override
  public String getUsername() {
    return user.getLogin();
  }

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

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

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

  @Override
  public boolean isEnabled() {
    return user.getEnabled();
  }
}
getPassword metodu
Örnek ver

getUsername metodu
Örnek ver



Hiç yorum yok:

Yorum Gönder