Spring Security 로그인구현

Posted by Albert 910Day 15Hour 31Min 7Sec ago [2022-10-22]

오래만에 다시 Spring security 로그인 만들어보려니 변한부분들이 좀 있어 삽질 좀했다.

구현은 spring boot + mariadb + mybatis +spring security 로그인구현

1. maven dependency 추가 

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

2. 테스트 테이블 생성

CREATE TABLE `su_user` (
`username` varchar(100) DEFAULT NULL,
`password` varchar(100) DEFAULT NULL,
`role` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


3. UserVO 파일 생성 db로 부터 가져올 data를 담을 vo

@Data
public class UserVO {
private String username;
private String password;
private String role;
}

4. customeUserDetailService 생성


@Service
@RequiredArgsConstructor
public class customeUserDetailService implements UserDetailsService {

@Autowired
SiteMapper siteMapper;

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

UserVO user = siteMapper.getUserInfo(username);

return new org.springframework.security.core.userdetails.User(
user.getUsername(),
user.getPassword(), true, true, true, true,
getRoles(user.getRole()));
//return user;
}

public Collection<? extends GrantedAuthority> getRoles(String role) {
ArrayList<GrantedAuthority> auth = new ArrayList<GrantedAuthority>();
auth.add(new SimpleGrantedAuthority(role));
return auth;
}


}


5. CustomAuthenticationProvider 생성

public class CustomAuthenticationProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String name = authentication.getName();
String password = authentication.getCredentials().toString();

return new UsernamePasswordAuthenticationToken(name, password, new ArrayList<>());
}

@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(
UsernamePasswordAuthenticationToken.class);
}
}


6. SecurityConfig 파일 생성 (여기에서 주요하게 로그인관련 설정들을 한니 가장 중요한 파일이다)

예전에는  WebSecurityConfigurerAdapter 을 사용하였는데 요즘에는 deprecated 되어 사용권장 하지않는다.

@Configuration
public class SecurityConfig {

@Autowired
public UserDetailsService userDetailsService;

@Bean
public WebSecurityCustomizer configure() {
return (web) -> web.ignoring().mvcMatchers(
"/tag/**"
);
}

@Bean
public DaoAuthenticationProvider authProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService);
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
}

@Bean
public AuthenticationManager authManager(HttpSecurity http) throws Exception {
AuthenticationManagerBuilder authenticationManagerBuilder =
http.getSharedObject(AuthenticationManagerBuilder.class);
authenticationManagerBuilder.authenticationProvider(authProvider());
return authenticationManagerBuilder.build();
}

@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csrf().disable()
.authorizeRequests()
.antMatchers("/abts/**").hasAuthority("ADMIN")
.antMatchers("/**").permitAll()
.and()
.formLogin()
.loginPage("/loginPage")
.loginProcessingUrl("/login")
.defaultSuccessUrl("/")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/").and().build();
}
}


7. 테스트 로그인 계정생성(PasswordEncoder 로 암호화 되어 등록되어 등록하는 서비스 하나 만들어 등록하였다.)

public void createUser() {
String pwd = passwordEncoder.encode("s741852!");
siteMapper.createUser(pwd);
}


8. 로그인 페이지 작성(설정상 /login 할시 로그인 액션처리되니 간단한 테스트라 아래와 같게 하였음)

<form class="login-form" action="/login" method="POST">

<div class="row">
<div class="input-field col s12">
<input id="email" type="text" name="username" class="validate"/>
<label for="email">Email</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="password" type="password" name="password" class="validate"/>
<label for="password">Password</label>
</div>
</div>
<input class="login-btn waves-effect waves-light btn" type="submit" value="로그인" />
</form>


8. 테스트

로그인 전: /admin/** 관리자 페이지에 접근하면 로그인 화면으로 돌아가고 기타 페이지들은

상관없이 접근가능하다.


로그인후: 관리자를 포함된 모든 페이지 접근 가능









LIST

Copyright © 2014 visionboy.me All Right Reserved.