일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- input태그
- StyleSheet
- springSecurity
- html
- programmers
- security
- 반복문
- 시큐리티
- 스프링 부트
- javascript
- 시큐리티 로그인
- codingtest
- Linux
- 2차원배열
- 시큐리티 로그아웃
- 리눅스
- gradle
- 시큐리티로그인
- 로그인
- sql
- springboot
- 싱글톤
- JAVA11
- 목록
- css
- 소스트리
- 프로그래머스
- java
- Spring boot
- 코딩테스트
Archives
- Today
- Total
JAVAIARY
Spring Security - 4. 로그인 성공 / 로그아웃 본문
1. 로그인 처리
- 로그인 한 사용자에게 부여된 권한 (Authentication) 객체를 이용해 사용자가 가진 모든 권한을 문자열로 체크하여
사용자가 권한을 가졌다면 로그인 후 바로 권한 페이지로 이동할 수 있게 해 주기
1) AuthenticationSuccessHandler 구현
@Log4j
public class CustomLoginSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication auth) throws IOException, ServletException {
// TODO Auto-generated method stub
log.warn("Login Success");
List<String> roleNames = new ArrayList<>();
auth.getAuthorities().forEach(authority -> {
roleNames.add(authority.getAuthority());
});
log.warn("ROLE NAMES: " + roleNames);
if (roleNames.contains("ROLE_ADMIN")) {
response.sendRedirect("/sample/admin");
return;
}
if (roleNames.contains("ROLE_MEMBER")) {
response.sendRedirect("/sample/member");
return;
}
response.sendRedirect("/");
}
}
2) CustomLoginSuccessHandler bean등록
<security:form-login login-page="/loginForm" authentication-success-handler-ref="customLoginSuccess"/>
- CustomLoginSuccessHandler bean 등록 후 security:form-login 에 추가
- 로그인시 정상적으로 페이지 접근하는지 확인
- member 계정으로 로그인 --> member 페이지
- admin 계정으로 로그인 --> admin 페이지
2. 로그아웃 처리
1) security-context.xml
<!-- 로그아웃 처리 -->
<security:logout logout-url="/logoutForm" invalidate-session="true"/>
2) Controller
- CommonController
@GetMapping("/logoutForm")
public void logoutGET() {
log.info("custom logout");
}
3) logoutForm 뷰 생성
<h1> Logout Page</h1>
<form action="/springsecurity/logoutForm" method='post'>
<input type="hidden"name="${_csrf.parameterName}"value="${_csrf.token}"/>
<button>로그아웃</button>
</form>
- 실제 작업은 /logoutForm으로 처리하고 post방식으로 이루어짐
- post 방식으로 이루어지기 떄문에 CSRF토큰 값을 함께 지정
- 로그아웃 시 추가 작업이 필요하면 logoutSuccessHandler를 정의하여 처리
- logout 확인을 위하여 admin 페이지와 member 페이지에 /logoutForm페이지로 이동하는 버튼 생성
4) 확인
- 로그아웃 되어 내부적으로 자동으로 로그인 페이지 /loginForm?logout 로 이동
- logout-success-url 속성 등을 이용하여 변경 가능
- sample/member 나 sample/admin 호출로 로그아웃 확인 가능
# 코드로 배우는 웹 프로젝트 참고
'lectureNote > SPRING' 카테고리의 다른 글
Spring Security - 5. mybatis를 이용하여 기존테이블을 통한 인증/권한 처리 (0) | 2022.12.21 |
---|---|
lombok 과 어노테이션 (0) | 2022.12.21 |
Spring Security - 3. 커스텀 로그인 페이지 & CSRF 토큰 (0) | 2022.12.16 |
Spring Security - 2. 로그인 처리 (0) | 2022.12.16 |
Spring Security - 1. 환경설정 (0) | 2022.12.14 |