본문 바로가기
🌿 Spring

[Spring Boot/RESTful] Spring Security를 이용한 로그인

by nitronium102 2022. 2. 18.

[기본] dependency 추가

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-security</artifactId>
</dependency>

 

1. 자동으로 생성되는 username, password를 이용

1) 기본 password 확인

dependency를 설정한 후, 어플리케이션을 실행하여 비밀번호를 확인해야 한다. (웹서버를 확인하기 위해 필요)

2) 웹 브라우저 요청

인증이 되어 있지 않다면 401 Unauthorized가 뜬다.

여기에서 username 값을 user로 해도 불러와지는 이유는 spring security의 기본 설정 때문이다.

 

Spring Security 기본 설정

spring.security.user.name / spring.security.user.password를 지정하지 않으면 기본 유저명과 랜덤 패스워드를 사용한다.

→ 기본 유저명은 user이며 password의 경우 스프링부트가 기동될 때 표시된다

 

스프링부트에서 설정할 수 있는 항목 :
https://docs.spring.io/spring-boot/docs/current/reference/html/application-properties.html

 

Common Application Properties

 

docs.spring.io

 

2. 개발자가 지정한 username과 password를 이용

1) application.yml

application.yml 파일에 고정적인 username과 password 부여 -> 정보가 바뀔 때마다 수정해야 한다.

[application.yml]
spring:
security:
    user:
      name: nitro
      password: helloworld

2) Configuration 클래스 생성(추천)

@Configuration // Spring boot 기동 시 메모리에 설정 정보를 같이 로딩하게 된다
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth)
		throws Exception {
			auth.inMemoryAuthentication()
				.withUser("minji")
                // {noop} : 어떤 동작도 없이 인코딩 없이 바로 사용(no operation)
				.password("{noop}test1234")
				.roles("USERS");

	}
}

댓글