安全 Restful Spring 启动应用程序
Secure Restful Spring boot application
我使用 Spring Boot 开发了一个 RESTful 网络服务。输入 URL 后,将返回 JSON 资源。服务器端不完全符合 JSON API 但它可以工作。
现在我想通过简单的 HTTP 基本身份验证来保护 RESTful 服务。简单地说,如果客户端发送 HTTP GET
以访问
http://mycompany.com/restful/xyz
它将收到 HTTP 未验证错误,除非请求配置正确 Authorization basic XXXXXXXX
。 xxxxxx是user:pwd
的加密形式
我想用 Spring 安全来做到这一点。经过一番谷歌搜索后,我可能需要创建一些 class,例如:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
....
}
@Override
protected void configure(HttpSecurity http) throws Exception {
....
}
}
有两点我需要明白:
我发现的大多数 Spring 安全示例在某种程度上与使用 Spring MVC 的 Web 应用程序相关,但我确信它可以用于如上所示的场景 -独立的 Web 服务(在 Tomcat 中,但不是 Web 应用程序);
任何人都可以在上面的两种方法中显示一些代码片段,其效果是只允许某些 user/pwd 将过滤器传递给资源,
http://mycompany.com/restful/xyz
否则返回HTTP认证错误码。
有人可以帮忙吗?
你可以有这样的东西:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/restful/**").hasRole("ROLE_USER").and().httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("john").password("mypass").roles("ROLE_USER");
}
}
我使用 Spring Boot 开发了一个 RESTful 网络服务。输入 URL 后,将返回 JSON 资源。服务器端不完全符合 JSON API 但它可以工作。
现在我想通过简单的 HTTP 基本身份验证来保护 RESTful 服务。简单地说,如果客户端发送 HTTP GET
以访问
http://mycompany.com/restful/xyz
它将收到 HTTP 未验证错误,除非请求配置正确 Authorization basic XXXXXXXX
。 xxxxxx是user:pwd
我想用 Spring 安全来做到这一点。经过一番谷歌搜索后,我可能需要创建一些 class,例如:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
....
}
@Override
protected void configure(HttpSecurity http) throws Exception {
....
}
}
有两点我需要明白:
我发现的大多数 Spring 安全示例在某种程度上与使用 Spring MVC 的 Web 应用程序相关,但我确信它可以用于如上所示的场景 -独立的 Web 服务(在 Tomcat 中,但不是 Web 应用程序);
任何人都可以在上面的两种方法中显示一些代码片段,其效果是只允许某些 user/pwd 将过滤器传递给资源,
http://mycompany.com/restful/xyz
否则返回HTTP认证错误码。
有人可以帮忙吗?
你可以有这样的东西:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/restful/**").hasRole("ROLE_USER").and().httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("john").password("mypass").roles("ROLE_USER");
}
}