HTTP 基本身份验证使用 Spring Boot 的基于 Java 的配置
HTTP Basic Authentication using Spring Boot's Java based configuration
我正在尝试设置一个简单的 Spring 引导应用程序,使用具有硬编码密码的单个用户使用 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。
好吧,如果我没理解错的话,你只是想设置一个 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")));
}
我希望这篇文章能帮到你,并且我理解你的问题
我正在尝试设置一个简单的 Spring 引导应用程序,使用具有硬编码密码的单个用户使用 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。
好吧,如果我没理解错的话,你只是想设置一个 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")));
}
我希望这篇文章能帮到你,并且我理解你的问题