Last active
December 7, 2020 14:49
-
-
Save privatejk2002/e0a5f8e35827aaa084561fa5a3c28217 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> | |
<html> | |
<head> | |
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> | |
<title>Insert title here</title> | |
<script> | |
function formSubmit(path){ | |
let form = document.getElementsByTagName('form')[0]; | |
form.action=path; | |
form.method="post"; | |
form.submit(); | |
} | |
</script> | |
</head> | |
<body> | |
<div th:if="${param.error}"> | |
ログインIDまたはパスワードが無効です。 | |
</div> | |
<form th:action="@{/sign_in}" method="post"> | |
<input type="text" name="username">ログインID | |
<br/> | |
<input type="password" name="password">パスワード | |
<br/> | |
<input type="submit" value="ログイン"> | |
<input type="button" value="アカウント新規登録" onclick="formSubmit('/regist');"> | |
</form> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package login.app.entity; | |
import javax.persistence.Column; | |
import javax.persistence.Entity; | |
import javax.persistence.Id; | |
import javax.persistence.Table; | |
@Entity | |
@Table(name = "user") | |
public class LoginUser { | |
@Column(name = "user_id") | |
@Id | |
private Long userId; | |
@Column(name = "username") | |
private String userName; | |
@Column(name = "password") | |
private String password; | |
public String getUserName() { | |
return userName; | |
} | |
public void setUserName(String userName) { | |
this.userName = userName; | |
} | |
public String getPassword() { | |
return password; | |
} | |
public void setPassword(String password) { | |
this.password = password; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package login.app.dao; | |
import javax.persistence.EntityManager; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.stereotype.Repository; | |
import login.app.entity.LoginUser; | |
@Repository | |
public class LoginUserDao { | |
@Autowired | |
EntityManager em; | |
/** | |
* ユーザからログイン情報を取得する | |
* @param userName | |
* @return 一致するユーザが存在するとき:UserEntity、存在しないとき:Null | |
*/ | |
public LoginUser findUser(String userName) { | |
String query = ""; | |
query += "SELECT * "; | |
query += "FROM user "; | |
query += "WHERE username = :userName "; | |
return (LoginUser)em.createNativeQuery(query, LoginUser.class).setParameter("userName", userName) | |
.getSingleResult(); | |
} | |
/** | |
* ログイン情報を登録する | |
* | |
* @param userName | |
* @param password | |
*/ | |
public void insertUser(String userName,String password) { | |
LoginUser loginUser = new LoginUser(); | |
loginUser.setUserName(userName); | |
loginUser.setPassword(password); | |
em.persist(loginUser); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package login.app.config; | |
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; | |
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; | |
public class MvcConfig implements WebMvcConfigurer{ | |
public void addViewControllers(ViewControllerRegistry registry) { | |
registry.addViewController("/login").setViewName("login"); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> | |
<html> | |
<head> | |
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> | |
<title>Insert title here</title> | |
</head> | |
<body> | |
<form th:action="@{/regist}" method="post"> | |
<input type="text" name="username">ログインID | |
<br/> | |
<input type="password" name="password">パスワード | |
<br/> | |
<input type="submit" value="登録"> | |
</form> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package login.app.controller; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.stereotype.Controller; | |
import org.springframework.web.bind.annotation.ModelAttribute; | |
import org.springframework.web.bind.annotation.RequestMapping; | |
import login.app.service.UserRegistService; | |
@Controller | |
public class RegistController { | |
@Autowired | |
UserRegistService userRegistService; | |
@RequestMapping("/regist") | |
public String regist(@ModelAttribute("userName") String userName, @ModelAttribute("password") String password) { | |
userRegistService.regist(userName, password); | |
return "success"; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> | |
<html> | |
<head> | |
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> | |
<title>ログイン成功</title> | |
</head> | |
<body> | |
<p>ログイン成功</p> | |
<p th:text="${userName}"></p> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package login.app.controller; | |
import org.springframework.security.core.Authentication; | |
import org.springframework.security.core.context.SecurityContextHolder; | |
import org.springframework.stereotype.Controller; | |
import org.springframework.ui.Model; | |
import org.springframework.web.bind.annotation.RequestMapping; | |
@Controller | |
public class SuccessController { | |
@RequestMapping("/success") | |
private String init(Model model) { | |
Authentication auth = SecurityContextHolder.getContext().getAuthentication(); | |
//Principalからログインユーザの情報を取得 | |
String userName = auth.getName(); | |
model.addAttribute("userName", userName); | |
return "success"; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package login.app.service; | |
import java.util.ArrayList; | |
import java.util.List; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.security.core.GrantedAuthority; | |
import org.springframework.security.core.authority.SimpleGrantedAuthority; | |
import org.springframework.security.core.userdetails.User; | |
import org.springframework.security.core.userdetails.UserDetails; | |
import org.springframework.security.core.userdetails.UserDetailsService; | |
import org.springframework.security.core.userdetails.UsernameNotFoundException; | |
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; | |
import login.app.dao.LoginUserDao; | |
import login.app.entity.LoginUser; | |
public class UserDetailsServiceImpl implements UserDetailsService { | |
@Autowired | |
private LoginUserDao userDao; | |
@Override | |
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException { | |
LoginUser user = userDao.findUser(userName); | |
if (user == null) { | |
throw new UsernameNotFoundException("User" + userName + "was not found in the database"); | |
} | |
List<GrantedAuthority> grantList = new ArrayList<GrantedAuthority>(); | |
GrantedAuthority authority = new SimpleGrantedAuthority("USER"); | |
grantList.add(authority); | |
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); | |
UserDetails userDetails = (UserDetails)new User(user.getUserName(), encoder.encode(user.getPassword()),grantList); | |
return userDetails; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package login.app.service; | |
public interface UserRegistService { | |
public void regist(String userName,String password); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package login.app.service; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import login.app.dao.LoginUserDao; | |
public class UserRegistServiceImpl implements UserRegistService{ | |
@Autowired | |
private LoginUserDao userDao; | |
@Override | |
public void regist(String userName,String password) { | |
userDao.insertUser(userName, password); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package login.app.config; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.context.annotation.Bean; | |
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; | |
import org.springframework.security.config.annotation.web.builders.HttpSecurity; | |
import org.springframework.security.config.annotation.web.builders.WebSecurity; | |
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; | |
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; | |
import login.app.service.UserDetailsServiceImpl; | |
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { | |
@Autowired | |
private UserDetailsServiceImpl userDetailsService; | |
//フォームの値と比較するDBから取得したパスワードは暗号化されているのでフォームの値も暗号化するために利用 | |
@Bean | |
public BCryptPasswordEncoder passwordEncoder() { | |
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(); | |
return bCryptPasswordEncoder; | |
} | |
/** | |
* 認可設定を無視するリクエストを設定 | |
* 静的リソース(image,javascript,css)を認可処理の対象から除外する | |
*/ | |
@Override | |
public void configure(WebSecurity web) throws Exception { | |
web.ignoring().antMatchers( | |
"/images/**", | |
"/css/**", | |
"/javascript/**" | |
); | |
} | |
/** | |
* 認証・認可の情報を設定する | |
* 画面遷移のURL・パラメータを取得するname属性の値を設定 | |
*/ | |
@Override | |
protected void configure(HttpSecurity http) throws Exception { | |
http | |
.authorizeRequests() | |
.anyRequest().authenticated() | |
.and() | |
.formLogin() | |
.loginPage("/login") //ログインページはコントローラを経由しないのでViewNameとの紐付けが必要 | |
.loginProcessingUrl("/sign_in") //フォームのSubmitURL、このURLへリクエストが送られると認証処理が実行される | |
.usernameParameter("username") //リクエストパラメータのname属性を明示 | |
.passwordParameter("password") | |
.successForwardUrl("/success") | |
.failureUrl("/login?error") | |
.permitAll() | |
.and() | |
.logout() | |
.logoutUrl("/logout") | |
.logoutSuccessUrl("/login?logout") | |
.permitAll(); | |
} | |
/** | |
* 認証時に利用するデータソースを定義する設定メソッド | |
* ここではDBから取得したユーザ情報をuserDetailsServiceへセットすることで認証時の比較情報としている | |
* @param auth | |
* @throws Exception | |
*/ | |
@Autowired | |
public void configure(AuthenticationManagerBuilder auth) throws Exception{ | |
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); | |
/* | |
auth | |
.inMemoryAuthentication() | |
.withUser("user").password("{noop}password").roles("USER"); | |
*/ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment