保护公共Java Spring-Boot Web应用程序的最佳实践是使用Spring Security库来实现身份验证和授权功能。下面是一个基本的示例代码,演示了如何配置Spring Security来保护Web应用程序:
org.springframework.boot
spring-boot-starter-security
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/public/**").permitAll() // 允许公共访问的URL
.anyRequest().authenticated() // 其他URL需要身份验证
.and()
.formLogin() // 启用表单登录
.loginPage("/login") // 自定义登录页面
.permitAll()
.and()
.logout() // 启用注销
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin").password("{noop}password").roles("ADMIN"); // 在内存中配置用户名、密码和角色
}
}
Login
Login
@RestController
@RequestMapping("/public")
public class PublicController {
@GetMapping("/hello")
public String hello() {
return "Hello, public!";
}
}
这个示例代码中,配置类WebSecurityConfig
继承了WebSecurityConfigurerAdapter
,并重写了configure(HttpSecurity http)
方法来配置哪些URL需要身份验证,哪些URL是公共访问的。在configure(AuthenticationManagerBuilder auth)
方法中,使用inMemoryAuthentication()
在内存中配置了一个用户名为admin、密码为password、角色为ADMIN的用户。
PublicController
是一个处理公共URL的控制器,其中的hello()
方法处理了/public/hello
的GET请求。
使用这些代码示例,并根据实际需求进行适当的修改,可以实现对公共Java Spring-Boot Web应用程序的保护。
上一篇:保护公共端点以防止表单提交
下一篇:保护公共联系表单的API端点