Back-end/java

시큐리티 저장이 안되는 문제..

Nellie Kim 2023. 9. 18. 20:42
728x90

HomeController

    // 4. 로그인 화면
    @GetMapping("/login")
    public String loginForm() {
        return "login";
    }


    // 4. 로그인
    @ResponseBody
    @PostMapping("/loginTest")
    public UserDto login(@RequestBody UserDto userDto) throws UserException {
//        Object a = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println("TEST");
        System.out.println(" 컨트롤러에서 " + userDto.getUsername());
        System.out.println(" 컨트롤러에서 " + userDto.getPassword());
        Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(userDto.getUsername(), userDto.getPassword()));
        SecurityContextHolder.getContext().setAuthentication(authentication);
        UserDetailsImpl principal = (UserDetailsImpl) authentication.getPrincipal();

        System.out.println("authentication = " + authentication);
        System.out.println("authentication.getName() = " + authentication.getName());
        System.out.println("authentication.getAuthorities() = " + authentication.getAuthorities());
        System.out.println("authentication.getDetails() = " + authentication.getDetails());
        System.out.println("authentication.getCredentials() = " + authentication.getCredentials());
        System.out.println("authentication.getPrincipal() = " + authentication.getPrincipal());
        System.out.println("principal = " + principal.getUsername());

        UserDto userDto1 = principal.getUserDto();
        user = userDto1;
        userService.login(userDto);
        System.out.println("유저: "+ user.getUsername());
        return userDto1;
    }

 

 

SecurityConfig

package com.example.first.config;

import com.example.first.service.UserDetailsServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
@RequiredArgsConstructor
@EnableWebSecurity
public class  SecurityConfig extends WebSecurityConfigurerAdapter {
    private final UserDetailsServiceImpl userDetailsService;



    /* 스프링 시큐리티 룰을 무시할 URL 규칙 설정
     * 정적 자원에 대해서는 Security 설정을 적용하지 않음 */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests()

        // 인증 필요시 로그인 페이지와 로그인 성공시 리다이랙팅 경로 지정

        http
                .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/")
                .failureUrl("/login?error=true")
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
                        response.sendRedirect("/login?error=true");
                    }
                })
                .usernameParameter("username")
                .passwordParameter("password")
                .and()
                .userDetailsService(userDetailsService)
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/")
                .and()
                .csrf().disable();

    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }



    // 인코더를 여기에서 빈으로 등록
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }


    // Spring Security에 사용자 인증 정보를 제공하고 비밀번호 인코딩에 사용된다.
//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.userDetailsService(userDetailsService).passwordEncoder(encoder);
//    }
}

 

 

