@Data @AllArgsConstructor @NoArgsConstructor @Entity public class Member { @Id String mid; //メンバーID String name; //名前 String password; //パスワード(暗号化済) String role; //ロール }
@Data public class MemberForm { @Pattern(regexp ="[a-z0-9_\\-]{4,16}") String mid; //メンバーID.英小文字,数字,ハイフン,アンダーバー.4文字以上16文字以下. @NotBlank @Size(min = 1, max = 32) String name; //名前.最大32文字 @NotBlank @Size(min = 8) String password; //パスワード String role = "MEMBER"; //ロール.デフォルトは"MEMBER" public Member toEntity() { Member m = new Member(mid, name, password, role); return m; } }
解説
package jp.ac.kobe_u.cs.itspecialist.todoapp.dto; import java.util.ArrayList; import java.util.Collection; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import jp.ac.kobe_u.cs.itspecialist.todoapp.entity.Member; /** * 認証に必要なUserDetailsの実装クラス.Memberをラップする */ public class UserDetailsImpl implements UserDetails { Member member; Collection<GrantedAuthority> authorities = new ArrayList<>(); /** * コンストラクタ * @param member */ public UserDetailsImpl(Member member) { this.member=member; //メンバーのロールから権限を生成して追加 this.authorities.add(new SimpleGrantedAuthority("ROLE_" + member.getRole())); } public Member getMember() { return member; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities; } @Override public String getPassword() { return member.getPassword(); } @Override public String getUsername() { return member.getMid(); } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } }