묻고 답해요
131만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
미해결Spring Boot JWT Tutorial
유효한 JWT 토큰이 없습니다
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(signIn.userId(), registerUser(signIn.password())); Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken); SecurityContextHolder.getContext().setAuthentication(authentication); String jwt = tokenProvider.createToken(authentication); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add(JwtFilter.AUTHORIZATION_HEADER, "Bearer " + jwt); 위 코드에서 [authentication] 부분에 아래와 같은 오류가 발생합니다.org.springframework.security.authentication.BadCredentialsException: 자격 증명에 실패하였습니다. 어떻게 처리하면 되는지 잘 모르겠습니다... 이 문제에 대해 아시는 분들은 저에게 도움 부탁드립니다 ㅜㅜ
-
미해결따라하며 배우는 NestJS
컨트롤러에선 async/await 사용하지 않아도 되는 이유
서비스에서 async/await을 사용하는데컨트롤러에서는 사용하지 않아도 되는것이 의문입니다. express 환경에서는 컨트롤러까지 비동기처리를 해야데이터가 잘 넘겨졌던걸로 기억해서nestjs의 기능인가 싶어서 질문드립니다!
-
해결됨스프링부트 시큐리티 & JWT 강의
UsernamePasswordAuthenticationToken 질문 !
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()); 여기서 사용한 Token 은 그저 로그인 정보를 담아서 authenticationManager에 담기 위한 토큰인가요 ??
-
해결됨스프링부트 시큐리티 & JWT 강의
JWT SecurityConfig.java에서 .and() deprecated
Spring Boot 3.0.0에서 최신판인 Spring Boot 3.1.2로 업데이트 되면서Spring Security도 6.1.2로 업데이터 되었습니다.이에 따라서 강사님 github - Version3 branch에 있던 프로젝트의 SecurityConfig.java에서중간중간에 .and()로 묶어주신 부분도 .and()가 deprecated 되면서 사용할 수 없게 되었습니다.이에 따라 // 이전 생략 return http.csrf(CsrfConfigurer::disable) .sessionManagement(s->s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .formLogin(f->f.disable()) .httpBasic(h->h.disable()) .apply(new MyCustomDs1()) // custom Filter .authorizeHttpRequests(authorize-> { // 권한 부여 // authorizeRequests가 deprecated됨에 따라 authorizeHttpRequests 사용 권장 authorize .requestMatchers("/api/v1/user/**").hasAnyRole("hasRole('ROLE_USER') or hasRole('ROLE_MANAGER') or hasRole('ROLE_ADMIN')") .requestMatchers("/api/v1/manager/**").hasAnyRole("hasRole('ROLE_MANAGER') or hasRole('ROLE_ADMIN')") .requestMatchers(("/api/v1/admin/**")).hasAnyRole("hasRole('ROLE_ADMIN')") .anyRequest().permitAll(); });apply(new MyCustomDs1()) 이후에 authorizeRequest 메소드를 람다식으로 변환시켜서 이어줄려고 하는데, 위 캡쳐 이미지와 같이 에러가 떴습니다.내용을 보자 하니 http에 custom Filter(new MyCustomDs1())를 apply시키고 이후에 authorizeHttpRequests를 실행시켜야 하는데, authorizeHttpRequest가 MyCustomDs1 내부에 있는 함수로 인식하는거 같은데,, 어떻게 해결해야 하는지 방법을 공유해주시면 감사하겠습니다.
-
해결됨스프링부트 시큐리티 & JWT 강의
JwtAuthorizationFilter에서 오류가 뜹니다.
안녕하세요.. 저는 spring legacy 로 jwt를 구현했습니다.로그인 기능까지는 되었는데 인증과정에서 질문이 있습니다.@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("인증이나 권한이 필요한 주소 요청이 됨."); String header = request.getHeader(JwtProperties.HEADER_STRING); System.out.println("jwtHeader : " + header); // header 유무 확인 if (header == null || !header.startsWith(JwtProperties.TOKEN_PREFIX)) { chain.doFilter(request, response); // 필터를 타겟에 넘겨버리고 리턴 return; } // JWT 토큰 검증 String token = request.getHeader(JwtProperties.HEADER_STRING) .replace(JwtProperties.TOKEN_PREFIX, ""); System.out.println(token); String username = JWT.require(Algorithm.HMAC256(JwtProperties.SECRET)).build() .verify(token).getClaim("username").asString(); System.out.println("토큰 검증 완료");위의 코드는 JwtAuthorizationFilter에 있는 doFilterInternal 입니다.header 까지는 잘 들어오는데 알고리즘이 자꾸 맞지 않는다고 합니다.. 포스트맨으로 테스트할 때 login 후 header 값을 복사해 인증이 필요한 페이지에 접근할 때 header에 넣어주었습니다.. 제가 뭘 잘못한 건지 잘 모르겠습니다...ㅠㅠ
-
미해결[초급] 찍어먹자! 코틀린과 Spring Security + JWT로 회원가입 만들기
2.5강에서 포스트맨 오류와 전에 실습한 내용에 대해 질문 드립니다
강의 내용을 최대한 놓치지 않고 다 작성한 것 같은데 포스트맨에 나오는 내용이 다릅니다..[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개 밖에 사용을 못할까요?다중으로 사용하고 싶다면 어떻게 변경을 하면 좋을지 몰라 질문 남깁니다
-
미해결[초급] 찍어먹자! 코틀린과 Spring Security + JWT로 회원가입 만들기
TokenProvider의 Key 관련하여 질문이 있습니다.
안녕하세요, 강의 너무 잘 보고있습니다.`JwtTokenProvider.kt` 생성 중, 궁금한 것이 있어 질문 남깁니다. createToken에서 signWith에 사용하는 key를 private val key by lazy { Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret)) }yml파일에 쓴 key 그대로 사용하는 것이 아닌, 아래와 같이 한번 더 decode를 거치는 것으로 보여지는데요. signwith를 통해 또 다시 HS256으로 인코딩 하는데, 그 전에 한번 더 디코딩한 키를 넣는 이유가 궁금합니다!
-
미해결[개정3판] Node.js 교과서 - 기본부터 프로젝트 실습까지
서버 실패시, 패스포트 로그인 실패시 통합테스트 방법
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를 작성하라고 하신 말씀에 이 부분은 통합테스트로 코드를 짤 수 있나 의문이 들어서요! 감사합니다
-
미해결[개정3판] Node.js 교과서 - 기본부터 프로젝트 실습까지
7.5 시퀄라이즈 사용하기 에러
7.5 시퀄라이즈 사용하기 강좌 부분입니다.피피티와 동일하게 작성했는데 sync에러가 자꾸 뜹니다. 어떻게 고쳐야할지 모르겠습니다. app.jsconst 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.jsconst 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.jsC:\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=PUKOWrOuC0c0. 숫자 0부터 시작한 이유는 1보다 더 중요한 것이기 때문입니다. 에러가 났을 때 해결을 하는 게 중요한 게 아닙니다. 왜 여러분은 해결을 못 하고 저는 해결을 하는지, 어디서 힌트를 얻은 것이고 어떻게 해결한 건지 그걸 알아가셔야 합니다. 그렇지 못한 질문은 무의미한 질문입니다.1. 에러 메시지를 올리기 전에 반드시 스스로 번역을 해야 합니다. 번역기 요즘 잘 되어 있습니다. 에러 메시지가 에러 해결 단서의 90%를 차지합니다. 한글로 번역만 해도 대부분 풀립니다. 그냥 에러메시지를 올리고(심지어 안 올리는 분도 있습니다. 저는 독심술사가 아닙니다) 해결해달라고 하시면 아무런 도움이 안 됩니다.2. 에러 메시지를 잘라서 올리지 않아야 합니다. 입문자일수록 에러메시지에서 어떤 부분이 가장 중요한 부분인지 모르실 겁니다. 그러니 통째로 올리셔야 합니다.3. 코드도 같이 올려주세요. 다만 코드 전체를 다 올리거나, 깃헙 주소만 띡 던지지는 마세요. 여러분이 "가장" 의심스럽다고 생각하는 코드를 올려주세요.4. 이 강좌를 바탕으로 여러분이 응용을 해보다가 막히는 부분, 여러 개의 선택지 중에서 조언이 필요한 부분, 제 경험이 궁금한 부분에 대한 질문은 대환영입니다. 다만 여러분의 회사 일은 질문하지 마세요.5. 강좌 하나 끝날 때마다 남의 질문들을 읽어보세요. 여러분이 곧 만나게 될 에러들입니다.6. 위에 적은 내용을 명심하지 않으시면 백날 강좌를 봐도(제 강좌가 아니더라도) 실력이 늘지 않고 그냥 코딩쇼 관람 및 한컴타자연습을 한 셈이 될 겁니다.
-
미해결지금 당장 NodeJS 백엔드 개발 [사주 만세력]
혹시 season과 seasonStartTime 이 있는 경우에 앱마다 다른 이유
season과 seasonStartTime이 있는 경우에 앱마다 사주팔자가 다르게 나옵니다. 이거 이유가 뭘까요?saju.day는 아래와 같은데 다른 앱들 모두 다 다릅니다.
-
미해결스프링부트 시큐리티 & JWT 강의
구글 oauth 사용 중 궁금한 것.
- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요.안녕하세요 선생님의 시큐리티 강의 열심히 듣고있는 학생입니다! 다름이 아니라 시큐리티 oauth 설정 중 scope를 왜 처리하는 지 알고싶습니다.. scope 설정을 해야만 PrincipalOauth2UserService에 접근하여 이 함수를 리턴해주더라고용.. 설정을 안할 시에는 접근하지 못합니다..ㅠ혹시 무슨 이유인지 알 수 있을까요..?
-
미해결스프링부트 시큐리티 & JWT 강의
JWT방식에서 세션미사용
안녕하세요.강의중에 궁금사항이 있어서 질문드립니다. JWT방식으로 스프링시큐리티 진행중에 JwtAuthenticationFilter attemptAuthentication()에서 권한처리를 편하게하려고 return authentication; 하여 세션을 이용하셨습니다. 원래 JWT방식은 세션을 사용하지않아도된다고 하셨습니다.여기서 세션을 사용하지않으려면 return null로 하면될까요?return null로 하였더니 successfulAuthentication()가 실행되지않아 토큰 발행이 안되는데, 토큰발행부분을 attemptAuthentication()쪽으로 옮겨하는건지, 애초에 successfulAuthentication가 왜 실행되지않았는지 궁금합니다. return을 함으로써 authentication객체가 session영역에 저장된다고 설명하셨는데, session영역을 미사용하려면 어떻게 짜야하나요?
-
해결됨스프링부트 시큐리티 & JWT 강의
9강 구글 로그인 오류
시큐리티 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.
-
미해결지금 당장 NodeJS 백엔드 개발 [사주 만세력]
운세박사 같은 게 훨씬 정확하네요
운세박사 같은 게 훨~~~씬 더 정확한 것 같네요 https://aifortunedoctor.com/saju AI로 내 사주 진짜 잘 봐주네요 정확도 99%인 것 같은데
-
미해결지금 당장 NodeJS 백엔드 개발 [사주 만세력]
API접속이 안 됩니다.
Node js는 정상적으로 실행되었습니다.API POSTMAN 호출시 다음 에러가 발생합니다.Frontend를 실행시켜서 해 봐도 동일한 에러입니다.
-
미해결[개정3판] Node.js 교과서 - 기본부터 프로젝트 실습까지
NODE로 프로그램을 WINDOW 설치 프로그램으로 만들고싶습니다.
제가 만든 NODEJS 프로그램을 한글처럼 WINDOW 환경에서 통합설치 프로그램 하나만 설치하면 DB, NODE 프로그램이 설치되도록 하고싶은데 어떤 방법이 있고 구글에 어떻게 검색해야 하는지 궁금합니다.
-
미해결스프링부트 시큐리티 & JWT 강의
OAuth 이론
OAuth 이론은 이전강의에서 들으라고 하셨는데 어떤 강의를 말씀하시는 건가요 ?
-
미해결지금 당장 NodeJS 백엔드 개발 [사주 만세력]
백엔드 실행시에 다음 오류가 발생합니다.
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.jsC:\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...
-
해결됨[개정3판] Node.js 교과서 - 기본부터 프로젝트 실습까지
sequelize initiate() 쓰는 방식 최신인지, 공식문서 방법인지 궁금합니다
영상에서는 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); // trueinit()// 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연결도 되고 조작도 잘되지만이렇게 질문을 남긴 이유는강의에서는 공식문서를 따라갔다고 하는데 공식문서에서는 찾기 어렵다는 점과강의에 나오는 방식이 시기가 지난 방법이 아닐까 하는 생각에 질문 남기게 되었습니다 제가 찾아본게 잘못된걸수도 있기에 그런점 있다면 알려주세요글읽어주셔서 고맙습니다:)
-
미해결지금 당장 NodeJS 백엔드 개발 [사주 만세력]
seasonStartTime은 항상 null이 나오는데 원래 그런 것인가요?
항상 이렇게 seasonStartTime은 null이 나오는데 원래 이게 맞는건가요?