Spring Authorization Server认证后无法重定向至Next.js及invalid_client问题
环境与初始异常
搭建了运行在localhost:8080的Java Spring后端API(集成Spring Authorization Server),以及运行在localhost:3000的Next.js前端。用户注册后可正确重定向到授权服务器的登录页面,输入正确账号密码后,Spring日志显示用户已认证:
namePasswordAuthenticationToken, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=127.0.0.1, SessionId=4FEB7A8392B22372152176A6F947D0BA], Granted Authorities=[User]]
原本期望认证后重定向至前端(已设置页面接收授权码并调用接口获取令牌),但实际出现404错误(提示无特定/error页面,未说明具体错误)。
初始Spring授权配置
@Bean public AuthenticationManager authenticationManager( CustomUserDetailsService userDetailsService, PasswordEncoder passwordEncoder) { DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider(); authenticationProvider.setUserDetailsService(userDetailsService); authenticationProvider.setPasswordEncoder(passwordEncoder); return new ProviderManager(authenticationProvider); } @Bean public RegisteredClientRepository registeredClientRepository() { RegisteredClient linguaClient = RegisteredClient.withId("lingua-client.frontend") .clientId("lingua-client") .clientSecret("secret") .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN) .redirectUri("http://localhost:3000/login/oauth2/code/lingua-client") .postLogoutRedirectUri("http://localhost:3000") .scope(OidcScopes.OPENID) .scope("user.read") .scope("user.write") .clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build()) .build(); return new InMemoryRegisteredClientRepository(linguaClient); }
前端授权请求代码
const clientId = process.env.CLIENT_ID; const redirectUri = encodeURIComponent('http://localhost:3000/login/oauth2/code/lingua-client'); const response_type = 'code'; const scope = encodeURIComponent('user.read user.write'); const authServerUrl = process.env.AUTH_SERVER; const authUrl = `${authServerUrl}/authorize?response_type=${response_type}&client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scope}`;
已在http://localhost:3000/login/oauth2/code/lingua-client路径设置页面,但从未收到请求,直接访问该URL也返回404。
更新后新问题
添加以下安全链过滤器后,成功重定向并获取到授权码:
@Bean @Order(1) public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http); http.getConfigurer(OAuth2AuthorizationServerConfigurer.class) .oidc(Customizer.withDefaults()); // Enable OpenID Connect 1.0 http // Redirect to the login page when not authenticated from the // authorization endpoint .exceptionHandling((exceptions) -> exceptions .defaultAuthenticationEntryPointFor( new LoginUrlAuthenticationEntryPoint("/login"), new MediaTypeRequestMatcher(MediaType.TEXT_HTML) ) ); return http.build(); }
但现在调用token端点时,出现invalid_client错误。
内容的提问来源于stack exchange,提问作者nadajp
相关产品推荐
相关产品推荐

