我们正在重新修改我们的产品以删除默认的" anonymousUser" SpringSecurity中的行为,并希望锁定所有URL(通过过滤器安全性),只有几个端点除外。我们无法弄清楚的是如何指定"锁定除X,Y和Z之外的所有内容"
我们的安全设置主要归结为以下内容:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// disable anonymous users
.anonymous().disable()
// don't add ROLE_ to the role...
.authorizeRequests()
.regexMatchers("^/", "^/login", "^/mobile/login", "^/api/auth/.*")
.authenticated()
.and()
;
}
}
我采取的其他路线类似于:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// disable anonymous users
.anonymous().disable()
// don't add ROLE_ to the role...
.authorizeRequests()
.antMatchers("/**")
.authenticated()
.antMatchers("/", "/login", "/mobile/login", "/api/auth/**", "/reservations/**")
.permitAll()
.and()
;
}
}
任何建议/意见将不胜感激。
谢谢!
答案 0 :(得分:14)
我们正在重新修改我们的产品以删除默认的" anonymousUser" SpringSecurity中的行为
我想知道你的意思。根据其余描述,我认为您不需要以下内容(即您应将其删除):
anonymous().disabled()
上面说如果没有用户通过身份验证,用户将为null,这往往导致NullPointerException
s
请记住,对于authorizeRequests()(或intercept-url),排序很重要。您拥有的java配置(稍微重新格式化为readability)
.authorizeRequests()
.antMatchers("/**").authenticated()
.antMatchers("/", "/login", "/mobile/login", "/api/auth/**", "/reservations/**").permitAll()
.and()
将使用以下逻辑:
相反,您应该使用以下内容:
.authorizeRequests()
.antMatchers("/", "/login", "/mobile/login", "/api/auth/**", "/reservations/**").permitAll()
.anyRequest().authenticated()
.and()
注意:antMatchers(" / **")更简洁地表示为anyRequest()
答案 1 :(得分:3)
Rob Winch的答案几乎在所有情况下都是正确的答案,也是我在项目中采用的方法。我认为值得注意的是,另一种可能的方法可能是:
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/assets/**", "/index.html");
}
请注意这是与您之前提交的示例中的方法不同的方法。该方法的参数类型为
HttpSecurity
,而此类型的参数类型为WebSecurity
该代码示例将执行的任务是查找匹配的所有请求,并完全跳过http安全筛选器。因此,如果您想优化一些您知道需要HttpSecurity
提供的功能的请求,那么这可能是一个很好的解决方案。这意味着,如果您使用csrf()
,requestCache()
,headers()
等功能,则不会将其应用于上述示例中的匹配请求(" / assets / **&# 34;," /index.html")
答案 2 :(得分:0)
如果你使用security.xml,我知道你可以做这样的事情
<http use-expressions="true" entry-point-ref="authenticationEntryPoint">
<custom-filter position="BASIC_AUTH_FILTER" ref="loginFilter" />
<intercept-url pattern="/login" access="permitAll" />
<intercept-url pattern="/mobile/login" access="permitAll" />
<intercept-url pattern="/api/auth/**" access="fullyAuthenticated" />
<intercept-url pattern="/**" access="fullyAuthenticated" />
<logout success-handler-ref="logoutHandler" />
</http>
这样做是允许任何人访问登录或移动/登录,但只允许完全通过身份验证的人访问api / auth或网站上的任何其他内容
<intercept-url pattern="/api/auth/**" access="fullyAuthenticated" />
此行可以删除,相同的功能也可以使用。它从上到下开始,因此顶部允许的任何内容都优先。