Login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>로그인 화면</title>

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
          integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <style>
        body {
            min-height: 100vh;

            background: -webkit-gradient(linear, left bottom, right top, from(#92b5db), to(#1d466c));
            background: -webkit-linear-gradient(bottom left, #92b5db 0%, #1d466c 100%);
            background: -moz-linear-gradient(bottom left, #92b5db 0%, #1d466c 100%);
            background: -o-linear-gradient(bottom left, #92b5db 0%, #1d466c 100%);
            background: linear-gradient(to top right, #92b5db 0%, #1d466c 100%);
        }

        .input-form {
            max-width: 680px;

            margin-top: 80px;
            padding: 32px;

            background: #fff;
            -webkit-border-radius: 10px;
            -moz-border-radius: 10px;
            border-radius: 10px;
            -webkit-box-shadow: 0 8px 20px 0 rgba(0, 0, 0, 0.15);
            -moz-box-shadow: 0 8px 20px 0 rgba(0, 0, 0, 0.15);
            box-shadow: 0 8px 20px 0 rgba(0, 0, 0, 0.15)
        }
    </style>
</head>

<body>
<div class="container">
    <div class="input-form-backgroud row">
        <div class="input-form col-md-12 mx-auto">
            <h4 class="mb-3">로그인</h4>
            <form name="login_form" class="validation-form" action="/login" method="post">
                <div class="mb-3">
                    <label for="username">이메일</label>
                    <input type="email" class="form-control" id="username" name="username" placeholder="weaver123@example.com" required>
                    <div class="invalid-feedback">
                        이메일을 입력해주세요.
                    </div>
                </div>

                <div class="mb-3">
                    <label for="password">비밀번호</label>
                    <input type="password" class="form-control" id="password" name="password" placeholder="" required>
                    <div class="invalid-feedback">
                        비밀번호를 입력해주세요.
                    </div>
                </div>

                <hr class="mb-4">
                <button class="btn btn-primary btn-lg btn-block" type="button" onclick="loginTest()">로그인</button>
                <div class="mt-3 text-center">
                    <a href="/forgot-password" class="mr-2 text-primary">비밀번호 찾기</a>|&nbsp;
                    <a href="/register" class="text-primary">회원가입</a>
                </div>
            </form>
        </div>
    </div>
    <footer class="my-3 text-center text-small">
        <p class="mb-1">&copy; 2021 Your Company</p>
    </footer>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    // window.addEventListener('load', () => {
    //     const forms = document.getElementsByClassName('validation-form');
    //
    //     Array.prototype.filter.call(forms, (form) => {
    //         form.addEventListener('submit', function (event) {
    //             if (form.checkValidity() === false) {
    //                 event.preventDefault();
    //                 event.stopPropagation();
    //             }
    //
    //             form.classList.add('was-validated');
    //         }, false);
    //     });
    // }, false);


    function loginTest() {
        // document.login_form.submit();


        var username = $('#username').val()
        var password = $('#password').val()

        console.log(username);
        console.log(password);




        // 가져온 정보를 data로 묶기
        let data = {
            "username" : username,
            "password" : password
        }

        // 4. 클라에서 가져온 데이터를 서버로 전송 (이 예시에서는 URL이 '/register'로 가정)
        $.ajax({
            type: 'POST',
            url: '/loginTest',
            data: JSON.stringify(data),
            contentType: 'application/json',
            success: function (response, status, xhr) {
                console.log(response);
                console.log(status);
                console.log(xhr);
                if (xhr.status === 200) {
                    // 서버 응답의 상태 코드가 200일 때만 실행
                    alert(username + '님 환영합니다!');
                    location.href = "/board";
                } else {
                    // 가입 실패 처리
                    alert('서버에서 오류가 발생했습니다.');
                }
            },
            error: function (response, status, xhr) {
                // 서버 요청 실패 시 실행
                console.log('실패했다...')
                console.log(response); //응답 body부 데이터

                alert('서버 요청 실패');
            }
        });

        return true;

        // // 5. 모든 필드가 유효한 경우 폼을 서버로 제출할 수 있습니다.
        // if (isValid) {
        //     $("#registrationForm")[0].submit();
        // }
    }

</script>
</body>

</html>

 

 

이렇게 하는데 저장이 안된다.. ㅜㅜㅜ 왜그럴까ㅜ

 

마이페이지에서 시큐리티에 저장된 사용자 정보를 가져오려고 했는데 오류가 났다.

 

MypageController

package com.example.first.controller;


import com.example.first.dto.UserDto;
import com.example.first.mapper.HomeMapper;
import com.example.first.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;

@RequiredArgsConstructor
@Controller
@Slf4j
@CrossOrigin
public class MypageController {
    private final UserService userService;
    private final HomeMapper homeMapper;

    // 마이페이지 화면
    @GetMapping("/mypage")
    public String mypage(Model model) {
        // 사용자 정보를 가져와 모델에 추가
//        UserDto userDto = userService.getUserInfo(); // UserService에서 현재 사용자 정보를 가져오는 메서드


        UserDto user = homeMapper.findByUsername("yocu1784@naver.com");
//
        // 현재 사용자의 인증 정보 가져오기
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        System.out.println("마이페이지 - authentication = " + authentication);

        // 사용자 이름 가져오기
        String username = authentication.getName();

        UserDto foundUser = homeMapper.findByUsername(username);

        model.addAttribute("username", foundUser.getUsername());
        model.addAttribute("nickname", foundUser.getNickname());
        model.addAttribute("phoneNumber", foundUser.getPhoneNumber());
        model.addAttribute("streetAdr", foundUser.getStreetAdr());
        model.addAttribute("detailAdr", foundUser.getDetailAdr());

//        model.addAttribute("username", user.getUsername());
//        model.addAttribute("name", user.getName());
//        model.addAttribute("nickname", user.getNickname());
//        model.addAttribute("phoneNumber", user.getPhoneNumber());
//        model.addAttribute("streetAdr", user.getStreetAdr());
//        model.addAttribute("detailAdr", user.getDetailAdr());




        System.out.println("마이페이지 - user.getUsername() ==== " + user.getUsername());
        System.out.println("마이페이지 - user.getUsername() ==== " + user.getName());
        System.out.println("마이페이지 - user.getNickname() ==== " + user.getNickname());
        System.out.println("마이페이지 - user.getPhoneNumber() ==== " + user.getPhoneNumber());
        System.out.println("마이페이지 - user.getStreetAdr() ==== " + user.getStreetAdr());
        System.out.println("마이페이지 - user.getDetailAdr() ==== " + user.getDetailAdr());
//        System.out.println("마이페이지 - authentication.getCredentials() ==== " + user.getCredentials());
//        System.out.println("마이페이지 - authentication.getDetails() ==== " + user.getDetails());
//        System.out.println("마이페이지 - authentication.getPrincipal() ==== " + user.getPrincipal());
//        System.out.println("마이페이지 - authentication.getAuthorities() ==== " + user.getAuthorities());
//        System.out.println("마이페이지 - authentication==== " + user);

        // 여기에서 필요한 정보를 세션에서 가져와 모델에 추가하거나 직접 사용할 수 있습니다.
        // 예를 들어, 사용자 이름을 모델에 추가하면 해당 정보를 뷰에서 사용할 수 있습니다.
//        model.addAttribute("username", username);

        return "mypage";
    }


}

 

아래 부분에서 계속 오류가 난다. 

// 현재 사용자의 인증 정보 가져오기
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
System.out.println("마이페이지 - authentication = " + authentication);

// 사용자 이름 가져오기
String username = authentication.getName();

시큐리티 컨텍스트 홀더에 authoration을 저장했는데 왜 못가져오는거지?...ㅠㅠ