比如说在未登录淘宝时,我们可以访问淘宝的首页,可是在访问购物车时就会跳出登录权限。
重载configure(HttpSecurity)方法通过拦截器来保护请求。
@Override
protected void configure(HttpSecurity http) throws Exception{
http
.authorizeRequests()
.antMatchers("/spitters/me").authenticated()
.antMatchers(HttpMethod.POST,"/spittles").authenticated()
.anyRequest().permitAll();
}
上面的代码实现了访问/spitters/me页面要进行登录权限的认证。
.antMatchers 或 .regexMatchers
一个是ant的通配符一个是正则格式的
authenticated()的意思是验证用户是否登录认证。
如果用户没有认证,Spring Security的Filter将会捕获该请求,并将用户重定向到应用的登录界面。同时permitAll()方法允许请求没有任何的安全限制。
常用的还有hasRole("xxx")是否具备给定角色
hasAuthority("")是否具备给定权限
access(String)给定spEL为true就允许访问。
注意:将最不具体的路径(如anyRequest())放在最后面。如果不这样做,那不具体的路径配置将会覆盖掉更为具体的路径配置。
使用SpEL(Spring表达式)进行安全保护
上面的大多数方法都是一维的,如hasRole()方法和hasIpAddress()方法没办法同时限制一个请求路径。 但是可以使用上面的access()方法检测spEL语言
.antMatchers("/spitter/me")
.access("hasRole('SPITTER') and hasIpAddress('127.0.0.1')");
就可实现多维检测
强制通道的安全性
传递到configure()方法中的HttpSecurity对象,除了具有authorizeRequests()方法以外,还有一个requiresChannel()方法,借助这个方法能够为各种URL模式声明所要求的通道(如HTTPS)。
这是因为通过HTTP发送的数据没有经过加密,黑客就有机会拦截请求并且能够看到他们想看的数据。这就是为什么敏感信息要通过HTTPS来加密发送的原因。
@Override
protected void configure(HttpSecurity http) throws Exception{
http
.authorizeRequests()
.antMatchers("/spitter/me").hasRole("SPITTER")
.antMatchers(HttpMethod.POST,"/spittles").hasRole("SPITTER")
.anyRequest().permitAll();
.and()
.requiresChannel()
.antMatchers("spitter/form").requiresSecure(); //需要
}
不论何时,只要是对“/spitter/form”的请求,Spring Security都视为需要安全通道(通过调用requiresChannel()确定的)并自动将请求重定向到HTTPS上。
与之相反,有些页面并不需要通过HTTPS传送。例如,首页不包含任何敏感信息,因此并不需要通过HTTPS传送。我们可以使用requiresInsecure()代替requiresSecure()方法,将首页声明为始终通过HTTP传送:
防止跨站请求伪造
@Override
protected void configure(HttpSecurity http) throws Exception{
http
.authorizeRequests()
.antMatchers("/spitter/me").hasRole("SPITTER")
...
.and()
.csrf()
.disable(); //禁用CSRF防护功能
}
网友评论