这个SpringSecurity登录插件牛啊,验证码、小程序、OAuth2都能快速接入

博客 分享
0 176
张三
张三 2022-06-15 11:00:33
悬赏:0 积分 收藏

这个Spring Security登录插件牛啊,验证码、小程序、OAuth2都能快速接入

上次我们把验证码登录、小程序登录优雅地集成到了Spring Security,很多同学大呼过瘾,相比较一些传统玩法高级了很多。胖哥就赶紧抓住机会举一反三,把几个非标准的OAuth2也接入了进来,主要是微信、企业微信,做到应接尽接。

只需要通过下面几行简单的代码就可以完成集成:

    @Bean    DelegateClientRegistrationRepository delegateClientRegistrationRepository(@Autowired(required = false) OAuth2ClientProperties properties) {        DelegateClientRegistrationRepository clientRegistrationRepository = new DelegateClientRegistrationRepository();        if (properties != null) {            List<ClientRegistration> registrations = new ArrayList<>(                    OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(properties).values());            registrations.forEach(clientRegistrationRepository::addClientRegistration);        }        return clientRegistrationRepository;    }

这个是为了兼容在application.yaml配置文件的OAuth2客户端配置、预设的微信等知名三方配置,你还可以通过DelegateClientRegistrationRepositorysetDelegate方法来扩展获取客户端配置的方式:

    public void setDelegate(Function<String, ClientRegistration> delegate) {        this.delegate = delegate;    }

然后在HttpSecurity中你这样配置就完全OK了:

httpSecurity.apply(new OAuth2ProviderConfigurer(delegateClientRegistrationRepository))                // 微信网页授权  下面的参数是假的            .wechatWebclient("wxdf90xxx8e7f", "bf1306baaaxxxxx15eb02d68df5")                // 企业微信登录 下面的参数是假的            .workWechatWebLoginclient("wwa70dc5b6e56936e1",                                      "nvzGI4Alp3xxxxxxZUc3TtPtKbnfTEets5W8", "1000005")                // 微信扫码登录 下面的参数是假的            .wechatWebLoginclient("xxxxxxxx", "xxxxxxxx")         .oAuth2LoginConfigurerConsumer(oauth2Configurer->            oauth2Configurer.successHandler(new ForwardAuthenticationSuccessHandler("/"))          );

把帐号配置进去就完事了,简单不简单,而且扩展性依然有保障,完全能够满足你的个性化需求。如果你想数据库管理这些参数,你可以自行扩展一下,也不难。

登录的效果成这样:

稍微一改成自定义页面,是不是高大上起来了呢?

登录成功后的逻辑,你可以写一个/接口:

    @GetMapping("/")    public Map<String, Object> index(@RegisteredOAuth2AuthorizedClient                                     OAuth2AuthorizedClient oAuth2AuthorizedClient) {        Authentication authentication = SecurityContextHolder.getContext()            .getAuthentication();        Map<String, Object> map = new HashMap<>(2);        // OAuth2AuthorizedClient 为敏感信息不应该返回前端        map.put("oAuth2AuthorizedClient", oAuth2AuthorizedClient);        map.put("authentication", authentication);        // todo 处理登录注册的逻辑 处理权限问题        // todo 根据 authentication 生成  token   cookie之类的           // todo 也可以用 AuthenticationSuccessHandler 配置来替代        return map;    }

根据Authentication信息返回token也好、cookie也好,都能实现。你也可以不写接口,配置一个AuthenticationSuccessHandler

如果你有其它第三方OAuth2要对接,可以提供给胖哥配置,胖哥帮你免费搞定。

项目和DEMO地址是:https://gitee.com/felord/spring-security-login-extension 记得给个star哦!

关注公众号:Felordcn 获取更多资讯

个人博客:https://felord.cn

posted @ 2022-06-15 10:35 码农小胖哥 阅读(2) 评论(0) 编辑 收藏 举报
回帖
    张三

    张三 (王者 段位)

    821 积分 (2)粉丝 (41)源码

     

    温馨提示

    亦奇源码

    最新会员