반응형
Spring Security를 구현한 페이지입니다.
코드는 깃허브에서 확인하실 수 있습니다.
https://github.com/Heegene/personal_projects/tree/master/spring_security_demo
Heegene/personal_projects
personal project repository mostly with Spring framework - Heegene/personal_projects
github.com
<개발 환경>
개발언어: Java8
WAS: Apache Tomcat 9.0.37(Spring boot 내장 Tomcat)
프레임워크: Spring Boot 2.3.3
빌드: Gradle
<디렉터리 구조>
<구현 기능>
Spring Security를 이용한 회원가입/로그인/로그아웃/마이페이지/관리자 페이지
-. Anonymous상태에서의 회원가입 및 로그인
-> 이때, 비밀번호는 Spring Security에 의해 암호화되어 저장됩니다.
-. admin 계정 로그인
-> admin으로 로그인할 경우, admin 페이지 접근 권한이 생겨납니다.
-. 로그아웃
-> 로그아웃 시 세션이 만료됩니다.
<주요 코드>
memberRepository.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
package com.heegene.secudemo.signuplogin.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.heegene.secudemo.signuplogin.domain.Role;
import com.heegene.secudemo.signuplogin.domain.entity.MemberEntity;
import com.heegene.secudemo.signuplogin.domain.repository.MemberRepository;
import com.heegene.secudemo.signuplogin.dto.MemberDto;
import lombok.AllArgsConstructor;
@Service
@AllArgsConstructor
public class MemberService implements UserDetailsService {
private MemberRepository memberRepository;
@Transactional
public Long joinUser(MemberDto memberDto) { // 회원가입 처리하는 메서드로, 비밀번호 암호화하여 저장
// 비밀번호 암호화
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
memberDto.setPassword(passwordEncoder.encode(memberDto.getPassword()));
return memberRepository.save(memberDto.toEntity()).getId();
}
@Override
public UserDetails loadUserByUsername(String userEmail) throws UsernameNotFoundException {
Optional<MemberEntity> userEntityWrapper = memberRepository.findByEmail(userEmail);
MemberEntity userEntity = userEntityWrapper.get();
List<GrantedAuthority> authorities = new ArrayList<>();
if (("admin@example.com").equals(userEmail)) {
authorities.add(new SimpleGrantedAuthority(Role.ADMIN.getValue()));
// 롤을 부여하는 코드(admin@example.com) 이면 admin 롤 부여
// 회원가입시 롤을 부여할 수 있도록 role entity를 만드렁 매핑해 주는 것이 좋음
} else {
authorities.add(new SimpleGrantedAuthority(Role.MEMBER.getValue()));
}
return new User(userEntity.getEmail(), userEntity.getPassword(), authorities);
// Springsecurity에서 제공하는 userdetails를 구현한 user를 반환함 (매개변수는 순서대로 아이디, 비밀번호, 권한리스트)
}
}
|
cs |
SeruciryConfig.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
package com.heegene.secudemo.signuplogin.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
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;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import com.heegene.secudemo.signuplogin.service.MemberService;
import lombok.AllArgsConstructor;
@Configuration
@EnableWebSecurity
@AllArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private MemberService memberService;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/css/**", "/js/**", "/img/**", "/lib/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
// 페이지 권한 설정
.antMatchers("/admin/**").hasRole("ADMIN") // admin 페이지는 ADMIN 롤이 있는 경우만
.antMatchers("user/myinfo").hasRole("MEMBER") // user/myinfo는 MEMBER 롤이 있는 경우만
.antMatchers("/**").permitAll() // /로 시작하는 건 전체 허용
.and() // 로그인 설정
.formLogin()
.loginPage("/user/login") // 로그인 페이지
.defaultSuccessUrl("/user/login/result") // 성공 시 페이지
.permitAll()
.and() // 로그아웃 설정
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/user/logout")) // 로그아웃 페이지
.logoutSuccessUrl("/user/logout/result") // 로그아웃 성공 시 페이지
.invalidateHttpSession(true) // session invalidate
.and()
// 403 예외처리 핸들링
.exceptionHandling().accessDeniedPage("/user/denied");
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(memberService).passwordEncoder(passwordEncoder());
}
}
|
cs |
반응형
'Developments' 카테고리의 다른 글
Hibernate ddl-auto 설정 (0) | 2020.08.18 |
---|---|
[이럴땐이렇게] Spring boot application.yml 파일 mapping value 에러발생 시 (yaml syntax) (1) | 2020.08.18 |
200811 Spring MVC를 이용한 블로그 시스템 1.0 (0) | 2020.08.11 |
200806 TIL: Spring 예외처리(ExceptionHandler, ControllerAdvice) (0) | 2020.08.06 |
200805 Spring boot를 이용한 일기장 Webapp (0) | 2020.08.04 |