728x90
pom.xml에 라이브러리 등록하기
<!-- 이하 생략 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- 이하 생략 -->
인터페이스 AuthenticationProvider 구현한 클래스 생성
@Component
@RequiredArgsConstructor
public class DBConnectionProvider implements AuthenticationProvider{
private final MemberMapper dao;
private final BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
//authentication이 입력한 id,password를 가져옴
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String userId=authentication.getName();
String password=(String)authentication.getCredentials();
Member loginMember=dao.selectMemberById(userId);
//로그인 실패
if(loginMember==null||!encoder.matches(password, loginMember.getPassword()))
throw new BadCredentialsException("인증실패");
//로그인객체 비밀번호 권한
return new UsernamePasswordAuthenticationToken(loginMember, loginMember.getPassword(),loginMember.getAuthorities());
}
@Override
public boolean supports(Class<?> authentication) {
// TODO Auto-generated method stub
return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
}
}
Security Configuration 클래스 생성
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
//DBConnectionProvider 의존 주입
private final DBConnectionProvider dbprovider;
//SecurityFilterChain클래스를 bean으로 등록
@Bean
SecurityFilterChain authenticationPath(HttpSecurity http) throws Exception{
return http
.csrf(csrf->csrf.disable())
.authorizeHttpRequests(request->{
request.requestMatchers("/").permitAll()
.requestMatchers("/WEB-INF/views/**").permitAll()
.requestMatchers("/members").hasAnyAuthority(MyAuthority.ADMIN.name())
//어떤 것이든 권한이 있어야 한다는 메소드(권한체크) 맨마지막에 위치
.anyRequest().authenticated();
})
.formLogin(formlogin->{
formlogin.loginProcessingUrl("/logintest");
//인증실패 URL
//.failureForwardUrl("/loginfail")
//.successForwardUrl("/loginsuccess");
})
.logout(logout->logout.logoutUrl("/logout"))
//인증에 관한 것
.authenticationProvider(dbprovider)
.build();
}
}
DTO 클래스에 인터페이스 UserDetails 구현
public class Member implements UserDetails{
private String userId;
private String password;
private String name;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<GrantedAuthority> auth=new ArrayList<>();
// auth.add(new SimpleGrantedAuthority("USER"));
// if(userId.equals("admin")) {
// auth.add(new SimpleGrantedAuthority("ADMIN"));
// }
auth.add(new SimpleGrantedAuthority(MyAuthority.USER.name()));
if(userId.equals("admin")) {
auth.add(new SimpleGrantedAuthority(MyAuthority.ADMIN.name()));
}
return auth;
}
@Override
public String getUsername() {
// TODO Auto-generated method stub
return this.userId;
}
@Override
public boolean isAccountNonExpired() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean isAccountNonLocked() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean isCredentialsNonExpired() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean isEnabled() {
// TODO Auto-generated method stub
return true;
}
}
'스프링' 카테고리의 다른 글
Spring, SpringBoot의 특징 (0) | 2024.01.22 |
---|---|
sql.Date 와 util.Date의 차이 (0) | 2024.01.06 |
스프링부트(Spring Boot) MyBatis 사용하기 (0) | 2023.12.21 |
WebSocket 채팅 구현 (0) | 2023.12.18 |
ajax 응답/처리 (0) | 2023.12.14 |