【问题标题】:Stateless Application Spring Security无状态应用程序 Spring Security
【发布时间】:2015-10-26 04:02:58
【问题描述】:

我正在使用 Spring Web、Spring Security 和 Spring social 创建一个 Spring Boot 应用程序。该应用程序包含使用基本身份验证来确保安全的其他服务。我正在尝试配置 Spring 以使应用程序无状态,但是当我使用浏览器向 Web 服务发出请求时,浏览器会提示输入用户凭据,但由于会话创建,所有先前的请求都使用相同的用户凭据。我已经配置了应用程序来阻止这种情况发生但仍然存在问题。\

public class SecurityConfig extends WebSecurityConfigurerAdapter{
    @override
    protected void configure(HttpSecurity http) throws Exception{
        http.sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/api/**")
            .hasRole("USER")
            .andBasic();
    }

    @override
    protected void configure(AuthenticatioinManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("some@gmail.com")
            .password("12345")
            .role("USER");
    }
}

我应该更改或添加什么来获得此功能。

【问题讨论】:

    标签: java spring spring-security spring-boot


    【解决方案1】:

    看看这个:

        http
      .sessionManagement()
      .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
      .and()
      .csrf().disable()
      .authorizeRequests()
      .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() //allow CORS option calls
      .antMatchers("/resources/**").permitAll()
      .anyRequest().authenticated()
      .and()
      .httpBasic();
    

    【讨论】:

    • 欢迎来到 StackOverflow!在答案中解释您的代码可能对未来的读者或有类似问题的人更有帮助。
    【解决方案2】:

    Spring 安全性基于称为 SecurityContext 的东西。这是一个 ThreadLocal,例如一次只存在于一个线程上。每个请求都将在它自己的线程上,并且将无法访问任何受保护的资源,除非将 SecurityContext 设置为包含适当的角色。因此,即使您刚刚登录,它在幕后将角色插入到 SecurityContext 中,该安全上下文也消失了,就好像它是一个不同的用户一样。令牌是您处理此问题的方式。或者 base64 将您的用户名和密码编码到每个请求中,无论您的船是什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-30
      • 2013-03-21
      • 2018-12-29
      • 2021-12-18
      • 1970-01-01
      • 2016-03-28
      • 2017-04-05
      • 2016-11-09
      相关资源
      最近更新 更多