【发布时间】:2017-06-21 10:19:56
【问题描述】:
我已经使用 Spring Boot 和由 AngularJS 提供支持的单页应用程序创建了 REST API。
问题是如何防止所有人使用我在互联网上公开提供的 REST api?我希望它只允许在我的网页上使用。
我不能从角度使用任何秘密/密码/令牌,因为任何人都可以看到它。
【问题讨论】:
标签: angularjs spring rest security
我已经使用 Spring Boot 和由 AngularJS 提供支持的单页应用程序创建了 REST API。
问题是如何防止所有人使用我在互联网上公开提供的 REST api?我希望它只允许在我的网页上使用。
我不能从角度使用任何秘密/密码/令牌,因为任何人都可以看到它。
【问题讨论】:
标签: angularjs spring rest security
Spring 安全性可以帮助解决这个问题。您可以定义一些只有特定角色的特定用户才能访问的 url。
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
protected void configures(HttpSecurity http) throws Exception {
http.exceptionHandling()
.accessDeniedPage("/error").and()
.authorizeRequests()
.antMatchers("/api/**").hasAnyRole("USER_ROLE");
}
}
因此,只有角色为“USER_ROLE”的人才能访问任何以“/api”开头的网址。 为了拥有此功能,您必须实现一个登录系统,在成功登录后将“USER_ROLE”分配给用户。
在 AngularJs 部分,这很容易。您只需向 REST api 发出一个 http 请求,因为浏览器保存 cookie 和 JSESSIONID,它将与请求头中的请求一起发送。 Spring 将其拾取并检查具有该 JSESSIONID 的用户是否有权访问该 url。
【讨论】: