본문 바로가기

자바

로그인 성공, 실패 핸들러 작성 feat. 로그인 실패 시 alert 띄우기 [Java, Spring Security]

반응형

config패키지의 SecurityConfig.java에 fromLogin() 을 이용하여 로그인에 관련된 부분을 다룰 수 있다.

failureHandler와 successHandler로 실패 핸들러와 성공핸들러를 작성해보자

 

SecurityConfig.java

 @Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
			.antMatchers("/", "/login").permitAll()
			//.antMatchers("/admin").hasRole("ADMIN")
			.antMatchers("/favicon.ico").permitAll()
			.anyRequest().authenticated()
			.and()
		.formLogin()
			.loginPage("/login")
			.loginProcessingUrl("/authenticate")
			.defaultSuccessUrl("/main")
			.failureHandler(authenticationFailureHandler())  //로그인실패했을 때
			.successHandler(successHandler())                //로그인성공했을 때
			.permitAll()
			.and()
		.logout()
			.logoutUrl("/logout")
			.logoutSuccessUrl("/login")
			.deleteCookies("auth_code", "JSESSIONID")
			.invalidateHttpSession(true)
			.permitAll();
		
		http.csrf().disable();
		
	}

    @Bean
	public PasswordEncoder passwordEncoder()
	{
		return new BCryptPasswordEncoder();
	}
	//실패 핸들러
	@Bean
	public AuthenticationFailureHandler authenticationFailureHandler() {
		return new CustomizeAuthenticationFailureHandler();
		
	}
	//성공 핸들러
	@Bean
	public AuthenticationSuccessHandler successHandler() {
		return new AuthenticationSuccessHandler();
	}

 

실패핸들러 CustomizeAuthenticationFailureHandler.java

public class CustomizeAuthenticationFailureHandler implements AuthenticationFailureHandler{

	@Autowired
	private UserDao userDao;
	
	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {
		// TODO Auto-generated method stub
		String msg = "";
		String ID = request.getParameter("username");
		String PW = request.getParameter("password");
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();		
		String password = userDao.check_account(ID);	
		if(password == null || password.equals("")) {
			msg = "NotFound";
		}
		boolean result = encoder.matches(PW, password);
		if(result == false) {
			msg = "NotFound";
		}
		//msg = URLEncoder.encode(msg, "UTF-8");
		response.sendRedirect("/login?msg="+msg);
	}
}

 

성공핸들러 (CustomizeAuthenticationSuccessHandler.java)

public class CustomizeAuthenticationSuccessHandler implements AuthenticationSuccessHandler{

	@Autowired
	private MemberServiceImpl memberService;
	
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpSession session = request.getSession();

		if(session != null){
			String name = authentication.getName();
			MemberVo member = (MemberVo)session.getAttribute("LoginMember");
			if(member == null)
			{
				member = memberService.getMemberDetail(name);
				session.setAttribute("LoginMember", member);
			}			
		}
		response.sendRedirect("/main");
	}
}

 

 

핸들러 파일은 securityConfig.java 와 같은 뎁스에 만들면 됨