【问题标题】:Spring Security that needs username and password on every request每次请求都需要用户名和密码的 Spring Security
【发布时间】:2020-07-26 10:02:45
【问题描述】:

我想做的是构建一个 Rest 后端应用程序,该应用程序在每个请求上都需要 Authorization 标头,验证并返回数据,如果用户或密码错误,则返回 401 Unauthorized。

我的类路径中有 Spring Security,配置简单:

@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .passwordEncoder(NoOpPasswordEncoder.getInstance())
                .withUser("user")
                .password("pass")
                .roles("USER");
    }
}

但有一件事不能正常工作:当我使用有效的用户名和密码向 Postman 发出请求时,服务器会正​​确响应数据,但是如果我将密码更改为错误的密码并保持正确的用户名,服务器仍然会停止以数据和 OK 状态响应,就好像它正在使用 JSESSIONID Cookie 来检查进一步的请求。

这是一种仅使用 Spring Security 来检查标头授权的方式(没有 cookie、会话或保存用户信息或登录和注销页面),还是只使用过滤器来代替?

感谢您的帮助!

【问题讨论】:

    标签: spring-boot spring-security


    【解决方案1】:

    只需将以下内容添加到您的配置中:

     @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
          .sessionManagement()
    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    }
    

    这会将 spring security 配置为从不创建 cookie,每个请求都必须重新验证。

    【讨论】:

      猜你喜欢
      • 2017-08-03
      • 1970-01-01
      • 2014-11-02
      • 1970-01-01
      • 2012-10-08
      • 1970-01-01
      • 2022-01-25
      • 2012-06-13
      • 1970-01-01
      相关资源
      最近更新 更多