gpt4 book ai didi

spring-boot - 是否可以为 Spring Boot 应用程序提供 oauth 和基本用户名密码登录选项?

转载 作者:行者123 更新时间:2023-12-03 08:20:40 26 4
gpt4 key购买 nike

我正在尝试通过提供基于用户名和密码的登录以及用于用户身份验证的 google oAuth 来使用 Spring Boot 实现基本登录页面。

想知道 spring 是否允许使用同一个应用程序来完成此操作。

任何帮助将不胜感激。

最佳答案

是的,这是可以做到的。您需要在中配置 OAuth2 和表单登录你的 WebSecurityConfigurer并配置自定义登录页面。您还需要配置一个 PasswordEncoderUserDetailsService用于表单登录和 OAuth2UserService(并且可能是一个 OidcUserService )用于 OAuth2 登录。这 Principal实现将对应于登录类型。

WebSecurityConfigurer.configure(HttpSecurity):

        @Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/**")
.authorizeRequests(t -> t.anyRequest().authenticated())
.formLogin(t -> t.loginPage("/login").permitAll())
.oauth2Login(Customizer.withDefaults())
.logout(t -> t.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/").permitAll());
...
}

自定义登录页面,包括表单登录和 OAuth2 提供商链接:

<div>
<div>
<div>
<form th:object="${form}">
<input type="email" th:name="username" th:placeholder="'E\'mail Address'"/>
<label th:text="'E\'mail Address'"/>
<input type="password" th:name="password" th:placeholder="'Password'"/>
<label th:text="'Password'"/>
<button type="submit" th:text="'Login'"/>
<th:block th:if="${! oauth2.isEmpty()}">
<hr/>
<a th:each="client : ${oauth2}" th:href="@{/oauth2/authorization/{id}(id=${client.registrationId})}" th:text="${client.clientName}"/>
</th:block>
</form>
</div>
</div>
<div>
<div>
<p th:if="${param.error}">Invalid username and password.</p>
<p th:if="${param.logout}">You have been logged out.</p>
</div>
</div>
</div>

OAuth2 配置:

---
spring:
security:
oauth2:
client:
registration:
google:
client-id: XXXXXXXXXXXXXXXXXXXX
client-secret: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
provider:
google:
user-name-attribute: email

这取 self 的文章 https://blog.hcf.dev/article/2020-10-31-spring-boot-part-07 (源代码在 https://github.com/allen-ball/spring-boot-web-server/tree/trunk/part-07 )。

关于spring-boot - 是否可以为 Spring Boot 应用程序提供 oauth 和基本用户名密码登录选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67955529/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com