SimpleController 생성
import java.security.Principal;
@Controller
public class SampleController {
@GetMapping("/")
public String index(Model model) {
model.addAttribute("message", "Hello Spring Security!");
return "index";
}
@GetMapping("/info")
public String info(Model model) {
model.addAttribute("message", "Info");
return "info";
}
@GetMapping("/dashboard")
public String dashboard(Model model, Principal principal) {
model.addAttribute("message", "Hello " + principal.getName());
return "dashboard";
}
@GetMapping("/admin")
public String admin(Model model, Principal principal) {
model.addAttribute("message", "Hello Admin " + principal.getName());
return "admin";
}
}
로그인 후 다른 메시지
@GetMapping("/")
public String index(Model model, Principal principal) {
if (principal == null) {
model.addAttribute("message", "Hello Spring Security!");
}
else {
model.addAttribute("message", "Hello " + principal.getName());
}
return "index";
}
index.html 생성
<!DOCTYPE html>
<html lang="en" xmlns:th="<http://www.thymeleaf.org>">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 th:text="${message}">Hello</h1>
</body>
</html>
admin.html
<!DOCTYPE html>
<html lang="en" xmlns:th="<http://www.thymeleaf.org>">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 th:text="${message}">Hello</h1>
</body>
</html>
dashboard.html
<!DOCTYPE html>
<html lang="en" xmlns:th="<http://www.thymeleaf.org>">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 th:text="${message}">Hello</h1>
</body>
</html>
info.html
<!DOCTYPE html>
<html lang="en" xmlns:th="<http://www.thymeleaf.org>">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 th:text="${message}">Hello</h1>
</body>
</html>
form.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
의존성을 추가하면 모든 요청은 인증이 필요하다
스프링 부트 시큐리티 기본 설정
모든 요청은 인증을 필요로 한다
기본유저가 생성
SecurityConfig 생성
WebSecurityConfigureAdapter를 상속 받아 SecurityConfig를 만든다
package me.jiho.demospringsecurityform.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.mvcMatchers("/", "/info").permitAll() // "/" "/info" 모두 접근허용
.mvcMatchers("/admin").hasRole("ADMIN") // "/admin"은 ADMIN Role을 가지고 있이야 한다
.anyRequest().authenticated() // 그밖에 모든 요청 허용
.and()
.formLogin() //formLogin 사용 기본설정으로 사용
.and()
.httpBasic(); // httpBasic 사용
}
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.mvcMatchers("/", "/info").permitAll()
.mvcMatchers("/admin").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.httpBasic();
http.formLogin();
}
나누어 사용해도 된다.
UserDetailsServiceAutoConfiguration
스프링 부트 실행 시 유저를 하나 등록 해준다
@Lazy
public InMemoryUserDetailsManager inMemoryUserDetailsManager(SecurityProperties properties, ObjectProvider<PasswordEncoder> passwordEncoder) {
User user = properties.getUser();
List<String> roles = user.getRoles();
return new InMemoryUserDetailsManager(new UserDetails[]{org.springframework.security.core.userdetails.User.withUsername(user.getName()).password(this.getOrDeducePassword(user, (PasswordEncoder)passwordEncoder.getIfAvailable())).roles(StringUtils.toStringArray(roles)).build()});
}
SecurityProperties를 사용해서 application.properties에서 기본 유저를 변경할 수 있다
spring.security.user.name=admin
spring.security.user.password=1234
spring.security.user.roles=ADMIN
configure(AuthenticationManagerBuilder auth)
SecurityConfig 클래스에서 configure(AuthenticationManagerBuilder auth)를 오버라이딩 하여 유저를 추가 및 inMemoryAuthentication 사용
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("jiho").password("{noop}pass").roles("USER").and()
.withUser("admin").password("{noop}pass").roles("ADMIN")
}
{encoder}는 스프링 시큐리티 내부에 있는 기본 패스워드 인코더 중 현재 사용중인것을 의미한다 password가 {noop}은 암호화가 되어 있지 않은 것을 의미한다
의존성 추가
jpa 의존성을 추가한다
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
데이터베이스 의존성 추가한다
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
Entity 생성
Account Entity를 만든다
package me.jiho.demospringsecurityform.account;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Account {
@Id @GeneratedValue
private Integer id;
@Column(unique = true)
private String username;
private String password;
private String role;
public Integer getId() {
return id;
}
public void setId(Integer 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;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}