nge*_*esh 2 oauth spring-security google-oauth spring-boot
我正在尝试通过提供基于用户名和密码的登录以及用于用户身份验证的 google oAuth 来使用 Spring Boot 实现基本登录页面。
想知道 spring 是否允许使用同一个应用程序来完成此操作。
任何帮助将非常感激。
是的,这是可以做到的。您需要在 WebSecurityConfigurer中配置 OAuth2 和表单登录 ,并配置自定义登录页面。您还需要 为表单登录 配置PasswordEncoder 和 UserDetailsService ,为 OAuth2 登录配置OAuth2UserService (可能还有 OidcUserService)。主体 实现将与登录类型相对应。
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());
...
}
Run Code Online (Sandbox Code Playgroud)
自定义登录页面包括表单登录和 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>
Run Code Online (Sandbox Code Playgroud)
OAuth2配置:
---
spring:
security:
oauth2:
client:
registration:
google:
client-id: XXXXXXXXXXXXXXXXXXXX
client-secret: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
provider:
google:
user-name-attribute: email
Run Code Online (Sandbox Code Playgroud)
这取自我的文章 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)。
| 归档时间: |
|
| 查看次数: |
2051 次 |
| 最近记录: |