개발자의 오르막

[SpringSecurity #15] 스프링 시큐리티 데이터 연동 본문

SpringFrameWork/SpringSecurity

[SpringSecurity #15] 스프링 시큐리티 데이터 연동

계단 2020. 10. 6. 00:18

#  스프링 데이터 연동

compile group: 'org.springframework.security', name: 'spring-security-data', version: '4.0.0.RELEASE'

 

- 먼저 테스트를 위한 Book 데이터를 만들기 위해 도메인과 DefaultDataGenerator 를 만들어 본다.

 

 

 

- Book

@Entity
@Getter
@Setter
public class Book {

    @Id @GeneratedValue
    private Integer id;

    private String title;

    @ManyToOne
    private Account author;

    public Integer getId() {
        return id;
    }
}

 

- DefaultDataGenerator

@Component
@RequiredArgsConstructor
public class DefaultDataGenerator implements ApplicationRunner {

    private final AccountService accountService;
    private final BookRepository bookRepository;



    @Override
    public void run(ApplicationArguments args) throws Exception {
        // TODO jake - spring
        // TODO jay -jpa

        Account jake = createUser("jake");
        Account jay = createUser("jay");

        Book spring = createBook("spring", jake);
        Book jpa = createBook("jpa", jay);
    }

    private Book createBook(String title, Account jake) {
        Book book = new Book();
        book.setTitle(title);
        book.setAuthor(jake);
        return bookRepository.save(book);
    }

    private Account createUser(String username) {
        Account account = new Account();
        account.setUsername(username);
        account.setPassword("123");
        account.setRole("USER");
        return accountService.createNew(account);
    }
}

 

- indexController

@GetMapping("/user")
    public String user(Model model, Principal principal) {
        model.addAttribute("message", "Hello User, " + principal.getName());
        model.addAttribute("books", bookRepository.findCurrentUserBooks());
        return "user";
    }

 

 

- BookRepository

public interface BookRepository extends JpaRepository<Book, Integer> {
    
    @Query("select b from Book b where b.author.id = ?#{principal.account.id}")
    List<Book> findCurrentUserBooks();
    
}

  스프링 시큐리티 데이터 연동을 사용하면 Repository 의 쿼리 안에 principal 을 활용할 수 있다.

 

 

- user.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>user</title>
</head>
<body>
<h1 th:text="${message}">user</h1>
<tr th:each="book : ${books}">
    <td><span th:text="${book.title}">Title</span></td>
</tr>
</body>
</html>
Comments