Spring Securityを使用する
pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity4</artifactId> </dependency>
ユーザ取得処理の実装
ReservationUserDetails.java
package mrs.domain.service.user; import java.util.Collection; import mrs.domain.model.User; import org.springframework.security.core.GrantedAuthority; import org.springframework.secuirty.core.authority.AuthorityUtils; import org.springframework.secuirty.core.userdetails.UserDetails; public class ReservationUserDetails implements UserDetails { private final User user; public ReservationUserDetails(User user) { this.user = user; } public User getUser() { return user; } @Override public Collection<? extends GrantedAuthority> getAuthorities(){ return AuthorityUtils.createAuthorityList("ROLE_" + this.user.getRoleName().name()); } @Override public String getPassword() { return this.user.getPassword(); } @Override public String getUsername() { return this.user.getUserId(); } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsExpired() { return true; } @Override public boolean isEnabled() { return true; } }
ん、認証って、一つ一つ書くんか。
UserRepository.java
package mrs.domain.repository.user; import org.springframework.data.jpa.repository.JpaRepository; import mrs.domain.model.User; public interface UserRepository extends JpaRepository<User, String>{ }
ReservationUserDetailsService.java
package mrs.domain.service.user; import mrs.domain.model.User; import mrs.domain.repository.user.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; @Service public class ReservationUserDetailsService implements UserDetailsService { @Autowired UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findOne(username); if(user == null) { throw new UsernameNotFoundException(username + " is not found."); } return new ReservationUserDetails(user); } }
LoginController.java
package mrs.app.login; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class LoginController { @RequestMapping("loginForm") String loginForm() { return "login/loginForm"; } }
プロジェクトルートで ./mvnw package で.jarファイルを作成する
うむ、何がわかってないかがわかってない状態だ。