保护Spring Boot应用程序的一种常见方法是使用Spring Security库。下面是一些代码示例,演示如何使用Spring Security来保护刚刚暴露的端点。
首先,您需要将Spring Security添加为项目的依赖项。在您的pom.xml文件中添加以下依赖项:
...
org.springframework.boot
spring-boot-starter-security
...
接下来,在您的应用程序中创建一个安全配置类SecurityConfig.java,该类扩展了WebSecurityConfigurerAdapter:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin").password("{noop}password").roles("ADMIN");
}
}
在上面的代码中,我们使用了内存身份验证,并创建了一个名为admin的用户,密码是password,并赋予ADMIN角色。
现在,您可以使用上述配置保护您的端点。例如,假设您的应用程序有一个名为/my-endpoint的端点,您可以在应用程序类中使用@RequestMapping
注解来保护它:
@RestController
public class MyController {
@RequestMapping("/my-endpoint")
public String myEndpoint() {
return "Hello, World!";
}
}
通过添加以下配置,将需要身份验证才能访问/my-endpoint:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
return new OAuth2MethodSecurityExpressionHandler();
}
}
上述配置使得在方法级别进行安全控制成为可能。
完成上述步骤后,您的Spring Boot应用程序的刚刚暴露的端点将受到保护。对于未经身份验证的用户,将返回401 Unauthorized错误。
下一篇:保护GCP云函数的HTTP端点