3 글 보임 - 1 에서 3 까지 (총 3 중에서)
-
글쓴이글
-
2024년 8월 1일 15:54 #128972
도준엽참가자[문제] - 로그인(성공/오류) 다 올바르게 동작/ 마이페이지 잘 뜸 - 강의 Part2 로그인 기능 2 의 auth 값이 null 이 출력됨. 로그인을 성공하고 나서도 null 출력. 로그인 하지 않고 바로 주소창에서 /my-page 로 접근해도 마찬가지입니다.
System.out.println(auth.getName()); System.out.println(auth.isAuthenticated()); .getName() .isAuthenticated() 은 자동완성으로도 안되고 'cannot resolve method 'getName' in Authentication' 이라고 뜹니다. [시도해본 것들] - 게시판 검색 : Spring Security - 구글링 - 수업 초반에 했던 Controller 파일들에 혹시 문제 있나 확인. 가독성 떨어지는 텍스트 복붙 코드 죄송합니다 ㅠㅠ
<hr />
<h1 style="padding-left: 40px;">[MemberController.java]</h1>
package com.app.tmjCommunity.member;
import lombok.RequiredArgsConstructor; import org.apache.tomcat.util.net.openssl.ciphers.Authentication; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping;
@Controller @RequiredArgsConstructor public class MemberController {
private final MemberRepository memberRepository; private final MemberService memberService;
@GetMapping("/register") public String registerPage(){
return "register.html"; }
@GetMapping("/login") public String login(){
return "login.html"; }
@PostMapping("/member") public String addMember(String username, String password, String displayName){
memberService.addMember(username,password,displayName);
return "redirect:/list";
}
@GetMapping("/my-page") public String myPage(Authentication auth){
System.out.println(auth); // System.out.println(auth.getName()); // System.out.println(auth.isAuthenticated());
return "mypage.html"; }
}
<hr />
[MyUserDetailsService.java]
package com.app.tmjCommunity.member;
import lombok.RequiredArgsConstructor; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service;
import java.util.ArrayList; import java.util.List;
@RequiredArgsConstructor @Service public class MyUserDetailsService implements UserDetailsService {
private final MemberRepository memberRepository;
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // DB에서 username을 가진 유저를 찾아와서 // return new User(유저아이디, 비번, 권한) 해주세요
System.out.println("로그인 시도 함수?????"); var result = memberRepository.findByUsername(username); if(result.isEmpty()){ throw new UsernameNotFoundException("그런 아이디 없음"); } var user = result.get(); List<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority("일반유저"));
return new User(user.getUsername(),user.getPassword(),authorities);
}
}
<hr />
<h2>[login.html]</h2>
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link rel="stylesheet" href="/main.css"> </head> <body>
<div th:replace="~{ nav.html::navbar }"></div> <h4>로그인하세요</h4>
<div th:if="${param.error}"> <h4>아이디나 비번 틀림</h4> </div>
<form action="/login" method="POST">
<input name="username"> <input name="password" type="password"> <button type="submit">전송</button>
</form>
</body> </html>
<hr />
<h1>[SecurityConfig.java]</h1>
package com.app.tmjCommunity;
import org.springframework.context.annotation.Bean; 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.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain;
@Configuration @EnableWebSecurity public class SecurityConfig {
@Bean PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); }
@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.csrf((csrf) -> csrf.disable()); http.authorizeHttpRequests((authorize) -> authorize.requestMatchers("/**").permitAll() ); http.formLogin((formLogin) -> formLogin.loginPage("/login") .defaultSuccessUrl("/")
); return http.build(); }
}
<hr />
-
이 게시글은
도준엽에 의해 11 월 전에 수정됐습니다.
-
이 게시글은
-
글쓴이글
3 글 보임 - 1 에서 3 까지 (총 3 중에서)
- 답변은 로그인 후 가능합니다.