• 로그인
  • 장바구니에 상품이 없습니다.

home2 게시판 Spring 게시판 auth 값 null 출력

auth 값 null 출력

3 글 보임 - 1 에서 3 까지 (총 3 중에서)
  • 글쓴이
  • #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 파일들에 혹시 문제 있나 확인.
    
    가독성 떨어지는 텍스트 복붙 코드 죄송합니다 ㅠㅠ
     Q5
    Q5-2
    

    <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 월 전에 수정됐습니다.
    #128974

    도준엽
    참가자
    아 해결했습니다.
    
    아 ㅋ ㅋ ㅋ ㅋ ㅋ
    
    import 를 잘못했나 봅니다. 이거 너무 하  ㅋㅋ ㅋ ㅋ
    
    [잘못된 Authentication import]
    
    Q5-3
    
    
    [맞는 Authentication import]
    Q5-4
    
    
    
    [잘됨]
    Q5-5
    
    
    [import 할 때 주의하자]
    Q5-6
    
    
    
    
    
    
    #134799

    양상건
    참가자
    ㅎㅎ 덕분에 저도 해결했네요 올려주셔서 감사해요!
3 글 보임 - 1 에서 3 까지 (총 3 중에서)
  • 답변은 로그인 후 가능합니다.

About

현재 월 700명 신규수강중입니다.

  (09:00~20:00) 빠른 상담은 카톡 플러스친구 코딩애플 (링크)
  admin@codingapple.com
  이용약관
ⓒ Codingapple, 강의 예제, 영상 복제 금지
top

© Codingapple, All rights reserved. 슈퍼로켓 에듀케이션 / 서울특별시 강동구 고덕로 19길 30 / 사업자등록번호 : 212-26-14752 온라인 교육학원업 / 통신판매업신고번호 : 제 2017-서울강동-0002 호 / 개인정보관리자 : 박종흠