项目和DEMO地址是:

https://gitee.com/felord/spring-security-login-extension

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

  1. @Bean
  2. DelegateClientRegistrationRepository delegateClientRegistrationRepository(@Autowired(required = false) OAuth2ClientProperties properties) {
  3. DelegateClientRegistrationRepository clientRegistrationRepository = new DelegateClientRegistrationRepository();
  4. if (properties != null) {
  5. List<ClientRegistration> registrations = new ArrayList<>(
  6. OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(properties).values());
  7. registrations.forEach(clientRegistrationRepository::addClientRegistration);
  8. }
  9. return clientRegistrationRepository;
  10. }

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

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

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

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

把帐号配置进去就完事了,简单不简单,而且扩展性依然有保障,完全能够满足你的个性化需求。如果你想数据库管理这些参数,你可以自行扩展一下,也不难。
登录的效果成这样:
微信、企业微信的三方登录 - 图1
稍微一改成自定义页面,是不是高大上起来了呢?
微信、企业微信的三方登录 - 图2
登录成功后的逻辑,你可以写一个/接口:

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

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