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

home2 게시판 Spring 게시판 Authentication 클래스 getPrincipal

Authentication 클래스 getPrincipal

  • 이 주제에는 10개 답변, 2명 참여가 있으며 루니7 월, 1 주 전에 전에 마지막으로 업데이트했습니다.
10 글 보임 - 1 에서 10 까지 (총 11 중에서)
  • 글쓴이
  • #132264

    루니
    참가자
    안녕하세요~
    
    Authentication 클래스로 뽑은 auth에서 getPrincipal()이 안 나오는 문제가 있는데,
    어떻게 해결해야 할지 모르겠습니다.
    알려주시면 감사하겠습니다
    
    
    #132273

    codingapple
    키 마스터
    SecurityConfig파일이나 loadUserByUsername 함수에 이상한거 없나 확인해봅시다
    #132424

    루니
    참가자
    네 확인해보고 있는데 잘 못 찾겠습니다
    죄송하지만, MyUserDetailsService 파일, SecurityConfig 파일 메일로 부탁드리겠습니다.
    
    #132425

    codingapple
    키 마스터
    여기다가 코드 올려주시면 됩니다
    #132446

    루니
    참가자
    MyUserDetailsService
    
    
     package com.daehan.shop.member;
    import lombok.RequiredArgsConstructor;
    import org.springframework.security.core.GrantedAuthority;
    import org.springframework.security.core.authority.SimpleGrantedAuthority;
    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
    //DB에 있던 유저 정보 꺼내기
    @Service
    public class MyUserDetailsService implements UserDetailsService {
        private final MemberRepository memberRepository;
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    //        DB에서 username을 가진 유저를 찾아와서
    //        return new User(유저아이디, 비번, 권한) 해주세요
            var result = memberRepository.findByUsername(username);
            if (result.isEmpty()) {
                throw new UsernameNotFoundException("그런 아이디 없음");
            }
            var user = result.get();
            //System.out.println(user);
            List<GrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority("일반유저"));
            var a = new CustomUser(user.getUsername(), user.getPassword(), authorities);
            a.displayName = user.getDisplayName();
            return a;
        }
    }
    ***********************************************
    SecurityConfig
    
    
     package com.daehan.shop;
    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()
            );
            //나는 form으로 로그인하겠다
            http.formLogin((formLogin) -> formLogin.loginPage("/login")
                    .defaultSuccessUrl("/") //로그인성공
    //                .failureUrl("/fail")
            );
            http.logout(logout -> logout.logoutUrl("/logout"));
            return http.build();
        }
    }
     
    
    
    #132457

    codingapple
    키 마스터
    CustomUser 클래스도 이상한거없습니까 .getPrincipal()한걸 CustomUser 타입으로 바꾸기도 잘했습니까
    #132490

    루니
    참가자
    CustomUser 클래스입니다.
    
    package com.daehan.shop.member;
    import org.springframework.security.core.GrantedAuthority;
    import org.springframework.security.core.userdetails.User;
    import java.util.Collection;
    public class CustomUser extends User {
        public String displayName;
        public CustomUser(String username,
                          String password,
                          Collection<? extends GrantedAuthority> authorities) {
            //복사한 User클래스
            super(username, password, authorities);
        }
    //    public CustomUser(String username,
    //                      String password,
    //                      List<GrantedAuthority> authorities) {
    //        super(username, password, authorities);
    //    }
    }
    
    
    #132499

    codingapple
    키 마스터
    var user = (CustomUser) auth.getPrincipal() 해서 타입변경도 잘해놨습니까
    #132549

    루니
    참가자
    네 하였습니다.
    에러 메시지가 getPrincipal()이 정의 되지 않았다는 에러인듯한데,
    버전이 안 맞아서 이럴수가 있을까요?
    
    ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
    java: cannot find symbol
      symbol:   method getPrincipal()
      location: variable auth of type org.apache.tomcat.util.net.openssl.ciphers.Authentication
    ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
    
    
    package org.apache.tomcat.util.net.openssl.ciphers;
    public enum Authentication {
        RSA    /* RSA auth */,
        DSS    /* DSS auth */,
        aNULL  /* no auth (i.e. use ADH or AECDH) */,
        DH     /* Fixed DH auth (kDHd or kDHr) */,
        ECDH   /* Fixed ECDH auth (kECDHe or kECDHr) */,
        KRB5   /* KRB5 auth */,
        ECDSA  /* ECDSA auth*/,
        PSK    /* PSK auth */,
        GOST94 /* GOST R 34.10-94 signature auth */,
        GOST01 /* GOST R 34.10-2001 */,
        FZA    /* Fortezza */,
        SRP    /* Secure Remote Password */,
        ANY    /* TLS 1.3 */
    }
    #132555

    codingapple
    키 마스터
    Authentication 타입 import해오는 경로가 이상해서그럴수도요
10 글 보임 - 1 에서 10 까지 (총 11 중에서)
  • 답변은 로그인 후 가능합니다.

About

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

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

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