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

voj3qocg  于 2021-09-30  发布在  Java
关注(0)|答案(1)|浏览(330)

我试图通过提供基于用户名和密码的登录以及用于用户身份验证的GoogleOAuth来实现SpringBoot的基本登录页面。
想知道spring是否允许在同一个应用程序中实现这一点。
任何帮助都将不胜感激。

slwdgvem

slwdgvem1#

是的,可以做到。您需要在WebSecurity配置器中配置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());
            ...
        }

自定义登录页面,包括表单登录和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

这摘自我在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).

相关问题