상식닷컴
로그인
가입하기
2026년 상식닷컴 선정 식당 & 카페 리스트
2025년 2026년 신상 호텔 리스트
최근에 오픈한 호텔을 찾는다면 살펴보세요
일주일 식단표 어플
자동 일주일 식단표 어플
안드로이드
아이폰
주식 & 코인 차트의 신
1000만원으로 2000만원 만들기 프로젝트
수정하기 - 스프링의 Security 모듈을 사용하여 인증 및 권한 부여를 설정하는 방법은?
닉네임
비밀번호
제목
내용
[이미지 업로드는 권한이 있는 사람만 가능. 하단 카톡으로 연락]
스프링 프레임워크의 Security 모듈은 애플리케이션의 인증 및 권한 부여를 간편하게 설정할 수 있도록 도와줍니다. 이 글에서는 스프링 시큐리티를 사용하여 인증 및 권한 부여를 설정하는 방법에 대해 단계별로 설명하겠습니다. 1. 의존성 추가스프링 부트 프로젝트를 사용하고 있다면, `pom.xml` 또는 `<a href='https://sangseek.com/sangseeks/build.gradle/ko'>build.gradle</a>` 파일에 스프링 시큐리티 의존성을 추가해야 합니다. Maven (pom.xml) :```xml<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId></dependency>``` Gradle (build.gradle) :```groovyimplementation 'org.springframework.boot:spring-boot-starter-security'``` 2. 기본 설정스프링 시큐리티는 기본적으로 모든 요청에 대해 인증을 요구합니다. 이를 위해 `WebSecurity<a href='https://sangseek.com/sangseeks/Configure/ko'>Configure</a>rAdapter`를 확장하여 설정 클래스를 작성합니다.```javaimport 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@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) <a href='https://sangseek.com/sangseeks/throws/ko'>throws</a> Exception { http .authorizeRequests() .antMatchers("/public/ ").permitAll() // 공개 URL .anyRequest().authenticated() // 나머지 요청은 인증 필요 .and() .formLogin() // 기본 로그인 폼 사용 .loginPage("/login") // 커스텀 로그인 페이지 .permitAll() .and() .logout() // 로그아웃 설정 .permitAll(); }}``` 3. 사용자 인증 정보 설정사용자 인증 정보를 메모리 또는 데이터베이스에 저장할 수 있습니다. 여기서는 메모리 기반 사용자 저장소를 설정하는 예를 보여드립니다.```javaimport org.springframework.context.annotation.Bean;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManager<a href='https://sangseek.com/sangseeks/Builder/ko'>Builder</a>;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;import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;import org.springframework.security.crypto.password.PasswordEncoder;@Configuration@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user").password(passwordEncoder().encode("password")).roles("USER") .and() .withUser("admin").password(passwordEncoder().encode("admin")).roles("ADMIN"); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/public/ ").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll(); }}``` 4. 권한 부여 설정특정 URL에 대한 권한을 설정하려면 `hasRole()` 또는 `hasAuthority()` 메서드를 사용할 수 있습니다.```java@Overrideprotected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/admin/ ").hasRole("ADMIN") // ADMIN 역할만 접근 가능 .antMatchers("/user/ ").hasRole("USER") // USER 역할만 접근 가능 .antMatchers("/public/ ").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll();}``` 5. 커스텀 로그인 페이지로그인 페이지를 커스터마이즈하려면, `/login` 경로에 해당하는 <a href='https://sangseek.com/sangseeks/HTML 파일/ko'>HTML 파일</a>을 생성하고, 사용자에게 적절한 피드백을 제공할 수 있습니다.```html<!-- login.html --><!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Login</title></head><body> <h2>Login</h2> <form action="/login" method="post"> <div> <label for="username">Username:</label> <input type="text" id="username" name="username" <a href='https://sangseek.com/sangseeks/require/ko'>require</a>d> </div> <div> <label for="password">Password:</label> <input type="password" id="password" name="password" required> </div> <button type="submit">Login</button> </form></body></html>``` 6. 테스트 및 실행이제 애플리케이션을 실행하고, `/login` 경로로 접근하여 로그인 기능을 테스트할 수 있습니다. 올바른 사용자 이름과 비밀번호를 <a href='https://sangseek.com/sangseeks/입력/ko'>입력</a>하면 인증이 성공하고, 권한에 따라 접근할 수 있는 페이지가 결정됩니다. 결론스프링 시큐리티를 사용하면 인증 및 권한 부여를 간편하게 설정할 수 있습니다. 위의 예제는 기본적인 설정 방법을 보여주지만, 실제 애플리케이션에서는 데이터베이스와 연동하거나 OAuth2, JWT 등을 활용하여 더욱 복잡한 인증 및 권한 부여 로직을 구현할 수 있습니다. 필요에 따라 다양한 기능을 추가하여 보안을 강화하세요.
이용안내
커뮤니티 이용안내
×
- 게시한 게시글로 발생하는 문제는 게시자에게 책임이 있습니다.
- 게시글이 타인/타업체의 저작권을 침해할 경우 모든 책임은 게시자에게 있습니다. 게시자가 모든 손해를 부담해야 합니다.
- 상식닷컴 운영자는 게시자와 상의하지 않고 게시글을 수정 또는 삭제할 수 있습니다.
- 상식닷컴 운영자는 깨끗한 커뮤니티 공간을 만드는 것이 1순위입니다.
수정하기
취소하기