【问题标题】:Spring Boot - spring security authorization issuesSpring Boot - Spring 安全授权问题
【发布时间】:2018-09-20 21:46:05
【问题描述】:

我已通过基本身份验证保护了我的 Spring Boot 应用程序。下面是我的 spring 安全配置。

package com.exxonmobil.asr.backoffice.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
@Configuration
@EnableWebSecurity
public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter {

    private static final String SPRING_SECURITY_PASSWORD = "spring.security.password";
    private static final String SPRING_SECURITY_USERNAME = "spring.security.username";
    @Autowired
    private AuthenticationEntryPoint authEntryPoint;

    @Autowired
    private Environment env;

    @Bean
    public PasswordEncoder bcryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser(env.getProperty(SPRING_SECURITY_USERNAME))
                .password(bcryptPasswordEncoder().encode(env.getProperty(SPRING_SECURITY_PASSWORD))).roles("USER");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable().authorizeRequests().antMatchers("/**").hasAnyRole("USER").anyRequest().authenticated().and().httpBasic()
                .authenticationEntryPoint(authEntryPoint);
    }

}

当我尝试通过邮递员访问应用程序休息 URL 时遇到问题。当我没有在邮递员的授权中提供任何授权/错误凭据时,我无法访问资源并获得无效凭据错误消息。但是,问题是当我第一次能够使用正确的凭据成功访问资源时,现在我将凭据更改为无效的凭据并尝试访问该资源,我仍然能够访问它。

我可以通过任何方式防止这种情况发生。

提前致谢。

问候, 法尔汉

【问题讨论】:

    标签: spring-boot spring-security


    【解决方案1】:

    Spring Security 创建一个会话并发回 Postman 保留的 cookie,然后您登录,直到该会话无效。

    您可以通过以下方式禁用会话:

    http
        .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    

    在SpringSecurityConfiguration的configure方法中。

    但请记住,您禁用了整个会话管理。如果您只有一个 REST API 可能没问题,但如果您还有其他 Web 组件,则可能需要 HTTP 会话。

    【讨论】:

      猜你喜欢
      • 2017-03-14
      • 1970-01-01
      • 2017-05-10
      • 2012-04-07
      • 2020-09-27
      • 1970-01-01
      • 2013-11-02
      • 2015-09-01
      相关资源
      最近更新 更多