Spring Boot Security从入门到实战示例教程
Spring Boot Security是基于Spring Boot和Spring Security开发的一套web应用安全框架。它强化了基于Spring的应用程序的安全性,同时还保持了生产就绪型的特性。
以下是Spring Boot Security的入门到实战示例教程:
一、Spring Boot Security入门
1.1 引入Spring Boot Security依赖
在pom.xml文件中引入以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
1.2 配置默认的Spring Boot Security
在Spring Boot的启动类中添加以下配置:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
}
1.3 配置Spring Boot Security认证
在Spring Boot的启动类中添加以下配置:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
1.4 配置Spring Boot Security授权
在Spring Boot的启动类中添加以下配置:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}
}
二、Spring Boot Security实战示例
2.1 实例一:基于数据库的认证和授权
2.1.1 引入相关依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-data</artifactId>
</dependency>
2.1.2 配置数据源
在application.properties文件中添加以下配置:
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=
2.1.3 实现UserDetailsService接口
在Spring Boot的启动类中添加以下配置:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select username, password, enabled from users where username = ?")
.authoritiesByUsernameQuery("select username, authority from authorities where username = ?");
}
}
2.1.4 配置授权
在Spring Boot的启动类中添加以下配置:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("USER", "ADMIN")
.anyRequest().authenticated()
.and().formLogin().loginPage("/login").permitAll()
.and()
.logout().logoutSuccessUrl("/").permitAll();
}
}
2.2 实例二:自定义认证和授权
从另一方面来说,向Spring Security添加自定义的认证和授权机制。
2.2.1 实现UserDetailsService接口
创建一个名为MyUserDetailsService的类,实现UserDetailsService接口。在loadUserByUsername方法中,实现自定义的用户验证逻辑。
@Service
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("User not found.");
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
AuthorityUtils.createAuthorityList(user.getRoles()));
}
}
2.2.2 实现AuthenticationProvider接口
在自定义的AuthenticationProvider中实现自定义的认证逻辑。重写authenticate方法并在其中实现自定义的认证逻辑。
@Component
public class MyAuthenticationProvider implements AuthenticationProvider {
@Autowired
private MyUserDetailsService userDetailsService;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String name = authentication.getName();
String password = authentication.getCredentials().toString();
UserDetails user = userDetailsService.loadUserByUsername(name);
if (user == null || !password.equals(user.getPassword())) {
throw new BadCredentialsException("Authentication failed.");
}
return new UsernamePasswordAuthenticationToken(user, password, user.getAuthorities());
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
2.2.3 配置认证和授权
在Spring Boot的启动类中添加配置:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyAuthenticationProvider authenticationProvider;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("USER", "ADMIN")
.anyRequest().authenticated()
.and().formLogin().loginPage("/login").permitAll()
.and()
.logout().logoutSuccessUrl("/").permitAll();
}
}
以上就是Spring Boot Security的入门到实战示例教程。我们可以选择适合自己的方式实现认证和授权。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:SpringBoot Security从入门到实战示例教程 - Python技术站