英文:
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("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>
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("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();
}
}
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<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")));
}
I hope this one helps you out, and that I understood your question
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论