강의 내용을 최대한 놓치지 않고 다 작성한 것 같은데 포스트맨에 나오는 내용이 다릅니다.. [22:12:33.504][WARN ][org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver.logException:line207] - Resolved [jakarta.validation.ConstraintDefinitionException: HV000243: Constraint ConSilkTea.SmallRecordServer.common.annotation.ValidEnum references constraint validator type ConSilkTea.SmallRecordServer.core.annotation.ValidEnumValidator, but this validator is defined for constraint type ConSilkTea.SmallRecordServer.core.annotation.ValidEnum.] 이건 로그에 나온겁니다.. 전에 했던 블로그 api랑 충돌이 일어나는 것 같은데 서버 하나당 api는 1개 밖에 사용을 못할까요? 다중으로 사용하고 싶다면 어떻게 변경을 하면 좋을지 몰라 질문 남깁니다
안녕하세요, 강의 너무 잘 보고있습니다. `JwtTokenProvider.kt` 생성 중, 궁금한 것이 있어 질문 남깁니다. createToken에서 signWith에 사용하는 key를 private val key by lazy { Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret)) } yml파일에 쓴 key 그대로 사용하는 것이 아닌, 아래와 같이 한번 더 decode를 거치는 것으로 보여지는데요. signwith를 통해 또 다시 HS256으로 인코딩 하는데, 그 전에 한번 더 디코딩한 키를 넣는 이유가 궁금합니다!
exports.login = (req, res, next) => { passport.authenticate('local', (authError, user, info) => { // 1. 서버 실패 부분 if (authError) { console.error(authError); return next(authError); } if (!user) { return res.redirect(`/?error=${info.message}`); } return req.login(user, (loginError) => { //2. 패스포트 로그인 실패 if (loginError) { console.error(loginError); return next(loginError); } return res.redirect('/'); }); })(req, res, next); }; --------------------- 1번과 2번은 통합테스트 코드로 어떻게 테스트 코드를 작성해야 하는지 여쭤봐도 될까요? 1번은 try - catch 로 어떻게 해보려해도 생각이 안나용 2번은 아애 생각이 안납니다 ㅜㅜ controllers를 자체를 단위테스트를 하는 것이 아니라 분기마다 test를 작성하라고 하신 말씀에 이 부분은 통합테스트로 코드를 짤 수 있나 의문이 들어서요! 감사합니다
7.5 시퀄라이즈 사용하기 강좌 부분입니다.피피티와 동일하게 작성했는데 sync에러가 자꾸 뜹니다. 어떻게 고쳐야할지 모르겠습니다. app.js const express = require('express'); const path = require('path'); const morgan = require('morgan'); const nunjucks = require('nunjucks'); const { sequelize } = require('./models'); const app = express(); app.set('port', process.env.PORT || 3001); app.set('view engine', 'html'); nunjucks.configure('views', { express: app, watch: true, }); sequelize.sync({ force: false }) .then(() => { console.log('데이터베이스 연결 성공'); }) .catch((err) => { console.error(err); }); app.use(morgan('dev')); app.use(express.static(path.join(__dirname, 'public'))); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use((req, res, next) => { const error = new Error(`${req.method} ${req.url} 라우터가 없습니다.`); error.status = 404; next(error); }); app.use((err, req, res, next) => { res.locals.message = err.message; res.locals.error = process.env.NODE_ENV !== 'production' ? err : {}; res.status(err.status || 500); res.render('error'); }); app.listen(app.get('port'), () => { console.log(app.get('port'), '번 포트에서 대기 중'); }); index.js const Sequelize = require('sequelize'); const env = process.env.NODE_ENV || 'development'; const config = require('../config/config')[env]; const db = {}; const sequelize = new Sequelize(config.database, config.username, config.password, config); db.seqelize = sequelize; module.exports = db; error ->[nodemon] restarting due to changes...[nodemon] starting node app.js C:\Users\jyoun\udr_node\lecture\app.js:15sequelize.sync({ force: false }) ^TypeError: Cannot read properties of undefined (reading 'sync') at Object.<anonymous> (C:\Users\jyoun\udr_node\lecture\app.js:15:11) at Module._compile (node:internal/modules/cjs/loader:1241:14) at Module._extensions..js (node:internal/modules/cjs/loader:1295:10) at Module.load (node:internal/modules/cjs/loader:1091:32) at Module._load (node:internal/modules/cjs/loader:938:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:83:12) at node:internal/main/run_main_module:23:47Node.js v20.7.0[nodemon] app crashed - waiting for file changes before starting... [제로초 강좌 질문 필독 사항입니다] 질문에는 여러분에게 도움이 되는 질문과 도움이 되지 않는 질문이 있습니다. 도움이 되는 질문을 하는 방법을 알려드립니다. https://www.youtube.com/watch?v=PUKOWrOuC0c 0. 숫자 0부터 시작한 이유는 1보다 더 중요한 것이기 때문입니다. 에러가 났을 때 해결을 하는 게 중요한 게 아닙니다. 왜 여러분은 해결을 못 하고 저는 해결을 하는지, 어디서 힌트를 얻은 것이고 어떻게 해결한 건지 그걸 알아가셔야 합니다. 그렇지 못한 질문은 무의미한 질문입니다. 1. 에러 메시지를 올리기 전에 반드시 스스로 번역을 해야 합니다. 번역기 요즘 잘 되어 있습니다. 에러 메시지가 에러 해결 단서의 90%를 차지합니다. 한글로 번역만 해도 대부분 풀립니다. 그냥 에러메시지를 올리고(심지어 안 올리는 분도 있습니다. 저는 독심술사가 아닙니다) 해결해달라고 하시면 아무런 도움이 안 됩니다. 2. 에러 메시지를 잘라서 올리지 않아야 합니다. 입문자일수록 에러메시지에서 어떤 부분이 가장 중요한 부분인지 모르실 겁니다. 그러니 통째로 올리셔야 합니다. 3. 코드도 같이 올려주세요. 다만 코드 전체를 다 올리거나, 깃헙 주소만 띡 던지지는 마세요. 여러분이 "가장" 의심스럽다고 생각하는 코드를 올려주세요. 4. 이 강좌를 바탕으로 여러분이 응용을 해보다가 막히는 부분, 여러 개의 선택지 중에서 조언이 필요한 부분, 제 경험이 궁금한 부분에 대한 질문은 대환영입니다. 다만 여러분의 회사 일은 질문하지 마세요. 5. 강좌 하나 끝날 때마다 남의 질문들을 읽어보세요. 여러분이 곧 만나게 될 에러들입니다. 6. 위에 적은 내용을 명심하지 않으시면 백날 강좌를 봐도(제 강좌가 아니더라도) 실력이 늘지 않고 그냥 코딩쇼 관람 및 한컴타자연습을 한 셈이 될 겁니다.
- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요. 안녕하세요 선생님의 시큐리티 강의 열심히 듣고있는 학생입니다! 다름이 아니라 시큐리티 oauth 설정 중 scope를 왜 처리하는 지 알고싶습니다.. scope 설정을 해야만 PrincipalOauth2UserService에 접근하여 이 함수를 리턴해주더라고용.. 설정을 안할 시에는 접근하지 못합니다..ㅠ 혹시 무슨 이유인지 알 수 있을까요..?
시큐리티 9강 강의 중 constructor using field 후 아래 같은 오류가 뜹니다. Description: The dependencies of some of the beans in the application context form a cycle: ┌─────┐ | securityConfig (field private com.example.demo.oauth.PrincipalOauth2UserService com.example.demo.config.SecurityConfig.principalOauth2UserService) ↑ ↓ | principalOauth2UserService (field private org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder com.example.demo.oauth.PrincipalOauth2UserService.bCyBCryptPasswordEncoder) └─────┘ Action: Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true.
PS C:\Users\SDS\Downloads\saju-backend-nodejs> npm run dev > saju-backend-nodejs@1.0.0 dev > nodemon server [nodemon] 2.0.16 [nodemon] to restart at any time, enter rs [nodemon] watching path(s): . [nodemon] watching extensions: js,mjs,json [nodemon] starting node server.js C:\Users\SDS\Downloads\saju-backend-nodejs\node_modules\@slack\webhook\dist\IncomingWebhook.js:15 throw new Error('Incoming webhook URL is required'); ^ Error: Incoming webhook URL is required at new IncomingWebhook (C:\Users\SDS\Downloads\saju-backend-nodejs\node_modules\@slack\webhook\dist\IncomingWebhook.js:15:19) at Object.<anonymous> (C:\Users\SDS\Downloads\saju-backend-nodejs\app\commons\slack.js:2:17) at Module._compile (node:internal/modules/cjs/loader:1256:14) at Module._extensions..js (node:internal/modules/cjs/loader:1310:10) at Module.load (node:internal/modules/cjs/loader:1119:32) at Module._load (node:internal/modules/cjs/loader:960:12) at Module.require (node:internal/modules/cjs/loader:1143:19) at require (node:internal/modules/cjs/helpers:121:18) at Object.<anonymous> (C:\Users\SDS\Downloads\saju-backend-nodejs\server.js:7:15) at Module._compile (node:internal/modules/cjs/loader:1256:14) Node.js v18.17.1 [nodemon] app crashed - waiting for file changes before starting...
영상에서는 sequelize 공식문서에서 바뀌어서 따라갔다고 하는데 공식문서에서 initiate() 쓰는 것 검색하였을 때 안보이며 static이랑 같이 쓴 것도 아직은 못찾았습니다 공식문서 따라가보면 주로 define(), init()을 쓰는데 강의영상의 방식과는 차이점이 있습니다. define() const { Sequelize, DataTypes } = require('sequelize'); const sequelize = new Sequelize('sqlite::memory:'); const User = sequelize.define('User', { // Model attributes are defined here firstName: { type: DataTypes.STRING, allowNull: false }, lastName: { type: DataTypes.STRING // allowNull defaults to true } }, { // Other model options go here }); // `sequelize.define` also returns the model console.log(User === sequelize.models.User); // true init() // Invalid class User extends Model { id; // this field will shadow sequelize's getter & setter. It should be removed. otherPublicField; // this field does not shadow anything. It is fine. } User.init({ id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true } }, { sequelize }); const user = new User({ id: 1 }); user.id; // undefined 강의에서 알려주는 방식으로 DB연결도 되고 조작도 잘되지만 이렇게 질문을 남긴 이유는 강의에서는 공식문서를 따라갔다고 하는데 공식문서에서는 찾기 어렵다는 점과 강의에 나오는 방식이 시기가 지난 방법이 아닐까 하는 생각에 질문 남기게 되었습니다 제가 찾아본게 잘못된걸수도 있기에 그런점 있다면 알려주세요 글읽어주셔서 고맙습니다:)
spring security 3.1.5 버전 방식입니다. 기존에 implement 하지 않고 클래스를 @configuration 해서 구성 파일로 인식하게 만들고 해당 메서드를 @bean 을 주입시켜 사용하는 방식입니다. 처음 참조할 부분은 여기를 참조 하시면 됩니다. 처음 설정 방법 :: 3.1.5 방법 1 SecurityConfig::SecurityFilterChain 메서드를 수정하기 @Bean public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception { httpSecurity .csrf(AbstractHttpConfigurer::disable) .exceptionHandling((handling) -> handling.authenticationEntryPoint(jwtAuthenticationEntryPoint) .accessDeniedHandler(jwtAccessDeniedHandler) ) .headers((header) -> header.frameOptions( HeadersConfigurer.FrameOptionsConfig::sameOrigin ) ) .authorizeHttpRequests((registry) -> registry.requestMatchers("/api/hello").permitAll() .requestMatchers("/api/authentication").permitAll() .requestMatchers("/api/signup").permitAll() .anyRequest().authenticated() ); return httpSecurity.build(); } 방법 2 JwtSecurityConfig에 메서드를 하나 추가 한다. public HttpSecurity configureAndReturn(HttpSecurity httpSecurity) { httpSecurity.addFilterBefore( new JwtFilter(tokenProvider), UsernamePasswordAuthenticationFilter.class ); return httpSecurity; } SecurityConfig::SecurityFilterChain 메서드를 수정하기 @Bean public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception { return new JwtSecurityConfig(tokenProvider).configureAndReturn( httpSecurity .csrf(AbstractHttpConfigurer::disable) .exceptionHandling((handling) -> handling.authenticationEntryPoint(jwtAuthenticationEntryPoint) .accessDeniedHandler(jwtAccessDeniedHandler) ) .headers((header) -> header.frameOptions( HeadersConfigurer.FrameOptionsConfig::sameOrigin ) ) .authorizeHttpRequests((registry) -> registry.requestMatchers("/api/hello").permitAll() .requestMatchers("/api/authentication").permitAll() .requestMatchers("/api/signup").permitAll() .anyRequest().authenticated() ) ).build(); } 개인적으로는 방법 1이 깔끔하다고 느낍니다.
저처럼 버전 안 맞춰서 안되는 분들 이걸로 해결해보세요. 문서 참조해서 지원 중단된 방식은 제외하고 설정했습니다. @Configuration @EnableWebSecurity @EnableMethodSecurity public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception { return httpSecurity .csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests((registry) -> registry.requestMatchers("/api/hello").permitAll() .anyRequest().authenticated() ) .build(); } } 어노테이션에 꼭 @Configuration 이 들어가야 설정 파일로 인식해 제대로 작동합니다. 빼먹으시면 안됩니다.