Compare commits
4 Commits
72bd137e8d
...
fa606e3cbf
| Author | SHA1 | Date | |
|---|---|---|---|
| fa606e3cbf | |||
| dd8fc3151f | |||
| 2687c00f35 | |||
| 47947636a1 |
@@ -1,37 +1,37 @@
|
|||||||
package com.example.demo.config;
|
package com.example.demo.config;
|
||||||
|
|
||||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
|
||||||
// データベースに保存されている平文パスワードと、BCryptでハッシュ化されたパスワードの両方を照合できるようにするクラス
|
// データベースに保存されている平文パスワードと、BCryptでハッシュ化されたパスワードの両方を照合できるようにするクラス
|
||||||
public class CompatiblePasswordEncoder implements PasswordEncoder {
|
public class CompatiblePasswordEncoder implements PasswordEncoder {
|
||||||
|
|
||||||
// パスワードを安全にハッシュ化するためのクラスを生成
|
// パスワードを安全にハッシュ化するためのクラスを生成
|
||||||
private final BCryptPasswordEncoder bcrypt = new BCryptPasswordEncoder();
|
private final BCryptPasswordEncoder bcrypt = new BCryptPasswordEncoder();
|
||||||
|
|
||||||
// パスワードのハッシュ化
|
// パスワードのハッシュ化
|
||||||
@Override
|
@Override
|
||||||
public String encode(CharSequence rawPassword) {
|
public String encode(CharSequence rawPassword) {
|
||||||
return bcrypt.encode(rawPassword);
|
return bcrypt.encode(rawPassword);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean matches(
|
public boolean matches(
|
||||||
CharSequence rawPassword,
|
CharSequence rawPassword,
|
||||||
String encodedPassword) {
|
String encodedPassword) {
|
||||||
|
|
||||||
// 保存済みパスワードが存在するか確認
|
// 保存済みパスワードが存在するか確認
|
||||||
if (encodedPassword == null) {
|
if (encodedPassword == null) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 既存の平文パスワードに対応
|
// 既存の平文パスワードに対応
|
||||||
if (!encodedPassword.startsWith("$2a$")
|
if (!encodedPassword.startsWith("$2a$")
|
||||||
&& !encodedPassword.startsWith("$2b$")
|
&& !encodedPassword.startsWith("$2b$")
|
||||||
&& !encodedPassword.startsWith("$2y$")) {
|
&& !encodedPassword.startsWith("$2y$")) {
|
||||||
return rawPassword.toString().equals(encodedPassword);
|
return rawPassword.toString().equals(encodedPassword);
|
||||||
}
|
}
|
||||||
|
|
||||||
// BCrypt形式のパスワードに対応
|
// BCrypt形式のパスワードに対応
|
||||||
return bcrypt.matches(rawPassword, encodedPassword);
|
return bcrypt.matches(rawPassword, encodedPassword);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
package com.example.demo.config;
|
package com.example.demo.config;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
import jakarta.servlet.ServletException;
|
import jakarta.servlet.ServletException;
|
||||||
@@ -11,49 +11,49 @@ import org.springframework.security.web.authentication.SimpleUrlAuthenticationFa
|
|||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
import com.example.demo.service.LoginAttemptService;
|
import com.example.demo.service.LoginAttemptService;
|
||||||
|
|
||||||
// ログイン失敗時の処理
|
// ログイン失敗時の処理
|
||||||
@Component
|
@Component
|
||||||
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
|
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
|
||||||
|
|
||||||
private LoginAttemptService loginAttemptService;
|
private LoginAttemptService loginAttemptService;
|
||||||
|
|
||||||
public CustomAuthenticationFailureHandler(LoginAttemptService loginAttemptService) {
|
public CustomAuthenticationFailureHandler(LoginAttemptService loginAttemptService) {
|
||||||
this.loginAttemptService = loginAttemptService;
|
this.loginAttemptService = loginAttemptService;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
|
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
|
||||||
AuthenticationException exception) throws IOException, ServletException {
|
AuthenticationException exception) throws IOException, ServletException {
|
||||||
|
|
||||||
// 画面から入力されたメールアドレスを取得
|
// 画面から入力されたメールアドレスを取得
|
||||||
String mailAddress = request.getParameter("mailAddress");
|
String mailAddress = request.getParameter("mailAddress");
|
||||||
|
|
||||||
if (mailAddress != null && !mailAddress.isBlank()) {
|
if (mailAddress != null && !mailAddress.isBlank()) {
|
||||||
String mail = mailAddress.trim();
|
String mail = mailAddress.trim();
|
||||||
|
|
||||||
if (loginAttemptService.isBlocked(mail)) {
|
if (loginAttemptService.isBlocked(mail)) {
|
||||||
getRedirectStrategy().sendRedirect(
|
getRedirectStrategy().sendRedirect(
|
||||||
request, response, "/login?error=locked");
|
request, response, "/login?error=locked");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 失敗回数を1増やす
|
// 失敗回数を1増やす
|
||||||
loginAttemptService.loginFailed(mail);
|
loginAttemptService.loginFailed(mail);
|
||||||
|
|
||||||
// すでにロック中なら失敗回数を増やさない
|
// すでにロック中なら失敗回数を増やさない
|
||||||
if (loginAttemptService.isBlocked(mail)) {
|
if (loginAttemptService.isBlocked(mail)) {
|
||||||
getRedirectStrategy().sendRedirect(
|
getRedirectStrategy().sendRedirect(
|
||||||
request, response, "/login?error=locked");
|
request, response, "/login?error=locked");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// あと何回失敗されるとロックされるか取得
|
// あと何回失敗されるとロックされるか取得
|
||||||
int remaining = loginAttemptService.getRemainingAttempts(mail);
|
int remaining = loginAttemptService.getRemainingAttempts(mail);
|
||||||
|
|
||||||
getRedirectStrategy().sendRedirect(
|
getRedirectStrategy().sendRedirect(
|
||||||
request, response, "/login?error=failed&remaining=" + remaining);
|
request, response, "/login?error=failed&remaining=" + remaining);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
package com.example.demo.config;
|
package com.example.demo.config;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
import jakarta.servlet.ServletException;
|
import jakarta.servlet.ServletException;
|
||||||
@@ -12,37 +12,37 @@ import org.springframework.stereotype.Component;
|
|||||||
|
|
||||||
import com.example.demo.common.Const;
|
import com.example.demo.common.Const;
|
||||||
import com.example.demo.service.LoginAttemptService;
|
import com.example.demo.service.LoginAttemptService;
|
||||||
|
|
||||||
@Component
|
@Component
|
||||||
public class CustomAuthenticationSuccessHandler
|
public class CustomAuthenticationSuccessHandler
|
||||||
extends SimpleUrlAuthenticationSuccessHandler {
|
extends SimpleUrlAuthenticationSuccessHandler {
|
||||||
|
|
||||||
private final LoginAttemptService loginAttemptService;
|
private final LoginAttemptService loginAttemptService;
|
||||||
|
|
||||||
public CustomAuthenticationSuccessHandler(
|
public CustomAuthenticationSuccessHandler(
|
||||||
LoginAttemptService loginAttemptService) {
|
LoginAttemptService loginAttemptService) {
|
||||||
this.loginAttemptService = loginAttemptService;
|
this.loginAttemptService = loginAttemptService;
|
||||||
setDefaultTargetUrl("/menu");
|
setDefaultTargetUrl("/menu");
|
||||||
setAlwaysUseDefaultTargetUrl(true);
|
setAlwaysUseDefaultTargetUrl(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onAuthenticationSuccess(
|
public void onAuthenticationSuccess(
|
||||||
HttpServletRequest request,
|
HttpServletRequest request,
|
||||||
HttpServletResponse response,
|
HttpServletResponse response,
|
||||||
Authentication authentication)
|
Authentication authentication)
|
||||||
throws IOException, ServletException {
|
throws IOException, ServletException {
|
||||||
|
|
||||||
if (authentication.getPrincipal() instanceof CustomUserDetails userDetails) {
|
if (authentication.getPrincipal() instanceof CustomUserDetails userDetails) {
|
||||||
String mail = userDetails.getUsername();
|
String mail = userDetails.getUsername();
|
||||||
|
|
||||||
loginAttemptService.loginSucceeded(mail);
|
loginAttemptService.loginSucceeded(mail);
|
||||||
|
|
||||||
request.getSession(true).setAttribute(
|
request.getSession(true).setAttribute(
|
||||||
Const.SESSION_LOGIN_USER,
|
Const.SESSION_LOGIN_USER,
|
||||||
userDetails.getLoginUser());
|
userDetails.getLoginUser());
|
||||||
}
|
}
|
||||||
|
|
||||||
super.onAuthenticationSuccess(request, response, authentication);
|
super.onAuthenticationSuccess(request, response, authentication);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
package com.example.demo.config;
|
package com.example.demo.config;
|
||||||
|
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
|
|
||||||
@@ -9,36 +9,36 @@ import org.springframework.security.core.userdetails.UserDetails;
|
|||||||
|
|
||||||
import com.example.demo.common.LoginUser;
|
import com.example.demo.common.LoginUser;
|
||||||
import com.example.demo.service.LoginAttemptService;
|
import com.example.demo.service.LoginAttemptService;
|
||||||
|
|
||||||
// システムの社員情報をSpring Securityが扱えるクラスに変更
|
// システムの社員情報をSpring Securityが扱えるクラスに変更
|
||||||
public class CustomUserDetails implements UserDetails {
|
public class CustomUserDetails implements UserDetails {
|
||||||
|
|
||||||
private final LoginUser loginUser;
|
private final LoginUser loginUser;
|
||||||
private final String password; // DBから取得した暗号化パスワードを保持
|
private final String password; // DBから取得した暗号化パスワードを保持
|
||||||
private final LoginAttemptService loginAttemptService;
|
private final LoginAttemptService loginAttemptService;
|
||||||
|
|
||||||
public CustomUserDetails(LoginUser loginUser, String password, LoginAttemptService loginAttemptService) {
|
public CustomUserDetails(LoginUser loginUser, String password, LoginAttemptService loginAttemptService) {
|
||||||
this.loginUser = loginUser;
|
this.loginUser = loginUser;
|
||||||
this.password = password;
|
this.password = password;
|
||||||
this.loginAttemptService = loginAttemptService;
|
this.loginAttemptService = loginAttemptService;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getPassword() {
|
public String getPassword() {
|
||||||
return this.password;
|
return this.password;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getUsername() {
|
public String getUsername() {
|
||||||
return loginUser.getMailAddress();
|
return loginUser.getMailAddress();
|
||||||
}
|
}
|
||||||
|
|
||||||
// アカウントのロック状態の確認
|
// アカウントのロック状態の確認
|
||||||
@Override
|
@Override
|
||||||
public boolean isAccountNonLocked() {
|
public boolean isAccountNonLocked() {
|
||||||
return !loginAttemptService.isBlocked(getUsername());
|
return !loginAttemptService.isBlocked(getUsername());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// 管理者判定メソッド
|
// 管理者判定メソッド
|
||||||
@Override
|
@Override
|
||||||
@@ -46,29 +46,29 @@ public class CustomUserDetails implements UserDetails {
|
|||||||
String role = loginUser.isAdmin()
|
String role = loginUser.isAdmin()
|
||||||
? "ROLE_ADMIN"
|
? "ROLE_ADMIN"
|
||||||
: "ROLE_USER";
|
: "ROLE_USER";
|
||||||
|
|
||||||
return Collections.singletonList( // 要素が一つだけの変更できないリストを作るメソッド
|
return Collections.singletonList( // 要素が一つだけの変更できないリストを作るメソッド
|
||||||
new SimpleGrantedAuthority(role));
|
new SimpleGrantedAuthority(role));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean isAccountNonExpired() {
|
public boolean isAccountNonExpired() {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean isCredentialsNonExpired() {
|
public boolean isCredentialsNonExpired() {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean isEnabled() {
|
public boolean isEnabled() {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ログイン成功後にコントローラー等でLoginUserを取り出すためのゲッター
|
// ログイン成功後にコントローラー等でLoginUserを取り出すためのゲッター
|
||||||
public LoginUser getLoginUser() {
|
public LoginUser getLoginUser() {
|
||||||
return loginUser;
|
return loginUser;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
package com.example.demo.config;
|
package com.example.demo.config;
|
||||||
|
|
||||||
import org.springframework.boot.security.autoconfigure.web.servlet.PathRequest;
|
import org.springframework.boot.security.autoconfigure.web.servlet.PathRequest;
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
@@ -7,25 +7,25 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
|||||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
import org.springframework.security.web.SecurityFilterChain;
|
import org.springframework.security.web.SecurityFilterChain;
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
@EnableWebSecurity
|
@EnableWebSecurity
|
||||||
public class SecurityConfig {
|
public class SecurityConfig {
|
||||||
|
|
||||||
private final CustomAuthenticationFailureHandler failureHandler;
|
private final CustomAuthenticationFailureHandler failureHandler;
|
||||||
private final CustomAuthenticationSuccessHandler successHandler;
|
private final CustomAuthenticationSuccessHandler successHandler;
|
||||||
|
|
||||||
public SecurityConfig(
|
public SecurityConfig(
|
||||||
CustomAuthenticationFailureHandler failureHandler,
|
CustomAuthenticationFailureHandler failureHandler,
|
||||||
CustomAuthenticationSuccessHandler successHandler) {
|
CustomAuthenticationSuccessHandler successHandler) {
|
||||||
this.failureHandler = failureHandler;
|
this.failureHandler = failureHandler;
|
||||||
this.successHandler = successHandler;
|
this.successHandler = successHandler;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public SecurityFilterChain securityFilterChain(
|
public SecurityFilterChain securityFilterChain(
|
||||||
HttpSecurity http) throws Exception {
|
HttpSecurity http) throws Exception {
|
||||||
|
|
||||||
http
|
http
|
||||||
.authorizeHttpRequests(authorize -> authorize
|
.authorizeHttpRequests(authorize -> authorize
|
||||||
.requestMatchers(
|
.requestMatchers(
|
||||||
@@ -47,10 +47,10 @@ public class SecurityConfig {
|
|||||||
.logoutUrl("/logout")
|
.logoutUrl("/logout")
|
||||||
.logoutSuccessUrl("/login?logout")
|
.logoutSuccessUrl("/login?logout")
|
||||||
.permitAll());
|
.permitAll());
|
||||||
|
|
||||||
return http.build();
|
return http.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public PasswordEncoder passwordEncoder() {
|
public PasswordEncoder passwordEncoder() {
|
||||||
return new CompatiblePasswordEncoder();
|
return new CompatiblePasswordEncoder();
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
|
|
||||||
package com.example.demo.controller;
|
package com.example.demo.controller;
|
||||||
|
|
||||||
import jakarta.servlet.http.HttpSession;
|
import jakarta.servlet.http.HttpSession;
|
||||||
|
|
||||||
import org.springframework.stereotype.Controller;
|
import org.springframework.stereotype.Controller;
|
||||||
@@ -9,15 +8,15 @@ import org.springframework.web.bind.annotation.GetMapping;
|
|||||||
import org.springframework.web.bind.annotation.RequestParam;
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
|
||||||
import com.example.demo.common.Const;
|
import com.example.demo.common.Const;
|
||||||
|
|
||||||
@Controller
|
@Controller
|
||||||
public class LoginController {
|
public class LoginController {
|
||||||
|
|
||||||
@GetMapping("/")
|
@GetMapping("/")
|
||||||
public String root() {
|
public String root() {
|
||||||
return "redirect:/login";
|
return "redirect:/login";
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/login")
|
@GetMapping("/login")
|
||||||
public String loginForm(
|
public String loginForm(
|
||||||
HttpSession session,
|
HttpSession session,
|
||||||
@@ -25,21 +24,21 @@ public class LoginController {
|
|||||||
@RequestParam(name = "logout", required = false) String logout,
|
@RequestParam(name = "logout", required = false) String logout,
|
||||||
@RequestParam(name = "remaining", required = false) Integer remaining,
|
@RequestParam(name = "remaining", required = false) Integer remaining,
|
||||||
Model model) {
|
Model model) {
|
||||||
|
|
||||||
// すでにログインしている場合はメニュー画面へ
|
// すでにログインしている場合はメニュー画面へ
|
||||||
if (session.getAttribute(Const.SESSION_LOGIN_USER) != null) {
|
if (session.getAttribute(Const.SESSION_LOGIN_USER) != null) {
|
||||||
return "redirect:/menu";
|
return "redirect:/menu";
|
||||||
}
|
}
|
||||||
|
|
||||||
// ログイン失敗時のメッセージ
|
// ログイン失敗時のメッセージ
|
||||||
if ("locked".equals(error)) {
|
if ("locked".equals(error)) {
|
||||||
model.addAttribute(
|
model.addAttribute(
|
||||||
"errorMessage",
|
"errorMessage",
|
||||||
"ログインに5回連続で失敗したため、10分間アカウントをロックしました。"
|
"ログインに5回連続で失敗したため、10分間アカウントをロックしました。"
|
||||||
);
|
);
|
||||||
|
|
||||||
} else if ("failed".equals(error) && remaining != null) {
|
} else if ("failed".equals(error) && remaining != null) {
|
||||||
|
|
||||||
if (remaining == 1) {
|
if (remaining == 1) {
|
||||||
model.addAttribute(
|
model.addAttribute(
|
||||||
"errorMessage",
|
"errorMessage",
|
||||||
@@ -53,17 +52,17 @@ public class LoginController {
|
|||||||
+ "回間違えると、10分間ログインできなくなります。"
|
+ "回間違えると、10分間ログインできなくなります。"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
} else if (error != null) {
|
} else if (error != null) {
|
||||||
model.addAttribute(
|
model.addAttribute(
|
||||||
"errorMessage",
|
"errorMessage",
|
||||||
"メールアドレスまたはパスワードが間違っています。"
|
"メールアドレスまたはパスワードが間違っています。"
|
||||||
);
|
);
|
||||||
|
|
||||||
} else if (logout != null) {
|
} else if (logout != null) {
|
||||||
model.addAttribute("message", "ログアウトしました。");
|
model.addAttribute("message", "ログアウトしました。");
|
||||||
}
|
}
|
||||||
|
|
||||||
return "login";
|
return "login";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
package com.example.demo.service;
|
package com.example.demo.service;
|
||||||
|
|
||||||
import org.springframework.security.core.userdetails.UserDetails;
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||||
@@ -10,28 +10,28 @@ import com.example.demo.common.LoginUser;
|
|||||||
import com.example.demo.config.CustomUserDetails;
|
import com.example.demo.config.CustomUserDetails;
|
||||||
import com.example.demo.entity.Employee;
|
import com.example.demo.entity.Employee;
|
||||||
import com.example.demo.repository.EmployeeRepository;
|
import com.example.demo.repository.EmployeeRepository;
|
||||||
|
|
||||||
//Spring Securityから依頼を受けて、ログインする社員情報をDBから取得
|
//Spring Securityから依頼を受けて、ログインする社員情報をDBから取得
|
||||||
@Service
|
@Service
|
||||||
public class CustomUserDetailsService implements UserDetailsService {
|
public class CustomUserDetailsService implements UserDetailsService {
|
||||||
|
|
||||||
private final EmployeeRepository employeeRepository;
|
private final EmployeeRepository employeeRepository;
|
||||||
private final LoginAttemptService loginAttemptService;
|
private final LoginAttemptService loginAttemptService;
|
||||||
|
|
||||||
public CustomUserDetailsService(
|
public CustomUserDetailsService(
|
||||||
EmployeeRepository employeeRepository,
|
EmployeeRepository employeeRepository,
|
||||||
LoginAttemptService loginAttemptService) {
|
LoginAttemptService loginAttemptService) {
|
||||||
this.employeeRepository = employeeRepository;
|
this.employeeRepository = employeeRepository;
|
||||||
this.loginAttemptService = loginAttemptService;
|
this.loginAttemptService = loginAttemptService;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public UserDetails loadUserByUsername(String maillAddress) throws UsernameNotFoundException {
|
public UserDetails loadUserByUsername(String maillAddress) throws UsernameNotFoundException {
|
||||||
|
|
||||||
Employee employee = employeeRepository.findByMailAddressAndFlgRetirement(maillAddress.trim(), Const.RETIRE_NO)
|
Employee employee = employeeRepository.findByMailAddressAndFlgRetirement(maillAddress.trim(), Const.RETIRE_NO)
|
||||||
.orElseThrow(() -> new UsernameNotFoundException("認証に失敗しました。"));
|
.orElseThrow(() -> new UsernameNotFoundException("認証に失敗しました。"));
|
||||||
// ↑社員情報が見つからない場合は例外処理
|
// ↑社員情報が見つからない場合は例外処理
|
||||||
|
|
||||||
// 取得したEmployeeをLoginUserに変換する
|
// 取得したEmployeeをLoginUserに変換する
|
||||||
LoginUser loginUser = new LoginUser(
|
LoginUser loginUser = new LoginUser(
|
||||||
employee.getIdEmployee(),
|
employee.getIdEmployee(),
|
||||||
@@ -39,9 +39,9 @@ public class CustomUserDetailsService implements UserDetailsService {
|
|||||||
employee.getKnEmployee(),
|
employee.getKnEmployee(),
|
||||||
employee.getMailAddress(),
|
employee.getMailAddress(),
|
||||||
employee.getFlgAdmin());
|
employee.getFlgAdmin());
|
||||||
|
|
||||||
// Spring Security用の形式に変換
|
// Spring Security用の形式に変換
|
||||||
return new CustomUserDetails(loginUser, employee.getPassword(), loginAttemptService);
|
return new CustomUserDetails(loginUser, employee.getPassword(), loginAttemptService);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -1,101 +1,101 @@
|
|||||||
package com.example.demo.service;
|
package com.example.demo.service;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
import java.util.concurrent.ConcurrentMap;
|
import java.util.concurrent.ConcurrentMap;
|
||||||
|
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
// 失敗回数とロック時間を管理
|
// 失敗回数とロック時間を管理
|
||||||
@Service
|
@Service
|
||||||
public class LoginAttemptService {
|
public class LoginAttemptService {
|
||||||
|
|
||||||
// 最大失敗回数
|
// 最大失敗回数
|
||||||
private static final int MAX_ATTEMPTS = 5;
|
private static final int MAX_ATTEMPTS = 5;
|
||||||
// ロック時間
|
// ロック時間
|
||||||
private static final int LOCK_MINUTES = 10;
|
private static final int LOCK_MINUTES = 10;
|
||||||
|
|
||||||
// 失敗回数を保存
|
// 失敗回数を保存
|
||||||
private final ConcurrentMap<String, AttemptState> attempts = new ConcurrentHashMap<>();
|
private final ConcurrentMap<String, AttemptState> attempts = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
public static class AttemptState {
|
public static class AttemptState {
|
||||||
// 何回失敗したか
|
// 何回失敗したか
|
||||||
private final int failedAttempts;
|
private final int failedAttempts;
|
||||||
// いつロックを解除するか
|
// いつロックを解除するか
|
||||||
private final LocalDateTime lockedUntil;
|
private final LocalDateTime lockedUntil;
|
||||||
|
|
||||||
private AttemptState(int failedAttempts, LocalDateTime lockedUntil) {
|
private AttemptState(int failedAttempts, LocalDateTime lockedUntil) {
|
||||||
this.failedAttempts = failedAttempts;
|
this.failedAttempts = failedAttempts;
|
||||||
this.lockedUntil = lockedUntil;
|
this.lockedUntil = lockedUntil;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private String normalize(String mailAddress) {
|
private String normalize(String mailAddress) {
|
||||||
return mailAddress.trim().toLowerCase(Locale.ROOT);
|
return mailAddress.trim().toLowerCase(Locale.ROOT);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ログイン失敗時
|
// ログイン失敗時
|
||||||
public void loginFailed(String mailAddress) {
|
public void loginFailed(String mailAddress) {
|
||||||
String mail = normalize(mailAddress);
|
String mail = normalize(mailAddress);
|
||||||
LocalDateTime now = LocalDateTime.now();
|
LocalDateTime now = LocalDateTime.now();
|
||||||
AttemptState current = attempts.get(mail);
|
AttemptState current = attempts.get(mail);
|
||||||
|
|
||||||
// ロック中なら何もしない
|
// ロック中なら何もしない
|
||||||
if (current != null && current.lockedUntil != null
|
if (current != null && current.lockedUntil != null
|
||||||
&& now.isBefore(current.lockedUntil)) {
|
&& now.isBefore(current.lockedUntil)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 失敗回数を数える
|
// 失敗回数を数える
|
||||||
int count = (current == null || current.lockedUntil != null)
|
int count = (current == null || current.lockedUntil != null)
|
||||||
? 1
|
? 1
|
||||||
: current.failedAttempts + 1;
|
: current.failedAttempts + 1;
|
||||||
|
|
||||||
// 5回失敗したら10分間ロック
|
// 5回失敗したら10分間ロック
|
||||||
LocalDateTime lockTime = count >= MAX_ATTEMPTS
|
LocalDateTime lockTime = count >= MAX_ATTEMPTS
|
||||||
? now.plusMinutes(LOCK_MINUTES)
|
? now.plusMinutes(LOCK_MINUTES)
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
// 失敗回数とロック時間を保存
|
// 失敗回数とロック時間を保存
|
||||||
attempts.put(mail, new AttemptState(count, lockTime));
|
attempts.put(mail, new AttemptState(count, lockTime));
|
||||||
}
|
}
|
||||||
|
|
||||||
// 現在ロック中かどうか判定
|
// 現在ロック中かどうか判定
|
||||||
public boolean isBlocked(String mailAddress) {
|
public boolean isBlocked(String mailAddress) {
|
||||||
String mail = normalize(mailAddress);
|
String mail = normalize(mailAddress);
|
||||||
AttemptState current = attempts.get(mail);
|
AttemptState current = attempts.get(mail);
|
||||||
|
|
||||||
if (current == null) {
|
if (current == null) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (current.lockedUntil == null) {
|
if (current.lockedUntil == null) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 10分経過したらロックを解除
|
// 10分経過したらロックを解除
|
||||||
if (!LocalDateTime.now().isBefore(current.lockedUntil)) {
|
if (!LocalDateTime.now().isBefore(current.lockedUntil)) {
|
||||||
attempts.remove(mail);
|
attempts.remove(mail);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ログイン成功時に、過去の失敗回数をきれいにリセットする
|
// ログイン成功時に、過去の失敗回数をきれいにリセットする
|
||||||
public void loginSucceeded(String mailAddress) {
|
public void loginSucceeded(String mailAddress) {
|
||||||
attempts.remove(normalize(mailAddress));
|
attempts.remove(normalize(mailAddress));
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getFailedAttempts(String mailAddress) {
|
public int getFailedAttempts(String mailAddress) {
|
||||||
AttemptState state = attempts.get(normalize(mailAddress));
|
AttemptState state = attempts.get(normalize(mailAddress));
|
||||||
return state == null ? 0 : state.failedAttempts;
|
return state == null ? 0 : state.failedAttempts;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getRemainingAttempts(String mailAddress) {
|
public int getRemainingAttempts(String mailAddress) {
|
||||||
int failed = getFailedAttempts(mailAddress);
|
int failed = getFailedAttempts(mailAddress);
|
||||||
return Math.max(0, MAX_ATTEMPTS - failed);
|
return Math.max(0, MAX_ATTEMPTS - failed);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user