Spring Security (5): 인증 (Authentication) - 문자 인증번호 로그 인
<p>
<label for="imageCode"> label>
<input type="input" id="smsCode" name="smsCode" required>
<button onclick="getSmsCode()"> button>
p>
<script>
function getSmsCode() {
var ajax = new XMLHttpRequest();
ajax.open('get','/code/sms');
ajax.send();
}
script>
@Data
@ToString
@AllArgsConstructor
@RequiredArgsConstructor
public class SmsCode {
private String code;
private LocalDateTime expireTime;
public SmsCode(String code, int expireIn) {
this.code = code;
this.expireTime = LocalDateTime.now().plusSeconds(expireIn);
}
public boolean isExpried() {
return LocalDateTime.now().isAfter(expireTime);
}
}
@RestController
public class SmsValidateCodeController {
private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
public static final String SESSION_KEY = "SESSION_KEY_SMS_CODE";
@GetMapping("/code/sms")
public void createCode(HttpServletRequest request) {
SmsCode smsCode = createSmsCode();
System.out.println(" :" + smsCode);
sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY, smsCode);
}
private SmsCode createSmsCode() {
String code = (int) ((Math.random() * 9 + 1) * 100000) + "";
return new SmsCode(code, 600);
}
}
public class SmsValidateCodeFilter extends OncePerRequestFilter {
@Autowired
private AuthenticationFailureHandler authenticationFailureHandler;
// spring-social-web
private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
if ("/login".equals(request.getRequestURI()) && "POST".equals(request.getMethod())) {
try {
validate(new ServletWebRequest(request));
} catch (ValidateCodeException e) {
authenticationFailureHandler.onAuthenticationFailure(request, response, e);
return;
}
}
filterChain.doFilter(request, response);
}
private void validate(ServletWebRequest request) throws ServletRequestBindingException {
SmsCode codeInSession = (SmsCode) sessionStrategy.getAttribute(request, SmsValidateCodeController.SESSION_KEY);
String codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(), "smsCode");
if (StringUtils.isEmpty(codeInRequest)) {
throw new ValidateCodeException(" ");
}
if (codeInSession == null) {
throw new ValidateCodeException(" ");
}
if (codeInSession.isExpried()) {
sessionStrategy.removeAttribute(request, SmsValidateCodeController.SESSION_KEY);
throw new ValidateCodeException(" ");
}
if (!codeInRequest.equals(codeInSession.getCode())) {
throw new ValidateCodeException(" ");
}
sessionStrategy.removeAttribute(request, SmsValidateCodeController.SESSION_KEY);
}
public AuthenticationFailureHandler getAuthenticationFailureHandler() {
return authenticationFailureHandler;
}
public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) {
this.authenticationFailureHandler = authenticationFailureHandler;
}
}
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private MyUserDetailsService myUserDetailsService;
@Autowired
private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;
@Autowired
private MyAuthenticationFailureHandler myAuthenticationFailureHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
SmsValidateCodeFilter smsValidateCodeFilter = new SmsValidateCodeFilter();
smsValidateCodeFilter.setAuthenticationFailureHandler(myAuthenticationFailureHandler);
http.csrf().disable()
//
.authorizeRequests()
.antMatchers("/login", "/code/image", "/code/sms").permitAll()
.anyRequest()
.authenticated()
.and()
//
.addFilterBefore(smsValidateCodeFilter, UsernamePasswordAuthenticationFilter.class)
.formLogin()
.loginPage("/login")
.usernameParameter("username")
.passwordParameter("password")
.successHandler(myAuthenticationSuccessHandler)
.failureUrl("/login?error")
.permitAll()
.and()
//
.logout()
.permitAll();
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(myUserDetailsService).passwordEncoder(passwordEncoder());
}
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/static/**");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
[MeU] Hashtag 기능 개발➡️ 기존 Tag 테이블에 존재하지 않는 해시태그라면 Tag , tagPostMapping 테이블에 모두 추가 ➡️ 기존에 존재하는 해시태그라면, tagPostMapping 테이블에만 추가 이후에 개발할 태그 기반 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.