일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- Spring JPA
- python
- 암호화폐시장
- SECS
- 암호화폐규제
- c
- 비트코인
- C++
- 스테이블코인
- CS
- 백준
- 자바
- java
- coins
- spring boot
- programmers
- 파이썬
- 암호화폐
- Digital Marketing
- Investing
- 지브리필터
- ai이미지변환
- SECS/GEM
- Spring
- finance & economics
- Cars
- Gem
- 프로그래머스
- Baekjoon
- 암호화폐투자
Archives
- Today
- Total
비버놀로지
[Spring JPA] 1-11. 회원 가입 : 현재 인증된 사용자 정보 참조 본문
반응형
package com.studyolle.account.controller;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
@AuthenticationPrincipal(expression = "#this == 'anonymousUser' ? null : account")
public @interface CurrentUser {
}
먼저 CurrentUser라는 어노테이션을 사용하기 위해 위와 같은 @interface 객체를 생성해 줍니다.
package com.studyolle.account.controller;
import java.util.List;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import com.studyolle.repository.dto.Account;
import lombok.Getter;
@Getter
public class UserAccount extends User{
private Account account;
public UserAccount(Account account) {
super(account.getNickname(), account.getPassword(),List.of(new SimpleGrantedAuthority("ROLE_USER")));
this.account=account;
}
}
그다음 위와 같이 Spring Security에서 제공하는 user를 이용을 해서 위와 같이 작성을 해줍니다.
public void login(Account account) {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
new UserAccount(account),
account.getPassword(),
List.of(new SimpleGrantedAuthority("ROLE_USER")));
SecurityContextHolder.getContext().setAuthentication(token);
}
이전에 작성했던 AccountService에서 login을 위와 같이 변경해 줍니다.
public class AccountService implements UserDetailsService
그리고 AccountService는 Spring Security에서 제공하는 UserDetailsService를 상속받아서 정의해 줘야 합니다.
@Override
public UserDetails loadUserByUsername(String emailOrNickname) throws UsernameNotFoundException {
Account account = accountRepository.findByEmail(emailOrNickname);
if (account == null) {
account = accountRepository.findByNickname(emailOrNickname);
}
if (account == null) {
throw new UsernameNotFoundException(emailOrNickname);
}
return new UserAccount(account);
}
위의 코드를 서비스에 넣어주어 Spring Security에 로그인을 할 수 있도록 해줍니다.
위와 같이 로그인을 하게되면
위와 같이 닉네임이 나오는 것을 확인할 수 있습니다.
반응형
'LANGUAGE STUDY > Spring' 카테고리의 다른 글
[Spring JPA] 1-13. 회원 가입 : 로그인 기억하기 (0) | 2021.05.04 |
---|---|
[Spring JPA] 1-12. 회원 가입 : 로그인 로그아웃 (0) | 2021.05.04 |
[Spring JPA] 1-10. 회원 가입 : 인증 메일 확인 테스트 (0) | 2021.05.01 |
[Spring JPA] 1-9. 회원 가입 : 인증 메일 확인 (0) | 2021.05.01 |
[Spring JPA] 1-8. 회원 가입 : 패스워드 인코더 (0) | 2021.04.30 |
Comments