在WebSecurityConfigurerAdapter中正确使用WebSecurity

在WebSecurityConfigurerAdapter中正确使用WebSecurity,第1张

在WebSecurityConfigurerAdapter中正确使用WebSecurity

您的示例意味着Spring(Web)安全性将忽略与您定义的表达式匹配的URL模式

("/static/**")
。该URL被Spring
Security跳过,因此不安全。

允许添加Spring Security应该忽略的RequestMatcher实例。Spring Security提供的Web
Security(包括SecurityContext)在匹配的HttpServletRequest上将不可用。通常,注册的请求应该仅是静态资源的请求。对于动态请求,请考虑映射请求以允许所有用户使用。

有关更多信息,请参见WebSecurity
API文档。

您可以根据需要设置任意数量的安全或不安全URL模式。
使用Spring Security,您可以为应用程序的Web层提供 身份验证访问控制
功能。您还可以限制具有指定角色的用户访问特定的URL,依此类推。

阅读Spring Security参考以获取更多详细信息:http :
//docs.spring.io/spring-
security/site/docs/current/reference/html/

URL模式的排序优先级

当将指定的模式与传入的请求进行匹配时,将按照声明元素的顺序进行匹配。因此,最具体的匹配模式应排在最前面,最一般的匹配模式应排在最后。

http.authorizeRequests()方法有多个子代,每个子代都按照声明它们的顺序考虑。

模式始终按照定义的顺序进行评估。因此,重要的是,在列表中将较高的特定模式定义为比较低的特定模式高。

在这里阅读更多详细信息:[http](http://docs.spring.io/spring-
security/site/docs/current/reference/htmlsingle/#filter-security-interceptor)
//docs.spring.io/spring-
security/site/docs/current/reference/htmlsingle/#filter-security-
interceptor
例子1

WebSecurity

ignoring()
方法的常规用法省略了Spring Security,并且Spring
Security的功能均不可用。WebSecurity基于HttpSecurity
(在XML配置中,您可以编写以下代码:)
<http pattern="/resources/**" security="none"/>

@Overridepublic void configure(WebSecurity web) throws Exception {    web        .ignoring()        .antMatchers("/resources/**")        .antMatchers("/publics/**");}@Overrideprotected void configure(HttpSecurity http) throws Exception {    http        .authorizeRequests()        .antMatchers("/admin/**").hasRole("ADMIN")        .antMatchers("/publics/**").hasRole("USER") // no effect        .anyRequest().authenticated();}

上面的示例中的WebSecurity让Spring忽略

/resources/**
/publics/**
。因此
.antMatchers("/publics/**").hasRole("USER")
,不考虑HttpSecurity中的。

这将完全省略来自安全过滤器链的请求模式。请注意,与此路径匹配的所有内容都将不应用身份验证或授权服务,并且可以自由访问。

例子2

模式总是 按顺序 评估。以下匹配无效,因为第一个匹配每个请求,并且永远不会应用第二个匹配:

@Overrideprotected void configure(HttpSecurity http) throws Exception {    http        .authorizeRequests()        .antMatchers("/**").hasRole("USER")        .antMatchers("/admin/**").hasRole("ADMIN"):}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5600197.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-15
下一篇2022-12-15

发表评论

登录后才能评论

评论列表(0条)

    保存