묻고 답해요
131만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
미해결
SecurityConfig 설정 후 return 페이지 무한루프 질문입니다.
다름아니라 SecurityConfig 설정 관련 강의를 들은 후 혼자 만들어보면서 공부할려고 하는 중에 생긴 문제입니다. 해결해볼려고 몇 시간 헤매다 해결이 되지않아 질문합니다. 질문내용문제가 생긴 시점에 만든 파일은 자바 파일은 java > 프로젝트이름 > config > SecurityConfig.javajava > 프로젝트이름 > config > WebMvcConfig.javajava > 프로젝트이름 > controller > IndexController.javahtml 파일은 resources > templates > main > index.html (문제 생긴부분때문에 정상작동여부 확인차 main이란 디렉터리에 넣음) resources > templates > user > loginForm.html resources > templates > loginForm.html (loginForm.html은 위치가 다르게 파일이름은 같지만 문제점이 생겨 똑같은 이름으로 경로만 다르게 해서 2개 만들었으며 내용부분에 다른 부분이라면 페이지에 h1태그안에 로그인1,2 이렇게 글자만 다르게해서 브라우저에서 보일 때 어디 경로에 있는 html이 뜬건지 확인하도록 하였습니다.) 먼저 문제가 생긴 부분이 어떤 부분인지 말하자면 SecurityConfig 에 권한 설정 후 로그인하지 않은 사용자가 권한이 있는 페이지를 요청할 경우 "/login" 페이지로 이동 시키는 부분입니다. 제가 회원가입 뿐만 아니라 게시판, api를 이용한 페이지 이런 부분을 만들어서 보여주고싶은데 이 페이지들이 많아지면 디렉토리로 나눠놓는것이 좋을것같아 templates 밑에 디렉토리를 나누게 되었는데요. resources > templates > user > loginForm.html 을 만들어서 IndexController 에서 // 로그인 페이지 테스트2를 주석처리 후 // 로그인 페이지 테스트1를 주석해제 하고http://localhost:8080/login 를 실행시키면 화면에 "localhost에서 리디렉션한 횟수가 너무 많습니다." 라고 떠서 Sysout에서 확인해보니 url 요청 test1 라고 계속 뜹니다.(=> 이 부분 때문에 무한루프에 빠졌다고 생각하고 있습니다.) 그런데IndexController 에서 // 로그인 페이지 테스트1를 주석처리 후 // 로그인 페이지 테스트2를 주석해제 하고http://localhost:8080/login 를 실행시키면 화면이 정상적으로 작동됩니다. (// 로그인 페이지 테스트1과 // 로그인 페이지 테스트2 다른 부분은 return 부분밖에 없습니다.) 저는 templates 밑에 하위 디렉터리를 만들어서 작업을 계속 하고 싶은데 이 부분 어떻게 해결해야할까요?? 코드는 아래와 같습니다. SecurityConfig import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.Customizer; 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.configurers.CsrfConfigurer; import org.springframework.security.web.SecurityFilterChain; @Configuration // @EnableWebSecurity // 스프링 시큐리티 필터가 스프링 필터체인에 등록 public class SecurityConfig{ @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{ http.csrf(CsrfConfigurer::disable).cors(Customizer.withDefaults()); http.formLogin((formLogin) -> formLogin.loginPage("/login").permitAll().defaultSuccessUrl("/")) .authorizeHttpRequests(authorize -> authorize .requestMatchers("/login").permitAll() // 추가부분 .requestMatchers("/user/**").hasAnyRole("user","center","admin") // /user/** url => user, center, admin 권한이 있는 사용자만 접근 가능 .requestMatchers("/center/**").hasAnyRole("center","admin") // /center/** url => center, admin 권한이 있는 사용자만 접근 가능 .requestMatchers("/admin/**").hasAnyRole("admin") // /center/** url => admin 권한이 있는 사용자만 접근 가능 .anyRequest().permitAll() // 권한을 주지않은 url 이 아니면 접근 허용 ); //.formLogin().loginPage("/login").permitAll().defaultSuccessUrl("/") //.formLogin((formLogin) -> // formLogin.loginPage("/login").permitAll().defaultSuccessUrl("/") // ) // 위에 권한이 접근허용이 되지않은 비회원이 해당 페이지 들어갈 경우 /login 페이지로 이동 return http.build(); } }WebMvcConfig@Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(final ResourceHandlerRegistry registry){ registry.addResourceHandler("/**") .addResourceLocations("classpath:/templates/") .setCacheControl(CacheControl.maxAge(10, TimeUnit.MINUTES)); } }IndexController@Controller public class IndexController { // 메인 페이지 @GetMapping({"","/"}) public String index(){ return "main/index"; } // 로그인 페이지 테스트1 // @GetMapping("/login") // public String login(){ // System.out.println("url 요청 test1"); // return "user/loginForm"; // } // 로그인 페이지 테스트2 @GetMapping("/login") public String login(){ System.out.println("url 요청 test2"); return "loginForm"; } // 권한 설정 Test => Test 후에 지우기 @GetMapping("/user") public @ResponseBody String user(){ return "user"; } @GetMapping("/center") public @ResponseBody String center(){ return "center"; } @GetMapping("/admin") public @ResponseBody String admin(){ return "admin"; } @GetMapping("/join") public @ResponseBody String join(){ return "join"; } @GetMapping("/joinProc") public @ResponseBody String joinProc(){ return "회원가입 완료됨"; } }index.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Dreaming Animal</title> </head> <body> 메인 페이지 </body> </html>templates > user > loginForm.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>로그인</title> </head> <body> <h1>로그인 1</h1> <div> <form> <input type="text" name="username" placeholder="ID"><br> <input type="password" name="password" placeholder="password"><br> <button>로그인</button> </form> </div> </body> </html>templates > loginForm.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>로그인</title> </head> <body> <h1>로그인 2</h1> <div> <form> <input type="text" name="username" placeholder="ID"><br> <input type="password" name="password" placeholder="password"><br> <button>로그인</button> </form> </div> </body> </html>
-
미해결스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술
코틀린 사용자인데 강의 보면서 진행이 가능할까요?
코틀린으로 프로그래밍을 입문했습니다. 자바를 사용할 줄은 모르고 코틀린만 사용이 가능한 상황인데, 코틀린으로 공부가 가능한가요?
-
해결됨[쥬신게임아카데미] 완전 초보자를 위한 게임 C++
32:51초 질문입니다.
int* pInt = new int[2] (1, 2); 가 아니라int* pInt = new int[2] {1, 2} 아닌가요?? 괄호 -> 중괄호 영상이랑 똑같이하면 새 이니셜라이즈 어쩌구 오류가 발생해서요
-
해결됨파이썬/장고로 웹채팅 서비스 만들기 (Feat. Channels) - 기본편
@login_required 장식자를 적용한후에는 로그인을 성공하면 채팅방으로 어떻게 이동을 하는 건가요?
로그인을 하고 난후에 디폴트 주소가 /acconts/profile/ 인데@login_required 장식자를 적용한후에는 로그인을 성공하면 채팅방으로 어떻게 이동을 하는 건가요?채팅창에 있다가 로그아웃 한후 다시 로그인을 하면 profile 페이지로 이동하는데 강의에서는 채팅창으로 리다이렉션이 되는 이유가 궁금합니다.
-
해결됨[코드캠프] 훈훈한 Javascript
선생님 remaining 질문입니다.
제가 타이머 수업 들으면서 const remaining을 const reamaining이라고 입력했는데 오류가 떠서 넘어가지 않던데 const 뒤에 변수명을 입력하는거니까 굳이 remaining이 아니어도 상관 없는거 아닌가요?왜 오류가 뜨는건지 궁금합니다.
-
미해결[리뉴얼] React로 NodeBird SNS 만들기
로그인 401 Error (routes에서 user false, 'Missing credentials')
안녕하세요 선생님 상황)쿠키/세션 전체 로그인 흐름 강좌를 따라해보았는데 로그인을 했을 때 401 에러가 발생하는 상황입니다.시도해본 것)아래 파일들의 로그인과 관련된 코드에 로그를 찍어보았고 이런 결과가 출력 되었습니다.1)LoginForm => onSubmitForm함수에서 email,password찍으면 이메일,비밀번호 출력됨2)reducers/user => loginRequestAction함수에서 data찍으면 이메일만 출력되고 loginAction함수에서는 출력안됨3)sagas/user => logIn함수에서 action.data에 이메일만 출력되고 result는 출력안됨4)user/routes => err는 null, user는 false, info는 { message: 'Missing credentials' }라고 출력됨5)passport/index, passport/local => 출력안됨질문1) reducer와 sagas에서는 원래 비밀번호가 출력이 안되는게 맞나요? 질문2) 만약에 reducer와 sagas에서 원래 비밀번호가 안나오는게 맞다면 어떤 부분에 문제가 있어서 reducer와 saga에서 data 나오는데, routes에서는 users가 false로 나오고 Missing credentials가 나오는건가요?질문3)이 문제를 어떻게 해결하면 좋을까요,,?작성한 코드) 글자수 제한이 있어 로그인 부분만 올립니닷,,!LoginFormimport React, { useCallback, useEffect } from 'react'; import {Form, Input, Button} from 'antd'; import Link from 'next/link'; import styled from 'styled-components'; import {useDispatch, useSelector} from 'react-redux'; import useInput from '../hooks/useInput'; import {loginRequestAction} from '../reducers/user'; const LoginForm = () => { const dispatch = useDispatch(); const {logInLoading, logInError} = useSelector((state) => state.user); const [email, onChangeEmail] = useInput(''); const [password, onChangePassword] = useInput(''); useEffect(() => { if (logInError) { alert(logInError); } }, [logInError]); const onSubmitForm = useCallback(() => { console.log('LoginForm에서 email, password', email, password); //email, password luckyhaejin1@naver.com 1234 dispatch(loginRequestAction(email, password)); },[email, password]); return ( <FormWrapper onFinish={onSubmitForm}> {/* 생략 */} <Button type="primary" htmlType="submit" loading={logInLoading}>로그인</Button> </FormWrapper> ); } reducers/userimport {produce} from 'immer'; export const initialState = { logInLoading: false, //login시도중 logInDone: false, logInError: null, //생략 loginData:{} } export const LOG_IN_REQUEST = 'LOG_IN_REQUEST'; export const LOG_IN_SUCCESS = 'LOG_IN_SUCCESS'; export const LOG_IN_FAILURE = 'LOG_IN_FAILURE'; export const loginAction = (data) => { console.log('reducers loginAction에서 data', data);//로그x return (dispatch) => { setTimeout(() => { dispatch(loginRequestAction()); }, 2000); dispatch(loginRequestAction()); } } export const loginRequestAction = (data) => { console.log('reducers loginRequestAction에서 data', data); //luckyhaejin1@naver.com return { type: LOG_IN_REQUEST, data } } const reducer = (state = initialState, action) => produce(state, (draft) => { switch(action.type){ case LOG_IN_REQUEST: draft.logInLoading = true; draft.logInError = null; draft.logInDone = false; break; case LOG_IN_SUCCESS: draft.logInLoading = false; draft.logInDone = true; draft.me = action.data; break; case LOG_IN_FAILURE: draft.logInLoading = false; draft.logInError = action.error; break; //생략 } }); export default reducer; sagas/userimport axios from 'axios'; import { all, call, delay, fork, put, takeLatest } from 'redux-saga/effects'; import { LOG_IN_FAILURE, LOG_IN_REQUEST, LOG_IN_SUCCESS, } from '../reducers/user'; function logInAPI(data){ return axios.post('/user/login', data); } function* logIn(action) { try { console.log('sagas에서 action.data', action.data);//luckyhaejin1@naver.com const result = yield call(logInAPI, action.data); console.log('sagas에서 logIn함수에서 result', result);//로그x yield put({ type: LOG_IN_SUCCESS, data: result.data, }); } catch(err) { console.error(err); yield put({ type: LOG_IN_FAILURE, data: err.response.data, }); } } function* watchLogIn() { yield takeLatest(LOG_IN_REQUEST, logIn); } export default function* userSaga() { yield all ([ fork(watchLogIn) ]) }routes/userconst express = require('express'); const bcrypt = require('bcrypt'); const {User} = require('../models'); const router = express.Router(); const passport = require('passport'); router.post('/login',(req, res, next)=> { console.log('routes 진입'); passport.authenticate('local',(err, user, info) => { if(err) { console.error(err); return next(err); } if(info) { console.log('routes err', err);//null console.log('routes user', user);//false console.log('routes info', info);//{ message: 'Missing credentials' } return res.status(401).send(info.reason); } return req.login(user,async(loginErr)=> { if(loginErr) { console.log('routes loginErr', loginErr); console.error(loginErr); return next(loginErr); } return res.status(200).json(user); }); })(req, res, next); }); //POST /user/login module.exports = router; passport/indexconst passport = require('passport'); const local = require('./local'); const { User } = require('../models'); module.exports = () => { passport.serializeUser((user,done) => { console.log('serializeUser의 user.id', user.id);//로그x done(null,user.id);//첫번째 인자 에러, 두번째 인자 성공(쿠키와 묶어줄 user아이디만 저장) }); passport.deserializeUser(async(id, done) => { try { const user = await User.findOne({where:{id}}) console.log('deserializeUser의 user', user);//로그x done(null,user); } catch(error) { console.error(error); done(error); } }); local(); };passport/localconst passport = require('passport'); const {Strategy:LocalStrategy} = require('passport-local'); const bcrypt = require('bcrypt'); const {User} = require('../models'); const express = require('express'); const router = express.Router(); router.post('/login', passport.authenticate('local')); module.exports = () => { passport.use(new LocalStrategy({ usernameField: 'email', passwordField: 'password', }, async(email, password, done) => { console.log('Passport LocalStrategy - Start');//로그x try { const user = await User.findOne({ where:{email} }); if(!user) { console.log('Passport LocalStrategy - User not found');//로그x return done(null, false, {reasone: '존재하지 않는 이메일입니다!'}) } const result = await bcrypt.compare(password, user.password); if(result) { console.log('Passport LocalStrategy - Login success');//로그x return done(null, user);//성공에 사용자 정보 넘겨줌 } console.log('Passport LocalStrategy - Incorrect password');//로그x return done(null, false, {reason:'비밀번호가 틀렸습니다.'}); } catch(error) { console.error('Passport LocalStrategy - Error:', error);//로그x return done(error); } })); } 사용중인 OS) macOS Apple M1 Pro설치된 버전) back/Package.json "dependencies": { "passport": "^0.7.0", "passport-local": "^1.0.0", "sequelize": "^6.35.2", "sequelize-cli": "^6.6.2" },
-
미해결문과생도, 비전공자도, 누구나 배울 수 있는 파이썬(Python)!
아나콘다 설치
아나콘다를 설치하는데 64비트 다운로드만 존재하고 32비트 다운로드가 없어요 혹시 강의에서 보여지는 방법 외에 다른 설치 방법이 있나요??
-
해결됨모두의 깃 & 깃허브
sourcetree 스태시 옵션 관련 질문
sourcetree에서 스태시를 하면와 같은 옵션 창이 뜨는데, 각 옵션이 무슨 의미인지 궁금합니다.
-
미해결실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발
TransactionContext 로그가 안 찍히는 이유
학습하는 분들께 도움이 되고, 더 좋은 답변을 드릴 수 있도록 질문전에 다음을 꼭 확인해주세요.1. 강의 내용과 관련된 질문을 남겨주세요.2. 인프런의 질문 게시판과 자주 하는 질문(링크)을 먼저 확인해주세요.(자주 하는 질문 링크: https://bit.ly/3fX6ygx)3. 질문 잘하기 메뉴얼(링크)을 먼저 읽어주세요.(질문 잘하기 메뉴얼 링크: https://bit.ly/2UfeqCG)질문 시에는 위 내용은 삭제하고 다음 내용을 남겨주세요.=========================================[질문 템플릿]1. 강의 내용과 관련된 질문인가요? (예/아니오)2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예/아니오)3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예/아니오)[질문 내용]강의 화면을 보면 TransactionContext 에서" Rolled baxk transaction for test : .."라는 로그가 있는데제 거는 안 찍히면 어떤 문제일까요?
-
미해결김영한의 자바 입문 - 코드로 시작하는 자바 첫걸음
자바란? 7분 컴파일, 디컴파일 질문있습니다
강사님께서 out 폴더에서 디컴파일된 결과를 보여주시고 그 다음에 컴파일 결과인(?) bytecode를 보여주셨는데 이 bytecode는 어디서 확인할 수 있는지 알 수 있을까요 ???
-
해결됨오라클 성능 분석과 인스턴스 튜닝 핵심 가이드
Sequential Acess는 HDD상에서도 Block을 Sequential하게 읽나요?
안녕하세요!강의 Section2의 데이터베이스 IO Access 유형 이해 - Sequential 과 Random Access 에서 헷갈리는 점이 있어서 질문을 남깁니다.Radom access 와 Table Full scan(강의 중 9:00~)에 있는 Table은 실제로는 Block 단위로 저장되어 있을텐데, HDD 상에서도 이 Block이 연속으로 저장되어 있는건가요 ??Random acces는 Hard disk 에서 랜덤하게 접근하기 때문에 disk access time이 더 걸린다고 앞에서 말씀해주셨는데, 만약 hdd상에서 block 위치가 여기저기에 있으면 table full scan도 disk access time이 똑같이 많이 걸리지 않을까 ...싶어서 개념이 헷갈립니다.정리하자면 Sequential 이라는 개념이 물리적인 disk에서도 시퀀셜하게 읽는다는건지..? 궁금합니다
-
미해결
Is Sildalist 120 safe to use?
Sildalist 120, like any medication, should be used under the guidance and prescription of a qualified healthcare professional. The safety of Sildalist 120 depends on various factors, including your overall health, medical history, and potential interactions with other medications you may be taking.Sildalist 120 typically contains two active ingredients: sildenafil citrate (100 mg) and tadalafil (20 mg), both of which are phosphodiesterase type 5 (PDE5) inhibitors used to treat erectile dysfunction (ED). These medications work by increasing blood flow to the penis, helping men achieve and maintain an erection.While these medications can be effective for many individuals, they are not suitable for everyone. Sildalist 120 and Fildena 200 may interact with certain medications, such as nitrates or alpha-blockers, which are commonly prescribed for heart conditions. The combination of these medications can lead to a dangerous drop in blood pressure.Some individuals may be allergic or sensitive to the active ingredients in Sildalist 120, leading to adverse reactions.
-
해결됨김영한의 자바 입문 - 코드로 시작하는 자바 첫걸음
섹션2 변수초기화 질문드립니다 (7분경)
변수를 초기화할 때, int a; 라고 하면 a가 메모리상 어딘가에 할당이 되어야하고, 여기에 어떤 값이 들어가있을지 모른다고 하셨는데... 그러면 모든 메모리는 꽉차있는 상태에서(?) 작업을 할 때 덮어 씌워지는 형태로 할당이 진행되나요 ?? 메모리에 올라가있는 값을 왜 안빼는지도 궁금합니다. 값을 삭제해주지 않으면 더 많은 메모리를 사용해야할 때 빈공간이 어딘지 몰라서 어렵지 않을까요 ??
-
해결됨움짤로 빠르게 배우는 파이썬-아래아한글 자동화 레시피
파라미터 서브 타입 질문드립니다.
안녕하세요 일코님일코님 덕분에 많이 활용하고 있는 학생입니다.다름이 아니라ActionTable에서 파라미터가 있는 경우를 다루는 거까지는 잘 되는것 같지만파라미터의 서브타입 있는 경우가 매우 어렵게 느껴집니다.(강의에서 파라미터를 사용하는 방법까지는 이해가 되었지만 그 이후 서브 타입을 활용한 부분을 보는 예시가 있을까요?)표의 배경색을 바꾸려다 서브타입을 지정해야하는데 이 부분이 잘 안됩니다.
-
미해결따라하면서 배우는 고박사의 유니티 하이퍼캐주얼게임 시리즈 01
ZIGZAG강의중 Start를 Coroutine으로 사용하는 이유가 무엇인가요?
안녕하세요! ZIGZAG 강의를 보던 중 GameController 스크립트와 PlayerController 스크립트에서 IEnumerator로 Start 함수를 사용하는 데, 일반적인 void가 아닌 IEnumerator로 선언하기에 사용하는 이유가 무엇인지 궁금해 질문을 남깁니다.해당 스크립트들에서 Start를 Coroutine으로 선언하는 특별한 이유가 있을까요??
-
해결됨처음하는 파이썬 데이터 분석 (쉽게! 전처리, pandas, 시각화까지 전과정 기본 익히기) [데이터과학 Part1]
pandas 라이브러리로 실제 데이터 전처리하기3 7:40
import pandas as pd df=pd.DataFrame({ '성별':['남','남','남'], '이름':['David','Dave','Dave'], '수학':[100,50,80], '국어':[80,70,60] }) print(df)ㄴㅁㅇ ㅁㅇㄴ이렇게 열과 행이 이쁘게 안맞을때, 이쁘게 딱딱 맞추는건 어떻게 해야하나요?
-
미해결프론트엔드 개발환경의 이해와 실습 (webpack, babel, eslint..)
DefinePlugin 관련; env와 관련하여, (21.06.22 16:15, aloha_jh) 답변포함
DefinePlugin 보고 이런생각이 들었습니다.React.js나 Next.js로 프론트엔드 개발을 할 때, 서버주소를 보통 env || env.develop 등으로 관리했습니다. 강의와 답변을 보기 전에는 이러한 라이브러리 및 프레임워크가 env 파일을 웹팩으로 설정하여 자동으로 불러오게 만들어 주는것이라고 여겼습니다. console.log(process.env.NODE_ENV);설정한 부분을 콘솔에 기록하는 부분의 코드가 동일했기 때문입니다. 그런데 답변을 보니 DefinePlugin과 env 설정이 다른 것으로 보여서 개념상의 차이가 어떤 부분인지 싶어 질문드립니다.
-
미해결김영한의 자바 입문 - 코드로 시작하는 자바 첫걸음
productAdminEx문제를 if문 대신 switch로 풀어보았습니다.
작동은 잘 되는것 같은데 틀린부분이 있으면 피드백 부탁드려도 될까요?개인적으로 break나 continue사용에 부족한 부분이 있을 것 같습니다.
-
미해결
강의교재 p45 find 함수
end = input.find(delimiter, start);p45쪽에 더 빠른 split()부분에서요 저런코드가 있는데요 abcdabc에서 d가 delimiter라고 가정하고 start가 4라고 하면 end는 어떠한 값이 들어가야하는건가요?
-
미해결[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발
Restful api 검색 조건 설계 시 uri 를 어떻게 해야 할까요?
안녕하세요 강사님. 강의 듣다가 Rest api 설계시 궁금한 점이 있어 여쭤봤습니다.rest api 설계 시 조회 부분에서 대부분 업무 로직이 사용자 조건 검색 같은게 많은데요 예를들어 사용자의 나이와 이름 등을 입력 받아 조회하는 등의 검색 조건을 나열해야 한다면 url 설계를 어떻게 해야 할까요?