我正在尝试向我的 RestController 添加身份验证,但我找不到任何好的文档或任何带有 Java 配置的示例。
我尝试了这个,但它不起作用(我无需登录即可访问所有请求)
我的 Controller 带有@PreAuthorize注释
@RestController
@RequestMapping("/api/hello")
public class HelloController {
@RequestMapping(value = "/say", method = RequestMethod.GET)
public String sayHello() {
return "hello";
}
@PreAuthorize("hasRole('ROLE_USER')")
@RequestMapping(value = "/say/user", method = RequestMethod.GET)
public String sayHelloWithUserProtection(){
return "Hello USER";
}
@PreAuthorize("hasRole('ROLE_ADMIN')")
@RequestMapping(value = "/say/admin", method = RequestMethod.GET)
public String sayHelloWithAdminrProtection(){
return "Hello ADMIN";
}
}
安全配置
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@ComponentScan(basePackages = {"com.test.server.security"})
public class SecurityConfig {
@Autowired
public void configureAuthentification(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER").and()
.withUser("admin").password("admin").roles("USER","ADMIN");
}
@Configuration
public static class ApiWebConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/**")
.formLogin();
}
}
}
安全Web应用程序初始化器
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
}
我怎样才能让它发挥作用?
有什么好的教程可以使用 Java 配置使用 JPA(或 JDBC?)将基于 REST token (保存 session key 和其他自定义值的 token )保存在数据库中的身份验证吗?
最佳答案
删除 formLogin()。您需要保持 REST 应该是无状态的心态。以这种方式使用表单登录并不是纯粹的 REST。
您可以使用 Spring 安全链创建一个精细的屏蔽过滤器,如下所示(随机添加一些内容以创建更完整的过滤器。Spring Security 通过过滤器工作,这意味着您需要在启动之前创建一个实际的过滤器。具体来说,您在将请求与路径匹配之前需要对其进行授权。
http.authorizeRequests()
.antMatchers("/login").permitAll()
.antMatchers("/say/user/").hasRole("USER")
.antMatchers("/say/admin").hasRole("ADMIN")
.anyRequest().authenticated();
上面的代码应该是 self 解释的。如果没有,我会尽力详细说明。
对于基于 token 的登录,这是一个好主意,但您不应该自己动手。 Spring 具有出色的 Oauth 支持,开始使用它来保护您的 REST API 非常棒。
本教程非常详细地解释了它,并且应该可以帮助您进一步构建更好的 API。 http://spring.io/guides/tutorials/bookmarks/
另外,请确保您在此处阅读了 Fowler 关于 REST 的著作 http://martinfowler.com/articles/richardsonMaturityModel.html
关于java - Spring Security 方法级安全性与 Java 配置 + REST 身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27123182/