스프링시큐리티를 이용하여 index페이지를 통해 hello페이지는 누구나 볼 수 있으나
my페이지는 로그인한 사용자만 볼 수 있도록 해보자
1) 뷰 생성
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Welcome</h1>
<a href="/hello">Hello</a>
<a href="/my">My Page</a>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Hello</h1>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>My Page</h1>
</body>
</html>
먼저 다음과 같이 Thymleaf를 통해 index.html, hello.html, my.html 페이지를 생성하였다.
2) 컨트롤러 생성
@Controller
public class HomeController {
@GetMapping("/hello")
public String hello() {
return "hello";
}
@GetMapping("/my")
public String my() {
return "my";
}
}
hello와 my요청에 대한 컨트롤러도 만들어주었다.
3) SecurityConfig 생성
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override //재정의
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/hello").permitAll() // "/", "/hello" 는 모두 볼수있음
.anyRequest().authenticated() // 그 외에는 인증필요함
.and()
.formLogin()
.and()
.httpBasic();
}
@Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
}
WebSecurityConfigurerAdapter를 상속받은 SecurityConfig 클래스를 생성하여
configure메소드를 재정의 해 준다. 루트와 hello에 대한 요청은 인증이 필요없도록 설정하였다.
재정의 하였기에 기존에 스프링시큐리티에서 제공한 기본설정은 사용되지 않는다.
PasswordEncoder를 이용해 비밀번호는 암호화하여 저장되도록 하였다.
4) Entity 생성
@Entity
public class Account {
@Id @GeneratedValue
private Long id;
private String username;
private String password;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
사용자정보를 스프링시큐리티에서 제공하는 기본정보가 아닌 직접 DB에서 관리할 수 있도록
Account객체를 생성한다.
public interface AccountRepository extends JpaRepository<Account, Long> {
Optional<Account> findByUsername(String s);
}
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
JPA를 사용하기 위해 Repository와 의존성도 추가해주었다.
5) 서비스 구현
@Service
public class AccountService implements UserDetailsService {
@Autowired
private AccountRepository accountRepository;
@Autowired
private PasswordEncoder passwordEncoder;
public Account createAccount(String username, String password){
Account account = new Account();
account.setUsername(username);
account.setPassword(passwordEncoder.encode(password));
return accountRepository.save(account);
}
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
Optional<Account> byUsername = accountRepository.findByUsername(s);
Account account = byUsername.orElseThrow(() -> new UsernameNotFoundException(s));
return new User(account.getUsername(), account.getPassword(), authorities());
}
private Collection<? extends GrantedAuthority> authorities() {
return Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"));
}
}
DB 사용자 인증 처리을 위해 UserDetailsService 클래스를 커스트마이징 해야 한다.
UserDetailsService를 implement하여 loadUserByUsername를 구현해준다.
loadUserByUsername이 핵심이다. 이 부분에서 사용자계정과 DB가 연동된다.
6) 테스트 및 실행
@Component
public class AccountRunner implements ApplicationRunner {
@Autowired
AccountService accountService;
@Override
public void run(ApplicationArguments args) throws Exception {
Account ny = accountService.createAccount("ny", "1234");
System.out.println(ny.getUsername() + "password :" +ny.getPassword());
}
}
ApplicationRunner클래스를 생성하여 테스트를 진행해보자
실행해보면 인덱스페이지와 hello페이지는 접속되지만 my페이지를 클릭하면 로그인페이지가 뜬다.
인코딩된 사용자 정보가 찍히는 것도 확인할 수 있다.
'Study > Spring boot' 카테고리의 다른 글
[Spring Boot] 스프링 시큐리티 (0) | 2021.01.09 |
---|---|
[Spring Boot] 스프링 데이터 - 데이터베이스 초기화 (0) | 2021.01.03 |
[Spring Boot] 스프링 데이터 JPA (0) | 2021.01.02 |
[Spring Boot] 스프링 데이터 - MySQL, PostgreSQL (0) | 2020.12.26 |
[Spring Boot] 스프링 데이터 - H2 인메모리 데이터베이스 (0) | 2020.12.26 |