조급하면 모래성이 될뿐

SpringSecurity사용중 계정정보가 update되었을때 권한을 다시로드하는 방법. 본문

구현 기록/SpringSecurity

SpringSecurity사용중 계정정보가 update되었을때 권한을 다시로드하는 방법.

Pawer0223 2020. 3. 16. 19:30

개인 프로젝트를 진행하면서, 계정의 권한별로 보여지는 메뉴리스트 구성을 달리하였다.

 

프로젝트의 내용은 자영업자들이 이벤트를 등록하면, 일반유저들이 이용하는방식이다.

 

ㅇ 권한리스트

일반사용자 : ROLE_NORMAL

사업자 : ROLE_PARTNER, ROLE_NORMAL

 

일반사용자는 [ 가게등록 ] 메뉴를 볼 수 있다.

[ 가게등록 ]메뉴는 사업자를 등록하는 메뉴이고, 사업자등록시 ROLE_PARTNER권한을 부여받는다.

 

사업자를 등록한 계정은 더이상 [ 가게등록 ]메뉴를 볼 필요가없다.

 

그러나, 일반사용자가 로그인 후, 사업자등록을하게되면 ROLE_NORMAL에 ROLE_PARTNER의 권한이 추가되지만, Reload된 메뉴구성에는 여전히 [ 가게등록 ]메뉴가 보이고있다..

 

원인은 최초 로그인시 SpringSecurity가 계정정보를 관리할 수 있도록 만들어준 Authentication객체는 로그인 시점의 계정정보를 담고있는데, 사업자 권한이 추가되면서 update된 정보에대해서는 Authentication객체에 현행화 되지않았기 때문이다..

 

쉽게말하면, Security가 계정정보를 관리하고있는 객체가 update되지않았다는 말이다.

 

해결방법으로는, 가게등록을 완료한 후에 기존계정이 관리되고있는 객체에 ROLE_PARTNER의 권한만 추가해주면된다.

 

먼저, 위와같이 풀기위한 JSP페이지의 헤더는 아래와같이 구성되어있다.

<!-- 가게 등록은, 사업자를 등록하지않은 일반 사용자에게만 보인다.  -->
<sec:authorize access="hasRole('ROLE_NORMAL')">
	<sec:authorize access="!hasRole('ROLE_PARTNER')">
		<div class="collapse navbar-collapse" id="ftco-nav">
			<ul class="navbar-nav ml-auto">
				<li class="nav-item"><a href="/nor/goRegistStore.do" class="nav-link">가게등록</a></li>
			</ul>
		</div>
	</sec:authorize>
</sec:authorize>

 

기존 객체에 동적으로 새로운 권한을 추가해주는 방법.

 

1. 기존 계정의 권한정보를 가지고온다.

Authentication auth = SecurityContextHolder.getContext().getAuthentication();

List<GrantedAuthority> updatedAuthorities = new ArrayList<>(auth.getAuthorities());

 

2. 거기에 ROLE_PARTNER를 추가해준다.

updatedAuthorities.add(new SimpleGrantedAuthority("ROLE_PARTNER"));

 

3. 추가한 권한정보로 다시 Security가 관리할 수 있는 객체를 생성해준다.

Authentication newAuth = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), updatedAuthorities);

4. Security가 관리하고있는 객체를 3에서 변경된 대상으로 변경해준다.

SecurityContextHolder.getContext().setAuthentication(newAuth);

 

위와같이 추가해주었더니, 권한을 추가한후에 새로고침을 누르면 정상적으로 [ 가게등록 ] 메뉴가 보이지않았다.

 

아래 블로그를 참조하면, 이해하는데 더 큰도움이 될것같다.. SecurityContextHolder?? [ 참조 ]

반응형