HTTP基本身份验证使用Spring Boot的基于Java的配置

huangapple go评论68阅读模式
英文:

HTTP Basic Authentication using Spring Boot's Java based configuration

问题

我正在尝试搭建一个简单的 Spring Boot 应用使用基本的 HTTP 基本认证来保护只允许一个预设密码的单一用户访问

目前为止我已经通过使用基于 XML 的配置使其正常工作

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

- **SecurityConfig.java**

```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>

注:由于 Spring Boot 问题#10236,我不得不使用 @EnableWebSecurity 代替 @Configuration

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


<details>
<summary>英文:</summary>

I am trying to set up a simple Spring Boot application secured with HTTP Basic Authentication using a single user with a hard-coded password.

So far, I got it working using XML based configuration.

How can I achieve the same result using Java based configuration?

- **SecurityConfig.java**

      @EnableWebSecurity
      @ImportResource(&quot;classpath:spring-security.xml&quot;)
      public class SecurityConfig {}

- **spring-security.xml**

      &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
      &lt;beans:beans xmlns=&quot;http://www.springframework.org/schema/security&quot;
                   xmlns:beans=&quot;http://www.springframework.org/schema/beans&quot;
                   xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
                   xsi:schemaLocation=&quot;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&quot;&gt;
          &lt;http&gt;
              &lt;intercept-url pattern=&quot;/MyService/**&quot; access=&quot;isAuthenticated()&quot; /&gt;
              &lt;http-basic /&gt;
          &lt;/http&gt;

          &lt;user-service&gt;
              &lt;user name=&quot;foo&quot; password=&quot;{noop}bar&quot; authorities=&quot;ROLE_USER&quot; /&gt;
          &lt;/user-service&gt;
      &lt;/beans:beans&gt;

Note: I had to use `@EnableWebSecurity` instead of `@Configuration` to work around [Spring Boot Issue #10236][1].

I am using Spring Boot 2.3.4 with Spring Security 5.3.4.

  [1]: https://github.com/spring-projects/spring-boot/issues/10236

</details>


# 答案1
**得分**: 0

这是一段关于设置HTTP连接的代码示例,你的XML将被适应到这个代码中。

```java
@Configuration("SecurityConfig")
@Order(1)
public class SecurityFrConfiguration extends WebSecurityConfigurerAdapter {

    // 警告:你应该使用密码编码器,我推荐使用带有10轮次、盐和pepper的Bcrypt
    @Bean
    public static PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.sessionManagement().sessionFixation().none().and()
                .antMatcher("/yourWebsite/**")
                .authorizeRequests()
                .regexMatchers("/MyService/**")
                .hasAuthority("ROLE_ADMIN")
                .and()
                .formLogin().loginPage(YOUR_LOGIN_FORM_HERE)
                .permitAll();
    }
}

如果你真的打算使用这段代码,你需要从数据库中获取用户,所以你也需要类似这样的内容:

@Service
public class YourUserDetailsService implements UserDetailsService {

    private final LoginsService LoginsService;

    public LibraryUserDetailsService(LoginsService loginsService) {
        this.loginsService = loginsService;
    }

    @Override
    public UserDetails loadUserByUsername(String password, String userName) throws UsernameNotFoundException {
        Optional<GrantedAcces> access = libraryLoginsService.findUser(userName, password);
        return new User(access.get().getUserName(), access.get().getPassword(), Collections.singleton(new SimpleGrantedAuthority("ROLE_ADMIN")));
    }
}

希望这能帮助你,并且我理解了你的问题。

英文:

Well, if i understand correctly, you just want to setup a http connection ?
Here is a code sample i wrote, and adapted to fit your xml (i think)

@Configuration(&quot;SecurityConfig&quot;) 
@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(&quot;/yourWebsite/**&quot;)
                .authorizeRequests() //Here I authorize all request on the site
                .regexMatchers(&quot;/MyService/**&quot;) //Except on /Myservice where you need to be admin
                .hasAuthority(&quot;ROLE_ADMIN&quot;) //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();

    }




}

Then if you intend to really use this, you need to get the user, probably from the database, so you'll also need something like this:

@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&lt;GrantedAcces&gt; 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(&quot;ROLE_ADMIN&quot;)));

   }

I hope this one helps you out, and that I understood your question

huangapple
  • 本文由 发表于 2020年10月13日 05:14:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/64325441.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定