【问题标题】:HTTP Basic Authentication using Spring Boot's Java based configuration使用 Spring Boot 的基于 Java 的配置进行 HTTP 基本身份验证
【发布时间】:2021-01-27 05:09:17
【问题描述】:

我正在尝试使用具有硬编码密码的单个用户设置一个简单的 Spring Boot 应用程序,该应用程序通过 HTTP 基本身份验证进行保护。

到目前为止,我使用基于 XML 的配置使其工作。

如何使用基于 Java 的配置实现相同的结果?

  • SecurityConfig.java

    @EnableWebSecurity
    @ImportResource("classpath:spring-security.xml")
    public class SecurityConfig {}
    
  • spring-security.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans:beans xmlns="http://www.springframework.org/schema/security"
                 xmlns:beans="http://www.springframework.org/schema/beans"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                                     http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
        <http>
            <intercept-url pattern="/MyService/**" access="isAuthenticated()" />
            <http-basic />
        </http>
    
        <user-service>
            <user name="foo" password="{noop}bar" authorities="ROLE_USER" />
        </user-service>
    </beans:beans>
    

注意:我必须使用@EnableWebSecurity 而不是@Configuration 来解决Spring Boot Issue #10236

我正在使用 Spring Boot 2.3.4 和 Spring Security 5.3.4。

【问题讨论】:

    标签: java spring spring-boot spring-security basic-authentication


    【解决方案1】:

    好吧,如果我理解正确,您只是想建立一个 http 连接? 这是我编写的代码示例,并适合您的 xml(我认为)

    @Configuration("SecurityConfig") 
    @Order(1) // If you have many security configs, you need to specify an order
    public class SecurityFrConfiguration extends WebSecurityConfigurerAdapter {
    
    
          WARNING: You should use a password encoder, i recommend Bcrypt with 10 rounds,  salt and pepper
        @Bean
        public static PasswordEncoder passwordEncoder() {
            return NoOpPasswordEncoder.getInstance();
        }
    
        @Override
        public void configure(HttpSecurity http) throws Exception {
    
    
            http.sessionManagement().sessionFixation().none().and() //sessionFixation() is used for sticky sessions, if you need them
                    .antMatcher("/yourWebsite/**")
                    .authorizeRequests() //Here I authorize all request on the site
                    .regexMatchers("/MyService/**") //Except on /Myservice where you need to be admin
                    .hasAuthority("ROLE_ADMIN") //ROLE_ADMIN is an example, you could define any number of role, and making it match to any URL through regexMatchers
                    .and()
                    .formLogin().loginPage(YOUR_LOGIN_FORM_HERE) //This allows you to override the default form login, and use your own
                    .permitAll();
    
        }
    
    
    
    
    }
    

    那么如果你打算真正使用它,你需要从数据库中获取用户,所以你还需要这样的东西:

    @Service
    public class YourUserDetailsService implements UserDetailsService { //UserDetailsService is the interface we need to let Spring do its magic
    
        private final LoginsService LoginsService;
    
        public LibraryUserDetailsService(LoginsService loginsService) {
            this.loginsService = loginsService;
        }
    
        @Override
        public UserDetails loadUserByUsername(String password, String userName) throws UsernameNotFoundException {
    
     //Here you fetch, decrypt, and check that the password and username are correct
     //WARNING: This is a really simple example, do not use this in your applications code 
         
      Optional<GrantedAcces> access = 
      libraryLoginsService.findUser(userName,password);
    
      //I create a new user with the authorized role, this is store in the session
               return new User(access.get().getUserName,access.get().getPassword(), Collections.singleton(new SimpleGrantedAuthority("ROLE_ADMIN")));
    
       }
    

    我希望这个可以帮助你,我理解你的问题

    【讨论】:

      猜你喜欢
      • 2014-09-22
      • 2015-08-12
      • 2012-07-19
      • 2019-04-25
      • 2011-03-18
      • 2011-02-11
      • 2017-08-03
      • 2018-01-22
      • 2016-10-31
      相关资源
      最近更新 更多