You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Spring Security OAuth2与Vaadin Flow 21实现Discord登录异常求助

问题修复方案

以下是需要调整的配置点:

  1. 调整HttpSecurity配置调用顺序
    VaadinWebSecurityConfigurerAdapter的configure(HttpSecurity http)方法内置了默认权限控制规则,你当前先写自定义OAuth配置再调用super.configure(http)的写法,会导致自定义配置被父类规则覆盖。需要调整为优先调用父类方法,再追加自定义规则:
@Override
protected void configure(HttpSecurity http) throws Exception {
    // 先调用父类配置
    super.configure(http);
    // 追加自定义规则
    http.authorizeRequests()
        .antMatchers("/oauth2/authorization/discord", "/login/oauth2/callback/**").permitAll()
        .anyRequest().authenticated();
    http.oauth2Login(oauth -> {
            // 第二个参数设为true,强制认证成功后始终跳转到指定路径
            oauth.defaultSuccessUrl("/test", true);
        })
        .logout(logout -> {
            logout.logoutSuccessUrl("/");
        });
}
  1. 给受保护视图添加权限注解
    Vaadin默认拦截无权限注解的视图访问请求,需要给TestView添加@PermitAll注解允许已登录用户访问:
@Route("test")
@PermitAll
public class TestView extends VerticalLayout {
    public TestView() {
        add("It Works! :D");
    }
}
  1. 更新Discord API域名(可选但推荐)
    Discord已将API域名从discordapp.com迁移到discord.com,建议更新application.yml配置避免后续旧域名失效:
provider:
  discord:
    authorizationUri: https://discord.com/api/oauth2/authorize
    tokenUri: https://discord.com/api/oauth2/token
    userInfoUri: https://discord.com/api/users/@me
    usernameAttribute: username
  1. 核对Discord开发者后台配置
    需要在Discord开发者平台的OAuth2设置页,配置和你项目中完全匹配的回调地址,本地测试时应为http://localhost:8080/login/oauth2/callback/discord,线上部署需要替换为对应正式域名,地址不匹配会直接导致回调失败跳转回首页。

  2. 添加配置生效注解
    在SecurityConfig类上添加@EnableWebSecurity注解,确保Spring正确加载你的安全配置规则。


内容的提问来源于stack exchange,提问作者Skyriiy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 13:45:07