【问题标题】:How to use Spring Security in a Web API?如何在 Web API 中使用 Spring Security?
【发布时间】:2026-01-05 00:00:01
【问题描述】:

我正在使用 Spring Boot 创建一个 Web API,我想在其中使用 Spring Security 进行身份验证及其 Remember-Me 功能。 注意,我创建的是 Web API 而不是 REST API,这意味着我不会使用基于 JWT 的身份验证,而是使用 CookiesSessions

默认情况下,Spring Security 提供了一个我没有使用的登录和注销页面,而是创建了一个端点,我在其中使用 AuthenticationManager 对用户进行身份验证,但我无法使用 Spring Security 的 Remember-Me 功能。似乎只有在使用他们自己的登录表单时才会激活“记住我”。

我只想知道我是否可以像在我的 Web API 中一样使用 Spring Security,只需稍作修改(自己登录和注销用户),其他一切都由 Spring 处理。如果没有,是否有任何其他解决方法,还是我必须自己重新创建“记住我”功能?

【问题讨论】:

  • 如果这是一个 Web API,而不是 REST API,你如何在没有登录表单和关联 login 处理程序的情况下向用户询问凭据?
  • 使用端点,我创建了一个控制器 [POST],它通过请求正文获取用户凭据。
  • 这类似于内置的/login POST 处理程序,它从表单POST 正文中获取用户和密码并执行登录操作,包括。设置记住我。因此,如果您需要弄清楚记住我是如何完成的,请查看内置 POST 处理程序的源代码。

标签: java spring spring-boot spring-mvc spring-security


【解决方案1】:

[SpringBoot中的身份验证]

https://spring.io/guides/tutorials/spring-boot-oauth2/此链接包含您正在寻找的完成身份验证和授权的基本信息。

解决方法是,您可以简单地使用 OAuth 而不是 OAuth2。您可以扩展 WebSecurityConfigurerAdapter 并添加您的身份验证逻辑(会话、缓存或基于您的偏好的用户名/密码)。

是的,您还可以通过简单的更改在您的课程中包含记住我的功能。代码如下

` @Override
受保护的无效配置(HttpSecurity http)抛出异常{

  http.authorizeRequests().  
  antMatchers("/index", "/user","/").permitAll()  
  .antMatchers("/admin").authenticated()  
  .and()  
  .formLogin()  
  .loginPage("/login")  
  .and()  
  .rememberMe()  
  .key("rem-me-key")  
  .rememberMeParameter("remember") // it is name of checkbox at login page  
  .rememberMeCookieName("rememberlogin") // it is name of the cookie  
  .tokenValiditySeconds(100) // remember for number of seconds  
  .and()  
  .logout()  
  .logoutRequestMatcher(new AntPathRequestMatcher("/logout"));    

} ` 希望这会有所帮助

【讨论】:

  • 但重点是我不想要登录页面。我有一个登录控制器,它通过请求正文获取用户凭据。在该参数中,我使用AuthenticationManager 对用户进行身份验证。我启用了rememberMe(),但是当我自己验证用户身份时它不起作用,并且仅在使用我不想使用的 Spring 登录页面时才起作用。
  • Spring Boot 中的默认安全性是 Basic。您可以通过设置 security.basic.enabled=false 来禁用它。
【解决方案2】:

克服 Spring 配置的基本安全性的另一种方法是使用过滤器。

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity security) throws Exception
    {
     security.httpBasic().disable();
    }
}

或者您可以禁用 Spring Security 自动配置。不过不推荐。

@SpringBootApplication(exclude={SecurityAutoConfiguration.class})

【讨论】:

    最近更新 更多