새소식

반응형
WEB/Spring Security

[Spring Security] 로그인 유저 이름과 / 권한 확인하는 방법

  • -
반응형

2022-12-18


Photo by Anita Austvika on Unsplash


1. 방법

 

유저의 권한의 경우 Authentication 객체를 사용해 현재 로그인한 유저의 권한 정보를 가져오고 자신이 구현한 서비스에 접근 권한이 있는지 없는지를 확인할 수 있는 flag 변수를 선언함으로써, 접근 제어를 설정할 수 있게끔 소스코드를 구현했다.

 

이후 접근 권한이 있을 경우 유저의 계정 정보를 확인할 수 있도록  UserDetails 객체를 사용하여 유저의 계정명을 가져온다.


import
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import lombok.extern.slf4j.Slf4j;

소스코드
	public void authCheck(Authentication authentication) {
		
        //유저 권한 확인
        @SuppressWarnings("unchecked")
		List<GrantedAuthority> authList = (List<GrantedAuthority>) authentication.getAuthorities();
		log.info("권한 : ");
		boolean authCheck = false;
		for(int i = 0; i< authList.size(); i++) {
			log.info(authList.get(i).getAuthority() + " ");
			if(authList.get(i).getAuthority().equals("ROLE_ADMIN")) {
				authCheck = true;
			}
		}
		
        	// 유저 권한이 있는 없는지 확인하는 옵션
		if(!authCheck) { 
			log.info("Deny -> No ROLE_ADMIN" );
			return;
		}	
		
       		//유저 이름 확인
		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String userName = ((UserDetails) principal).getUsername();
		
	
	}

메인 이미지 출처 : Photo by Anita Austvika on Unsplash  

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.