[Spring Boot] Spring Security Config

Coco Park·2024년 1월 10일
0

Spring_Boot

목록 보기
3/13

Spring Security Config

Spring Security를 사용하려면 의존성을 추가한 후에 Config파일을 생성하여 각 URL에 대한 권한관리를 진행하면 된다.

기본 설정

SecurityConfig Class를 생성한 후에 Bean 어노테이션을 명시한 SecurityFilterChain 메소드를 정의해주면 된다.

여기서 주의해야할 점은 위에서부터 아래로 권한이 설정되므로 최상단에 전체 권한을 허용하게끔 해두면 하단에 다른 권한 설정을 하더라도 전체 권한이 허용되므로 주의해야한다.

권한

1. permitAll - 모든 사용자들(유저가 아니어도 됨)이 해당 URL에 접근할 수 있다.

2. hasAnyRole - 명시된 권한들 중 하나를 만족한다면 해당 URL에 접근할 수 있다.

3. hasRole - 명시된 권한인 경우에만 해당 URL에 접근할 수 있다.

CASE 1. permitAll로 설정된 메인페이지에 접근하는 경우

다음과 같이 회원이 아닌 anonymousUser여도 접근할 수 있음.

CASE 2. ADMIN으로 설정된 /admin 페이지에 접근하는 경우

위처럼 admin이 아닌 회원이 접근하고자 하면 액세스가 거부됨

하지만 ROLE_ADMIN을 권한으로 갖는 유저는 접근이 가능함

- ADMIN 권한을 갖는 아이디로 로그인한 모습

- 미리 구현해 둔 테스트용 관리자 페이지

위에서 사용된 메인 컨트롤러와 VIEW 코드는 다음과 같다

<!--main.mustache-->
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
===MAIN PAGE===
<hr>
ID : {{id}} <!-- 컨트롤러에서 넘긴 ID-->
<hr>
ROLE : {{role}} <!-- 컨트롤러에서 넘긴 ROLE-->
</body>
</html>
//MainController.java
    @GetMapping("/")
    public String mainPage(Model model) {

		// 유저의 ID를 받아오는 방법
        String id = SecurityContextHolder.getContext().getAuthentication().getName();

        // 권한에 대한 정보를 받아오는 방법
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Collection<? extends GrantedAuthority> collection = auth.getAuthorities();
        Iterator<? extends GrantedAuthority> iterator = collection.iterator();
        GrantedAuthority grantedAuthority = iterator.next();
        String role = grantedAuthority.getAuthority();

		// VIEW단으로 정보를 전달
        model.addAttribute("id", id);
        model.addAttribute("role", role);

        return "main";
    }
profile
ヽ(≧□≦)ノ

0개의 댓글