当前位置: 首页 > 后端技术 > Java

这个SpringSecurity登录插件很给力,验证码、小程序、OAuth2快速接入

时间:2023-04-02 10:04:34 Java

上次我们优雅地将验证码登录和小程序登录集成到SpringSecurity中。许多学生都喜欢它。比起一些传统的玩法要先进很多。胖哥赶紧抓住机会,举一反三,还连上了几个非标准的OAuth2,主要是微信和企业微信,尽量多答。可以使用以下简单的代码行完成集成:@BeanDelegateClientRegistrationRepositorydelegateClientRegistrationRepository(@Autowired(required=false)OAuth2ClientPropertiesproperties){DelegateClientRegistrationRepositoryclientRegistrationRepository=newDelegateClientRegistrationRepository(){注册!registrations=newArrayList<>(OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(properties).values());registrations.forEach(clientRegistrationRepository::addClientRegistration);}返回clientRegistrationRepository;}这是为了兼容application.yaml配置文件中的OAuth2客户端配置,也可以使用DelegateClientRegistrationRepository的setDelegate方法扩展获取客户端配置的方式:publicvoidsetDelegate(Functiondelegate){this.delegate=委托;然后在HttpSecurity中这样配置就完全OK了:httpSecurity.apply(newOAuth2ProviderConfigurer(delegateClientRegistrationRepository))//微信网页授权下面的参数是假的.wechatWebclient("wxdf90xxx8e7f","bf1306baaaxxxxx15eb02d68df5")//企业微信登录下面的参数是假的.workWechatWebLoginclient("wwa70dc5b6e56936e1","nvzGI4Alp3xxxxxxZUc3TtPtKbnfTEets5W8","1000005")//WechatWebLoginclient("xxxxxxxx","xxxxxxxx").oAuth2LoginConfigurerConsumer(oauth2Configurer->oauth2Configurer.successHandler(newForwardAuthenticationSuccessHandler("/")));configuretheaccountThat'sit,it'ssimplebutnotsimple,andthescalabilityisstillguaranteed,whichcanfullymeetyourindividualneeds.Ifyouwantthedatabasetomanagetheseparameters,youcanexpandityourself,andit'snotdifficult.登陆后的效果是这样的:自定义页面稍微改一下,是不是变高了?登录逻辑成功后,可以写一个/接口:@GetMapping("/")publicMapindex(@RegisteredOAuth2AuthorizedClientOAuth2AuthorizedClientoAuth2AuthorizedClient){Authenticationauthentication=SecurityContextHolder.getContext().getAuthentication();Mapmap=newHashMap<>(2);//OAuth2AuthorizedClient为敏感信息,不应返回前端map.put("oAuth2AuthorizedClient",oAuth2AuthorizedClient);map.put("身份验证",身份验证);//todo处理登录和注册的逻辑处理权限问题//todo根据认证生成tokencookie//todo也可以配置AuthenticationSuccessHandler而不是returnmap;}可以实现根据Authentication信息返回token或cookies。您还可以在不编写接口的情况下配置AuthenticationSuccessHandler。如果你有其他第三方OAuth2要接入,可以提供给胖哥配置,胖哥免费帮你做。项目和DEMO的地址是:https://gitee.com/felord/spri...记得给个star!关注公众号:Felordcn获取更多资讯个人博客:https://felord.cn