반응형
안녕하세요
오늘은 스프링 시큐리티를 이용한 로그인을 할려합니다.
시작하겠습니다.
1. 우선 의존성 추가 해주셔야합니다.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
추가하시고 기동만 하셔도 아래와 같은 로그인 화면이 나오는데요
보통 아이디는 user
password는 콘솔창에 Using generated security password ~~라고 run 도중 찍혀있습니다. 그거 입력하시면 되요
하지만 저희는 커스텀하여 진행하겠습니다.
SecurityConfig.java
package kr.home.service;
import org.springframework.beans.factory.annotation.Autowired;
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;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@EnableWebSecurity // 1
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{
@Autowired
AuthProvider authProvider;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/css/**", "/js/**", "/img/**").permitAll() //해당 권한없이 접근
.antMatchers("/**/**/**").hasRole("USER") //ROLE_USER 권한을 가진 사람은 접근
.anyRequest().authenticated();
http.formLogin()
.loginPage("/login") // default //로그인view 페이지
.loginProcessingUrl("/authenticate") //로그인 form action url
.failureUrl("/login?error") // default
.defaultSuccessUrl("/home")
.usernameParameter("email") //로그인시 id name값
.passwordParameter("password") // -- pw name값
.permitAll();
http.logout()
.logoutUrl("/logout") // default
.logoutSuccessUrl("/login")
.invalidateHttpSession(true)
.permitAll();
http.authenticationProvider(authProvider);
http.csrf()
.csrfTokenRepository(new CookieCsrfTokenRepository());
}
}
AuthProvider.java
package kr.home.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import kr.home.service.login.service.LoginService;
import kr.home.service.user.vo.UserVO;
@Component
public class AuthProvider implements AuthenticationProvider{
@Autowired
LoginService loginsevice;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String email = authentication.getName();
String password = authentication.getCredentials().toString();
UserVO user = loginsevice.selectUser(email);
// email에 맞는 user가 없거나 비밀번호가 맞지 않는 경우.
if (null == user ) {
System.out.println("없음!");
return null;
}
List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
grantedAuthorityList.add(new SimpleGrantedAuthority("ROLE_USER"));
// 로그인 성공시 로그인 사용자 정보 반환
return new UsernamePasswordAuthenticationToken(user, null, grantedAuthorityList);
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
<body>
<div class="section"></div>
<main>
<div style="text-align:center;">
<img class="responsive-img" style="width: 250px;" src="https://i.imgur.com/ax0NCsK.gif" />
<div class="section"></div>
<div class="section"></div>
<div class="container">
<div class="z-depth-1 grey lighten-4 row" style="display: inline-block; padding: 32px 48px 0px 48px; border: 1px solid #EEE; width: 305px;">
<form class="col s12" method="post" action="<%=request.getContextPath() %>/authenticate">
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
<div class='row'>
<div class='col s12'>
</div>
</div>
<div class='row'>
<div class='input-field col s12'>
<input class='validate' type='email' name='email' id='email' value="<c:out value="${email}"/>">
<label for='email'>이메일</label>
</div>
</div>
<div class='row'>
<div class='input-field col s12'>
<input class='validate' type='password' name='password' id='password' />
<label for='password'>비밀번호</label>
</div>
</div>
<br/>
<div style="text-align:center;">
<div class='row'>
<button type='submit' name='btn_login' class='col s12 btn btn-large waves-effect indigo'>로그인</button>
</div>
</div>
</form>
<form action="<%=request.getContextPath() %>/logout" method="post">
<button type='submit' class='col s12 btn btn-large waves-effect indigo'>로그아웃</button>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</form>
</div>
</div>
<a href="<%=request.getContextPath() %>/join/View">회원가입</a>
</div>
<div class="section"></div>
<div class="section"></div>
</main>
저는 jps를 사용하여서 반드시!! hidden에 보이는 csrf 값 저걸 반드시! 넣어주셔야해요
타임리프 쓰시면 자동생성 되어 보내지는데 jsp는 저렇게 선언하여 보내야합니다 !
반드시! 아니면 403 에러나요!
반응형
'개발 > Spring' 카테고리의 다른 글
[Spring] poi 병목현상 해결! (0) | 2020.11.12 |
---|---|
[Spring] poi를 이용한 excel 다운로드 (0) | 2020.11.06 |
[Spring] 파일 정보를 못가져오는 에러! MultipartFile에 Xss Filter적용 (0) | 2020.10.30 |
[Spring] FCM 을 이용한 비동기 전송 (1) | 2020.09.05 |
[Java] Spring RestTemplate 에서 인증서 유효성 검사 안 함 (0) | 2020.03.27 |