묻고 답해요
161만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
미해결스프링 시큐리티 OAuth2
인가서버에 login post요청
안녕하세요?상태 :client server에서 고객 아이디와 비번을 client server controller로 보내서여기서 restTemplate를 이용하여,localhost:8081/oauth2/authorization/springoatuh2로 get mapping하여 login page를 얻어왔습니다.여기서다시 한번 restTemplate을 이용하여 localhost:9000/login 으로post 요청을 하면서 body (multipart/form-data) 에 username, password, _csrf(로그인페이지에 있는) 값을 보내어 access token을 받으려고 하였는데,null을 리턴받았습니다. response header 에 Location은 localhost:9000/login이 되었습니다.이유는 쿠키가 전달되지 않아서 그랬습니다. 그래서, 첫번째 restTemplate으로 부터 받은 response에서쿠키를꺼내서 두번째 restTemplate에 담아서 같이 보냈더니 localhost:9000/으로 response header Location이 잡혔습니다. 그래서, 인가서버에서 다음상황으로 그러니까 client server로 code를 전달해주는 과정으로 넘어가지가 않고 멈추었습니다. 인가서버 log level을 oauth2로 잡고 디버그해보았을때 로그인이 되어있고, redirect uri 가 `/` 로 되어있음도 확인하였습니다. postman으로는 두 요청을 보내었을때 성공적으로 accesstoken을 받았는데,질문 :직접 client server의 controller에서 보낼때는 실패하는 이유가 무엇일까요?뭔가 더 필요한 정보가 있을까요? state, nonce 와 같은 값들을 넣어주어야 할까요?긴글 읽어주셔서 감사합니다.
-
해결됨스프링 시큐리티 OAuth2
마지막 장 front end 에서 리소스 서버 직접 요청
안녕하세요. 선생님어느덧 마지막장이네요.한가지 질문이 있네요.사용자에 대한 엑세스 토큰을 발급 받기 위해 사용자가 로그인 링크를 클릭해서 클라이언트 서버에 로그인 요청하면 클라이언트 서버에서 임시코드를 발급 받기 위한 인가서버 요청 url을 만들어 사용자 브라우저로 redirect 하고, 인가서버의 로그인 화면에서 로그인을 하게 되면 인가서버는 임시코드를 parameter 로 넣어서 클라이언트로 redirect 되어, 최종 클라이언트 서버가 사용자에 대한 엑세스 토큰을 인가서버에 요청하여 발급 받잖아요? 그리고 클라이언트 서버가 그 엑세스 토큰을 관리하게 되고..그러니까 클라이언트 서버가 대신 요청? 그런데 마지막장에 리소스 서버에 자원을 요청하는데.. 클라이언트 API 서버가 요청하는 것도 있고.. frond end 자바스크립트에서 클라이언트 서버를 경유하지 않고 직접 리소스 서버에 자원을 요청하는 예제가 있네요.실무에서는 이렇게 frond end 단에서 직접 리소스 서버로 요청하기도 하는지요?front end에서 클라이언트 API 서버에 요청을 하여 사용자 정보를 가져와 보여주는 식으로 구현해야 하는 것인지? 아니면 front end에서 직접 리소스 서버에 토큰 들고 요청하여 사용자 정보를 가져와 보여주는 식으로 구현해야 하는지? 실무에서 어떻게 구현하는지 알고 싶네요.
-
미해결스프링 시큐리티 OAuth2
인가서버와 websecurityconfigureradapter
안녕하세요, 강사님? 강의 잘듣고 있습니다. 이제 막 회사에서 일하기 시작한 주니어 개발자입니다. 제 회사에서는 websecurityconfigureradapter 를 상속받아서, spring boot 2.7.6에서 사용하고 있습니다.이 경우에는 authorization server를 마지막 강의에서 사용하신 source code를 활용해보니 작동하지않았습니다. illegalStateException에서 security filter chain과 websecurityconfigureradapter 둘중 하나를 사용하라는 문제에 부딪혔습니다. 그외에도 oauth2 authroization server 관련 jar내 class들이 security filter chain을 형성하는 과정이 관련 있는 것 같아서, 동작하지 않는것으로 보이기도 합니다. 예를들면 @Bean (clientRegistration을 수행하는메서드) 입니다. 혹시 oauth2로는 websecurityconfigureradapter 과 함께 쓸수가 없는 것일까요? 있다면, 혹시 관련 코드를 가지고 계신것이 있다면 공유해주시면 감사드리겠습니다.!
-
미해결스프링 시큐리티 OAuth2
JWT Verify에 대한 질문이 있습니다.
protected String getJwtTokenInternal(JWSSigner jws, UserDetails user, JWK jwk) throws JOSEException { // JWT token 을 만들기 위해 3가지가 필요함(header, payload, sig) JWSHeader header = new JWSHeader.Builder((JWSAlgorithm) jwk.getAlgorithm()).keyID(jwk.getKeyID()).build(); List<String> authorities = user.getAuthorities().stream().map(author -> author.getAuthority()).collect(Collectors.toList()); JWTClaimsSet payload = new JWTClaimsSet.Builder() .subject("user") .issuer("http://localhost:8080") .claim("username", user.getUsername()) .claim("authority", authorities) .expirationTime(new Date(new Date().getTime() + 1000)) //1초 .build(); SignedJWT signedJWT = new SignedJWT(header, payload); // 서명 signedJWT.sign(jws); //토큰 발행 String jwtToken = signedJWT.serialize(); return jwtToken; } expiration Time 말고는 강사님 코드랑 동일합니다.토큰 만료되는 걸 체크하고 싶어서 테스트 코드를 작성했습니다. 만료시간을 1초로 만들었습니다. @Test @DisplayName("test") void test() throws JOSEException, InterruptedException, ParseException { UserDetails user = userDetailsService.loadUserByUsername("user"); System.out.println(user); String jwtToken = securitySigner.getJwtToken(user, jwk); System.out.println("jwtToken = " + jwtToken); Thread.sleep(7000); SignedJWT signedJWT = SignedJWT.parse(jwtToken); boolean verify = signedJWT.verify(new RSASSAVerifier(jwk)); System.out.println("verify = " + verify); } 근데 위의 테스트 코드를 실행한 결과7초라는 지연을 주었는데도 불구하고verify가 참으로 뜨네요. 어떤게 문제일까요?
-
미해결스프링 시큐리티 OAuth2
http://localhost:8081 접속 에러가 뜹니다.
또한 keycloak 19.0.1 버전은 사용시 실행이 되지않아22.0.5 버전을 사용하고 있습니다.issuerUri 는 사용시 스프링부트 실행자체가 되지 않아 막아두었습니다.주석처리를 해제하면 다음과 같은 에러가 뜹니다.Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.OAuth2ClientConfiguration$OAuth2ClientWebMvcSecurityConfiguration': Unsatisfied dependency expressed through method 'setClientRegistrationRepository' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'clientRegistrationRepository' defined in class path resource [org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2ClientRegistrationRepositoryConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository]: Factory method 'clientRegistrationRepository' threw exception; nested exception is java.lang.IllegalArgumentException: Unable to resolve Configuration with the provided Issuer of "http://localhost:8080/realms/oauth2"
-
미해결스프링 시큐리티 OAuth2
사용하지 않을 EndPoint를 Disable할 수 있는 방법이 있을까요?
.well-known/openid-configuration을 이용해 endpoint 및 정보들을 확인했는데 많은 default 값들이 존재합니다.여기서 제가 사용하지 않는 정보들을 disable 하는 방법이 있나요??아래는 .well-known/openid-configuration 호출 시 받은 정보입니다.{ "issuer": "http://127.0.0.1:6080", "authorization_endpoint": "http://127.0.0.1:6080/oauth2/authorize", "device_authorization_endpoint": "http://127.0.0.1:6080/oauth2/device_authorization", "token_endpoint": "http://127.0.0.1:6080/oauth2/token", "token_endpoint_auth_methods_supported": [ "client_secret_basic", "client_secret_post", "client_secret_jwt", "private_key_jwt" ], "jwks_uri": "http://127.0.0.1:6080/oauth2/jwks", "userinfo_endpoint": "http://127.0.0.1:6080/userinfo", "end_session_endpoint": "http://127.0.0.1:6080/connect/logout", "response_types_supported": [ "code" ], "grant_types_supported": [ "authorization_code", "client_credentials", "refresh_token", "urn:ietf:params:oauth:grant-type:device_code" ], "revocation_endpoint": "http://127.0.0.1:6080/oauth2/revoke", "revocation_endpoint_auth_methods_supported": [ "client_secret_basic", "client_secret_post", "client_secret_jwt", "private_key_jwt" ], "introspection_endpoint": "http://127.0.0.1:6080/oauth2/introspect", "introspection_endpoint_auth_methods_supported": [ "client_secret_basic", "client_secret_post", "client_secret_jwt", "private_key_jwt" ], "code_challenge_methods_supported": [ "S256" ], "subject_types_supported": [ "public" ], "id_token_signing_alg_values_supported": [ "RS256" ], "scopes_supported": [ "openid" ] }
-
해결됨스프링 시큐리티 OAuth2
PasswordOAuth2AuthorizedClientProvider @Deprecated
안녕하세요 선생님.최신 시큐리티 6.x 버전에서는 PasswordOAuth2AuthorizedClientProvider 클래스에 "The latest OAuth 2.0 Security Best Current Practice disallows the use of the Resource Owner Password Credentials grant" 라고 적혀있는데 그럼 더이상 Resource Owner Password Flow 방식을 사용하면 안되는건가요?
-
해결됨스프링 시큐리티 OAuth2
addFilterBefore 관련 질문이 있어요!
안녕하세요 선생님. spring security 그리고 spring security oauth 강의 잘 듣고있습니다.이전 security 기본 강의에서는 formlogin API를 호출해서 UsernamePasswordAuthenticationFilter가 존재하였는데, 지금은 formlogin API를 호출하지 않아서 UsernamePasswordAuthenticationFilter가 존재하지 않는데 왜 addFilterBefore에 UsernamePasswordAuthenticationFilter.class를 적는지 궁금해요!!
-
미해결스프링 시큐리티 OAuth2
강사님 로그인 요청시 궁금한 점이 있습니다.
POST /login으로 요청시JwtAuthenticationFilter는 실행되지만JwtAuthorizationMacFilter는 왜 실행되지 않는 이유가 궁금합니다. FilterChainProxy에 additionalFilters 목록을 보게 되면, JwtAuthenticationFilter와 JwtAuthorizationFilter가 담겨있고 UsernamePasswordAuthenticationFilter앞에 있는것을 확인할 수 있는데, JwtAuthorizationMacFilter을 넘어가는 이유가 뭔지 궁금합니다 디버깅 중에 왜 안나왔는지 알게되었네요JwtAuthenticationFilter는 인증 성공후에 doFilter 를 안넘겨서 그 이후 체인이 실행하지 않아 검증 필터가 실행되지 않았습니다. 혹시 체인을 안태운 이유가 가장 마지막 필터인 FilterSecurityInterceptor or AuthorizationFilter 에서 SecurityContextHolder.getContext().getAuthentication 에 null 체크 예외 발생 때문에 일부러 안넘기신건가요?? 토큰 인증 필터 성공 이후에 체인 안넘기신 이유가 궁금합니다.안넘기게 되면 컨트롤러단까지 요청이 안가서 index 페이지가 안나와서
-
미해결스프링 시큐리티 OAuth2
Consent Page에서 기존 다른 OAuth처럼 필수 동의와 선택 동의를 구분해서 받을 수 있는지 궁금합니다.
기존 Default Consent Page는 선택적 동의만 받을 수 있도록 되어 있는 것 같습니다.Custom Consent Page 예시를 보더라도 Consent Page를 만드는 예시일 뿐 필수동의와 선택동의를 구분하는 방법은 찾을 수 없었습니다.결론적으로, Consent Page에서 선택 동의와 필수동의를 구분해서 받을 수 있는지와, 만약 가능하다면 어떻게 구성해야하는 지 궁금합니다
-
미해결스프링 시큐리티 OAuth2
커스텀 인증 필터 만들때 질문이 있습니다.
커스텀 Authentication Filter를 만들때 어떤 코드는 AbstractAuthenticationProcessingFilter를 상속 받거나 강사님은 UsernamePasswordAuthenticationFilter를 상속 받는데요 혹시 무엇을 상속 받을지 구분하는게 있을까요? 어떤 필터를 상속 받는것을 추천한다던지
-
미해결스프링 시큐리티 OAuth2
소셜로그인과 JWT 인증 방식에 대해 궁금한점이 있습니다.
일반 로그인 + 소셜 로그인 전체로 JWT 인증 방식으로 도입하고자 할때소셜 로그인 인증 성공 후에 JWT 인증 객체를 발급해서 그 토큰으로 프론트단과 통신하면 되는건가요?? 그리고 JWT로 인증하는 과정이 현 강의와 밑에 나중 강의들에 나오는지 궁금합니다. 단지 인가서버에서 내려준 엑세스 토큰을 리소스 서버에서 JWT 토큰을 검증하기 위한 것인지. 아니면 일반 로그인에 대해서도 JWT 인증을 도입할시에 도움이 되는지 궁금합니다.
-
미해결스프링 시큐리티 OAuth2
authenticationEntryPoint 를 기본 설정된 /login이 아닌 react 웹 페이지로 설정 시 cors 문제가 지속해서 발생합니다.
authenticastion Entry Point로 지정 시 cors문제가 계속해서 진행되어 Authorization Code를 받아올 수 없습니다.코드 첨부Authorization Server Config@Bean @Order(Ordered.HIGHEST_PRECEDENCE) public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http); http .getConfigurer(OAuth2AuthorizationServerConfigurer.class) .oidc(Customizer.withDefaults() ); http .exceptionHandling((exceptions) -> exceptions .authenticationEntryPoint( new LoginUrlAuthenticationEntryPoint("http://localhost:3000") // new LoginUrlAuthenticationEntryPoint("/login") )) http.oauth2ResourceServer((resourceServer) -> resourceServer .jwt(Customizer.withDefaults())); return http.build(); } @Bean public RegisteredClientRepository registeredClientRepository() { RegisteredClient oidcClient = RegisteredClient.withId(UUID.randomUUID().toString()) .clientId("oidc-client") .clientSecret("{noop}secret") .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN) .redirectUri("https://oidcdebugger.com/debug") .redirectUri("https://test-b821b.web.app") .postLogoutRedirectUri("http://127.0.0.1:8080/") .scope(OidcScopes.OPENID) .scope(OidcScopes.PROFILE) .clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build()) .build(); return new InMemoryRegisteredClientRepository(oidcClient); } @Bean public AuthorizationServerSettings authorizationServerSettings() { return AuthorizationServerSettings.builder().issuer("http://localhost:6080").build(); } } Default Web Config @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://localhost:3000") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedHeaders("*") .allowCredentials(true) .exposedHeaders("*"); } }; } @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowCredentials(true); configuration.addAllowedHeader("*"); configuration.addAllowedMethod("*"); configuration.addAllowedOrigin("http://localhost:3000"); configuration.setExposedHeaders(Arrays.asList("*")); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .cors(customCorsConfig -> customCorsConfig.configurationSource(corsConfigurationSource())) .csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests(authorizeHttpRequestsCustomizer -> authorizeHttpRequestsCustomizer.requestMatchers(AUTH_WHITELIST).permitAll() .anyRequest().authenticated() ) .formLogin( httpSecurityFormLoginConfigurer -> httpSecurityFormLoginConfigurer.loginPage("http://localhost:3000").loginProcessingUrl("/login") // Customizer.withDefaults() ) ; return http.build(); } @Bean public UserDetailsService userDetailsService() { PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); UserDetails userDetails = User.builder() .username("user") .password(passwordEncoder.encode("password")) .roles("USER") .build(); return new InMemoryUserDetailsManager(userDetails); } @Bean public JWKSource<SecurityContext> jwkSource() { KeyPair keyPair = generateRsaKey(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); RSAKey rsaKey = new RSAKey.Builder(publicKey) .privateKey(privateKey) .keyID(UUID.randomUUID().toString()) .build(); JWKSet jwkSet = new JWKSet(rsaKey); return new ImmutableJWKSet<>(jwkSet); } private static KeyPair generateRsaKey() { KeyPair keyPair; try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); keyPair = keyPairGenerator.generateKeyPair(); } catch (Exception ex) { throw new IllegalStateException(ex); } return keyPair; } @Bean public JwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) { return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource); } @Bean public PasswordEncoder encoder() { return new BCryptPasswordEncoder(); } 위 코드로 진행했을 시 발생하는 Cors Error입니다 Access to XMLHttpRequest at 'http://localhost:6080/oauth2/authorize?client_id=oidc-client&redirect_uri=https%3A%2F%2Foidcdebugger.com%2Fdebug&scope=openid&response_type=code&response_mode=form_post&state=3it6dl9kewr&nonce=hyq3pnronj7&continue' (redirected from 'http://localhost:6080/login') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.3. 이로 인해 CorsFilter를 적용하게 되면 해당 Cors는 해결되지만 authorization code 가 Redirect되는 시점에 Cors 에러가 새롭게 나옵니다.CorsFilter @Component @Slf4j @Order(Ordered.HIGHEST_PRECEDENCE) public class CorsFilter implements Filter { private static final Set<String> allowedOrigins = new HashSet<String>(); static { allowedOrigins.add( "http://localhost:3000" ); } @Override public void init(FilterConfig fc) throws ServletException { } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; HttpServletRequest request = (HttpServletRequest) req; String origin = request.getHeader(HttpHeaders.ORIGIN); log.info("Origin: {}", origin); if (origin != null) { Optional<String> first = allowedOrigins.stream().filter(origin::startsWith).findFirst(); first.ifPresent(s -> response.setHeader("Access-Control-Allow-Origin", s)); } response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Methods", "*"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Key, Authorization"); if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { response.setStatus(HttpServletResponse.SC_OK); } else { chain.doFilter(req, res); } } @Override public void destroy() { } Cors 오류Access to XMLHttpRequest at 'https://oidcdebugger.com/debug?code=1o_jSQQVu6EB4XDq-xCWP3qrzp2VDdGbH_AN7iBJGU5gQRC7BRFkQYdn2A6P-6G5Aoi8XLJLaVR4MSVktNzDvYLMmj_UXahcWfEwQdA-tk4GCw5Bff4mXn2q6mIYfs_d&state=3it6dl9kewr' (redirected from 'http://localhost:6080/login') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.혹시 외부 로그인 페이지와 연동한 예시가 있거나, Cors 문제를 해결할 방안이 있는지 궁금합니다ㅠㅠ
-
미해결스프링 시큐리티 OAuth2
spring boot 3.1 security entryPoint 관련 질문입니다
스프링부트 2.7.7 버전에서는 사용할때 아무 문제없던 코드들인데 3.1 버전 업데이트하면서 securityFilterChain 이부분 문법만 살짝 바뀐정도입니다 그런데jwt 토큰에서 chain.doFilter(request, response); 까지 잘 넘어가고비즈니스 로직인 service 단에서 에러가 터졌을때 (NullPointException,IllegalArgumentException)에러가 났을경우다시 엔트리포인트로 넘어와서 에러처리가 되는데 왜 이럴까요 ?? 무슨 에러가 나든엔트리포인트로 넘어오는데 엔트리포인트는 인증 실패일경우에 실행되어야하는걸로 알고있습니다토큰값은 모두 유효하고 jwt 토큰 인증은 되었음에도 불구하고 엔트리포인트로 넘어가는 이유를 모르겠습니다아래 에러는 비즈니스로직에서 에러 난 코드이며 2023-10-30T23:56:16.287+09:00 ERROR 26006 --- [nio-8081-exec-6] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.dao.InvalidDataAccessApiUsageException: No enum constant com.tripcoach.core.domain.alarm.enums.AlarmType.COACH] with root causejava.lang.IllegalArgumentException: No enum constant com.tripcoach.core.domain.alarm.enums.AlarmType.COACHat java.base/java.lang.Enum.valueOf(Enum.java:273) ~[na:na]at org.hibernate.type.descriptor.java.EnumJavaType.fromName(EnumJavaType.java:231) ~[hibernate-core-6.2.9.Final.jar:6.2.9.Final]at org.hibernate.type.descriptor.converter.internal.NamedEnumValueConverter.toDomainValue(NamedEnumValueConverter.java:53) ~[hibernate-core-6.2.9.Final.jar:6.2.9.Final] 바로 에러코드 다음이 2023-10-30T23:56:16.291+09:00 ERROR 26006 --- [nio-8081-exec-6] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] threw exceptionjava.lang.NullPointerException: Cannot invoke "Object.getClass()" because "exception" is nullat org.springframework.web.method.annotation.ExceptionHandlerMethodResolver.resolveMethodByThrowable(ExceptionHandlerMethodResolver.java:146) ~[spring-web-6.0.12.jar:6.0.12]at org.springframework.web.method.annotation.ExceptionHandlerMethodResolver.resolveMethod(ExceptionHandlerMethodResolver.java:134) ~[spring-web-6.0.12.jar:6.0.12] 엔트리포인트에서 넘어와버리네요부족한 코드이지만 아무리 찾아도 모르겠어서 글 남깁니다. 아래 전체코드 첨부합니다
-
미해결스프링 시큐리티 OAuth2
Naver Login시 권한에 대해 질문이 있습니다
CustomAuthorityMapper 클래스에서강사님과 코드는 동일하나authorities가 넘어올시에 위와 같이 넘어옵니다.그래서 강사님 영상과 다르게ROLE_USER만이 authority에 대해서 담기게 되고위의 사진은 hasRole 권한을 해제하여 찍어본것입니다. /api/user에 진입이 불가합니다 코드는 동일한데 뭐가 문제일까요,,,? 강사님의 네이버 로그인시는 response를 안벗기고도 진입이 가능해서 질문드립니다 package io.security.oauth2.sociallogin; import lombok.RequiredArgsConstructor; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper; import java.util.Collection; import java.util.HashSet; import java.util.Set; public class CustomAuthorityMapper implements GrantedAuthoritiesMapper { private String prefix = "ROLE_"; @Override public Set<GrantedAuthority> mapAuthorities(Collection<? extends GrantedAuthority> authorities) { HashSet<GrantedAuthority> mapped = new HashSet<>(authorities.size()); for (GrantedAuthority authority : authorities) { mapped.add(mapAuthority(authority.getAuthority())); } return mapped; } private GrantedAuthority mapAuthority(String name) { if(name.lastIndexOf(".") > 0){ int index = name.lastIndexOf("."); name = "SCOPE_" + name.substring(index+1); } if (!this.prefix.isEmpty() && !name.startsWith(this.prefix)) { name = this.prefix + name; } return new SimpleGrantedAuthority(name); } }
-
미해결스프링 시큐리티 OAuth2
Session id가 인가 코드와 access token을 교환하는 도중에 변경됩니다.
안녕하세요. 강의 잘 듣고 있습니다.제목에서처럼, session id가 access token을 교환하는 일련의 과정 중에 변경되어 다음과 같은 오류가 브라우저 상에서 보여집니다.해당 에러 메시지를 내뱉는 로직이 OAuth2LoginAuthenticationFilter 클래스의 attemptAuthentication 메소드에 있음을 확인하였습니다. 제가 찾은 원인은 OAuth2AuthorizationRequestRedirectFilter에서 AuthorizationRequest의 저장까지는 성공적인데, OAuth2LoginAuthenticationFilter에서 AuthorizationRequest를 Repository에서 꺼내오려고 시도할 때 바뀐 session id값 때문에 이전의 AuthorizationRequest 객체를 가져오지 못하고 null을 반환하는 것이었습니다. 이렇게 session id가 바뀌는 원인이 무엇인지 알려주시면 감사하겠습니다 ㅠㅠ
-
미해결스프링부트 시큐리티 & JWT 강의
Facebook 로그인 버튼만든 후 error(Sorry...) 발생시
인증 및 계정 만들기 > 수정 에서 Email 권한 추가해주어야 오류 안나네요.
-
미해결스프링 시큐리티 OAuth2
AuthorizedClient를 Service를 통해서 가져올시
위에 사진으로 authorizedClient가 nullpoint 에러가 발생합니다. repository시에는 authorizedClient는 잘 가져오는데 service로 load시에 못 가져오는거 같습니다. 왜 그런건지 궁금합니다
-
미해결스프링 시큐리티 OAuth2
임시 코드 요청시 Redirect에 대해 질문 드립니다
client registration의 redirect uri는 인가 서버로부터 임시코드를 발급받고, redirect uri로 임시 코드를 리다이렉트 시키는데,강사님께서redirect uri를 http://localhost:8081/client 로 설정하였고,ClientController의 매핑주소도 위와 같은 주소로 설정하였습니다. 여기서 궁금한점이 있습니다. 임시 코드를 발급한 시점에 저 리다이렉트 주소로 콜백하게 되는데, 이 시점에 clientcontroller에 저 매핑주소가 호출되어야 할텐데왜 token 발급시에 컨트롤러가 호출되는지그리고 redirect uri가 token 발급시 콜백 주소도 해당되는건가요?? 엑세스 토큰 발급후에도 http://localhost:8081/client여기로 호출되어서 의문이 듭니다.
-
미해결스프링 시큐리티 OAuth2
keycloak 연동 (클라이언트 앱 시작하기 - application.yml)
아래 사진과 같이 yml 파일을 작성했는데, keycloak 로그인 폼이 적용이 안되고 기존 로그인 폼이 나옵니다.(프로그램 실행 시 기존처럼 비밀번호가 출력되고 해당 비밀번호로 id pw 입력하여 로그인하면 index 화면이 나오는 상황입니다.)keycloak과 연동 문제인 듯 한데, keycloak 인가서버 도메인과 관련되어있는 것 일까요?혹은, keycloak 연동을 위해 build.gradle 같은 곳에 추가 설정해 줘야 하는 부분이 있을 까요? 참고로 build.gradle은 아래 사진과 같고,종속성 'org.springframework.boot:spring-boot-starter-oauth2-client' 추가해 준 상태 입니다.