Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- rest api
- HttpMessageConverters
- OAuth2
- JsonSerializer
- @ConfigurationProperties
- AuthenticationPrincipal
- 백준
- 외부설정
- Application Event
- 백기선
- 리소스 서버
- 스프링 부트
- cors
- 리소스핸들러
- 브루트포스
- Spring Security
- 백트래킹
- EnableAutoConfiguration
- 알고리즘
- HATEOAS
- JPA
- Application Argument
- 스프링부트
- Application Runner
- application.properties
- webjar
- WebApplication Type
- 정적 리소스
- @Profile
- 다익스트라
Archives
- Today
- Total
아카이브
[스프링 기반 REST API 개발] 시큐리티 폼 인증 설정하기 본문
configure(HttpSecurity Http) 커스터마이징
- 익명 사용자 사용 활성화
- 폼 인증 방식 활성화
- 기본 로그인 페이지 제공
- 요청에 인증 적용
- /api 이하 모든 GET 요청에 인증이 필요함
- (permitAll()을 사용하여 인증이 필요 없이 익명으로 접근이 가능케 할 수 있음)
- 그밖에 모은 요청도 인증이 필요함
/* filterchain 안에서 거르기*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.anonymous() // 익명사용자 허용
.and()
.formLogin() // 폼 인증
.and()
.authorizeRequests() // 인증요청에 대해서
.mvcMatchers(HttpMethod.GET, "/api/**").authenticated() // /api/* 경로 익명 허용
.anyRequest().authenticated(); // 나머지는 인증이 필요하다
}
PasswordEncoder를 통한 인코딩 패스워드 저장하기 (AccountService.class)
public Account saveAccount(Account account) {
account.setPassword(this.passwordEncoder.encode(account.getPassword()));
return this.accountRepository.save(account);
}
findByUsername() Test 코드 수정하기
@Test
void findByUsername() {
//Given
String username = "jumen@naver.com";
String password = "5215";
Account account = Account.builder()
.email(username)
.password(password)
.roles(Set.of(AccountRole.ADMIN, AccountRole.USER))
.build();
this.accountService.saveAccount(account); // using passwordEncoder
// When
UserDetailsService userDetailsService = accountService;
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
// Then
assertThat(this.passwordEncoder.matches(password, userDetails.getPassword())).isTrue();
}
테스트용 계정을 만드는 ApplicationRunner 추가하기 (AppConfig.class)
@Bean
public ApplicationRunner applicationRunner() {
return new ApplicationRunner() {
@Autowired
AccountService accountService;
@Override
public void run(ApplicationArguments args) throws Exception {
Account account = Account.builder()
.email("knoc5215@naver.com")
.password("5215")
.roles(Set.of(AccountRole.ADMIN, AccountRole.USER))
.build();
accountService.saveAccount(account);
}
};
}
'Spring > 스프링 기반 REST API 개발' 카테고리의 다른 글
[스프링 기반 REST API 개발] 시큐리티 OAuth2 리소스 서버 설정하기 (0) | 2021.01.09 |
---|---|
[스프링 기반 REST API 개발] 시큐리티 OAuth2 인증 서버 설정하기 (0) | 2021.01.09 |
[스프링 기반 REST API 개발] 시큐리티 기본 설정하기 (0) | 2021.01.09 |
[스프링 기반 REST API 개발] Account에 스프링 시큐리티 적용하기 (0) | 2021.01.09 |
[스프링 기반 REST API 개발] Account 도메인 추가 (0) | 2021.01.09 |