chae._.chae

시큐리티 - (1) 시큐리티 초기 설정 본문

스프링/시큐리티

시큐리티 - (1) 시큐리티 초기 설정

walbe0528 2022. 6. 30. 19:07
728x90
반응형

Dependencies : 

  • Spring Boot DevTools
  • Lombok
  • Spring Data JPA
  • MySQL Driver
  • Spring Security
  • Mustache
  • Spring Web

 

위의 의존성을 추가해 프로젝트를 생성해준다. 

 

- application.yml 파일 설정

server:
  port: 8080
  servlet:
    context-path: /
    encoding:
      charset: UTF-8
      enabled: true
      force: true
spring:
  datasource:
    driver-class-name: org.mariadb.jdbc.Driver
    url: jdbc:mariadb://localhost:3307/security?serverTimezone=Asia/Seoul
    username: root
    password: 1234

  main:
    allow-circular-references: true

  jpa:
    hibernate:
      ddl-auto: update
      naming:
        physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
    show-sql: true

 

- IndexController.java

@Controller  // view를 return
public class IndexController {

    // localhost:8080/
    // localhost:8080
    @GetMapping({"", "/"})
    public String index(){
        // 머스테치 기본 폴더 : src/main/resources/
        // 뷰 리졸버 설정(application.yml에서 설정) : templates(prefix), .mustache(suffix) -> 생략가능
        return "index";  // src/main/resources/templates/index.mustache를 찾는다
    }

    // 권한설정을 해줘서 권한이 있는 사람만 접속할 수 있게끔
    @GetMapping("/user")
    public @ResponseBody String user(){
        return "user";
    }

    @GetMapping("/admin")
    public @ResponseBody String admin(){
        return "admin";
    }

    @GetMapping("/manager")
    public @ResponseBody String manager(){
        return "manager";
    }
	// 시큐리티가 해당 주소를 낚아채서, 내가 설정한 login이 뜨지 않고, username과 password를 입력하는 창이 뜬다. 
    // SecurityConfig 파일 생성후 권한 설정을 해둔 뒤, 시큐리티가 낚아채지 않는다.
    @GetMapping("/login")
    public @ResponseBody String login(){
        return "login";
    }

    @GetMapping("/join")
    public @ResponseBody String join(){
        return "join";
    }

    @GetMapping("/joinProc")
    public @ResponseBody String joinProc(){
        return "회원가입 완료됨!";
    }

}

해당 주소로 접속했을때 뜨는 페이지 문구를 간단하게 만들어준다. 

 

 

 

http://localhost:8080에 접속하면 바로 index.html이 보이지 않고 위의 로그인 페이지가 뜬다. 

스프링부트에 시큐리티 의존성을 사용하면 홈페이지로 들어가는 모든 주소가 막혀서 인증이 필요한 서버가 된다.

 

 

Username : user

Password : 스프링부트를 실행시켰을 때 위의 사진처럼 출력되는 security password를 입력

 

 

 

- config패키지를 생성하고, SecurityConfig.java 파일을 설정해준다. 

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable();
        http.authorizeRequests()
                .antMatchers("/user/**").authenticated()  // 해당 주소로 들어오면 인증이 필요하다
                .antMatchers("/manager/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_MANAGER')")  // admin과 manager권한이 있는 사람만 접속 가능
                .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
                .anyRequest().permitAll(); // 다른 주소는 모두 허용

    }

}

 

이제 http://localhost:8080 페이지로 접속하면 로그인하지 않아도 index페이지가 뜨게 된다.

위에서 antMatchers()로 설정해준 주소가 아니기에 접근 가능하다.

또한, /login페이지로 접속하면 스프링 시큐리티가 낚아채지 않고 내가 만든 login페이지로 이동한다. 

/user로 접속하면 접근권한이 없다는 403에러가 뜬다. (로그인을 아직 안했기 때문에)

 

 

이제 권한이 없는 페이지에 접속했을때 로그인 페이지가 나오도록 설정해주려면, SecurityConfig에서

@Override
protected void configure(HttpSecurity http) throws Exception {

    http.csrf().disable();
    http.authorizeRequests()
            .antMatchers("/user/**").authenticated()  // 해당 주소로 들어오면 인증이 필요하다
            .antMatchers("/manager/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_MANAGER')")  // admin과 manager권한이 있는 사람만 접속 가능
            .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
            .anyRequest().permitAll() // 다른 주소는 모두 허용
            .and()
            .formLogin()
            .loginPage("/login"); // 권한이 없는 페이지에 접속했을때 로그인 페이지가 나오도록 설정
}

loginPage() 설정을 추가해준다. 

 

 

전체 프로젝트 구조

 

 


 

728x90