Java 为什么Spring安全性禁止特定资源,而不管其角色是什么?
我正在使用SpringMVC架构开发一个web应用程序,并使用SpringSecurity保护它。我将JPA存储库用于我的持久层。我遇到的问题是,当我试图从应用程序中的特定页面(“添加实现”页面)发送POST请求时,我会收到一个错误页面,其中包含以下消息:Java 为什么Spring安全性禁止特定资源,而不管其角色是什么?,java,spring,spring-security,Java,Spring,Spring Security,我正在使用SpringMVC架构开发一个web应用程序,并使用SpringSecurity保护它。我将JPA存储库用于我的持久层。我遇到的问题是,当我试图从应用程序中的特定页面(“添加实现”页面)发送POST请求时,我会收到一个错误页面,其中包含以下消息: There was an unexpected error (type=Forbidden, status=403). Forbidden 无论我的用户具有哪个角色,都会发生这种情况(有两个角色:admin和vendor)。此外,当我使用a
There was an unexpected error (type=Forbidden, status=403). Forbidden
无论我的用户具有哪个角色,都会发生这种情况(有两个角色:admin
和vendor
)。此外,当我使用antMatchers
和permitAll()
在我的configure(HttpSecurity http)
函数中显式允许有问题的Url时,甚至会发生这种情况。所以问题是,为什么我的POST请求没有被授权
我是Spring Security的新手,可能在其中的任何配置中都犯了严重错误。我将附上所有与Spring security相关的代码,以及相关的控制器
下面是我的配置函数:url/vendor/{id:[0-9]+}/addimpl
是给我带来麻烦的那个。我在这里明确允许它只是为了看看会发生什么,但在发布到它时仍然会出现403
错误(但是GET请求工作正常)
这是我的用户详细信息服务
:
@Service
@Transactional
public class AcvpUserDetailsService implements UserDetailsService {
@Autowired
private AcvpUserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) {
AcvpUser user = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException(username);
}
return new AcvpUserPrincipal(user);
}
}
还有UserDetails类
@Transactional
public class AcvpUserPrincipal implements UserDetails {
/**
* this is necessary for posterity to know whether they can serialize this
* class safely
*/
private static final long serialVersionUID = 3771770649711489402L;
private AcvpUser user;
public AcvpUserPrincipal(AcvpUser user) {
this.user = user;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return Collections.singletonList(new
SimpleGrantedAuthority(user.getRole()));
}
@Override
public String getPassword() {
return user.getPassword(); // this is now the encrypted password
}
@Override
public String getUsername() {
return user.getUsername();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
以下是我的pom文件中的Spring安全依赖项:
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<scope>runtime</scope>
</dependency>
最后,我将包括在SecurityConfiguration类上设置“debug”的输出。这可能会有帮助,但我没能从中得到任何东西
Request received for POST '/vendor/33/addimpl':
org.apache.catalina.connector.RequestFacade@3b981cfd
servletPath:/vendor/33/addimpl
pathInfo:null
headers:
host: localhost:8080
connection: keep-alive
content-length: 402
cache-control: max-age=0
origin: http://localhost:8080
upgrade-insecure-requests: 1
content-type: application/x-www-form-urlencoded
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
referer: http://localhost:8080/vendor/33/addimpl
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
cookie: JSESSIONID=1121ADD15A2E23786464649647B62356
Security filter chain: [
WebAsyncManagerIntegrationFilter
SecurityContextPersistenceFilter
HeaderWriterFilter
CsrfFilter
LogoutFilter
UsernamePasswordAuthenticationFilter
RequestCacheAwareFilter
SecurityContextHolderAwareRequestFilter
AnonymousAuthenticationFilter
SessionManagementFilter
ExceptionTranslationFilter
FilterSecurityInterceptor
]
************************************************************
2018-12-21 09:49:32.570 INFO 4392 --- [nio-8080-exec-3] Spring Security
Debugger :
************************************************************
Request received for POST '/error':
org.apache.catalina.core.ApplicationHttpRequest@73210c23
servletPath:/error
pathInfo:null
headers:
host: localhost:8080
connection: keep-alive
content-length: 402
cache-control: max-age=0
origin: http://localhost:8080
upgrade-insecure-requests: 1
content-type: application/x-www-form-urlencoded
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
referer: http://localhost:8080/vendor/33/addimpl
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
cookie: JSESSIONID=1121ADD15A2E23786464649647B62356
Security filter chain: [
WebAsyncManagerIntegrationFilter
SecurityContextPersistenceFilter
HeaderWriterFilter
CsrfFilter
LogoutFilter
UsernamePasswordAuthenticationFilter
RequestCacheAwareFilter
SecurityContextHolderAwareRequestFilter
AnonymousAuthenticationFilter
SessionManagementFilter
ExceptionTranslationFilter
FilterSecurityInterceptor
]
在将POST请求发送到/vendor/33/addimpl
之后,如果出现验证错误,我希望被重定向回供应商页面,或者再次重定向到“添加实现”页面(我从中发布的页面)。但这些都没有发生。我将被发送到默认错误页面 默认情况下启用CSRF(跨站点请求伪造)
您可能希望在AcvpUserDetailsService类中关闭它
加:
请在此处阅读有关CSRF的更多信息:正如其他人所说,问题在于CSRF已启用,并且CSRF令牌未随POST请求一起发送。然而,我并不希望完全禁用CSRF,因为我希望该应用程序不受CSRF攻击。事实证明,在这个应用程序中添加CSRF令牌非常简单。我使用thymeleaf作为模板工具,在已经发布的任何链接中都找不到这个简单的解决方案,但可以在这里找到: 我在登录表单中包含了以下代码:
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
根据上面的链接,这是所有必要的,但对我来说,直到我在所有表单操作中添加了thymeleaf
th:
符号,它才起作用。因此,我在POST请求中没有看到CSRF令牌,而不是执行。默认情况下,Spring Security已启用它。非常感谢。成功了。但是禁用csrf是个好主意吗?为什么我的应用程序没有在请求中提供csrf令牌?看起来我可以在您和Angelo Immedia向我推荐的链接中找到答案。谢谢
@RequestMapping(value = "/vendor/{id:[0-9]+}/addimpl", method = RequestMethod.GET)
public String getAddImplementation(Model model, @PathVariable("id") Long id)
throws VendorNotFoundException {
Vendor vendor = vendorRepository.findById(id)
.orElseThrow(VendorNotFoundException::new);
model.addAttribute("vendor", vendor);
model.addAttribute("edit", false);
model.addAttribute("moduleTypes", ModuleType.values());
ImplementationAddForm backingObject = new ImplementationAddForm();
model.addAttribute("form", backingObject);
return "implementation-add-edit";
}
@RequestMapping(value = "/vendor/{id:[0-9]+}/addimpl", method = RequestMethod.POST)
public String saveImplementation(@PathVariable("id") Long id,
@ModelAttribute("implementation") @Valid ImplementationAddForm form,
BindingResult bindingResult, Model model, RedirectAttributes ra)
throws VendorNotFoundException {
Vendor vendor = vendorRepository.findById(id)
.orElseThrow(VendorNotFoundException::new);
if (bindingResult.hasErrors()) {
model.addAttribute("vendor", vendor);
model.addAttribute("edit", false);
model.addAttribute("moduleTypes", ModuleType.values());
model.addAttribute("form", form);
return "implementation-add-edit";
} else {
Implementation i = form.buildEntity();
i.setVendor(vendor);
implementationRepository.save(i);
return "redirect:/vendor/" + id;
}
}
Request received for POST '/vendor/33/addimpl':
org.apache.catalina.connector.RequestFacade@3b981cfd
servletPath:/vendor/33/addimpl
pathInfo:null
headers:
host: localhost:8080
connection: keep-alive
content-length: 402
cache-control: max-age=0
origin: http://localhost:8080
upgrade-insecure-requests: 1
content-type: application/x-www-form-urlencoded
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
referer: http://localhost:8080/vendor/33/addimpl
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
cookie: JSESSIONID=1121ADD15A2E23786464649647B62356
Security filter chain: [
WebAsyncManagerIntegrationFilter
SecurityContextPersistenceFilter
HeaderWriterFilter
CsrfFilter
LogoutFilter
UsernamePasswordAuthenticationFilter
RequestCacheAwareFilter
SecurityContextHolderAwareRequestFilter
AnonymousAuthenticationFilter
SessionManagementFilter
ExceptionTranslationFilter
FilterSecurityInterceptor
]
************************************************************
2018-12-21 09:49:32.570 INFO 4392 --- [nio-8080-exec-3] Spring Security
Debugger :
************************************************************
Request received for POST '/error':
org.apache.catalina.core.ApplicationHttpRequest@73210c23
servletPath:/error
pathInfo:null
headers:
host: localhost:8080
connection: keep-alive
content-length: 402
cache-control: max-age=0
origin: http://localhost:8080
upgrade-insecure-requests: 1
content-type: application/x-www-form-urlencoded
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
referer: http://localhost:8080/vendor/33/addimpl
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
cookie: JSESSIONID=1121ADD15A2E23786464649647B62356
Security filter chain: [
WebAsyncManagerIntegrationFilter
SecurityContextPersistenceFilter
HeaderWriterFilter
CsrfFilter
LogoutFilter
UsernamePasswordAuthenticationFilter
RequestCacheAwareFilter
SecurityContextHolderAwareRequestFilter
AnonymousAuthenticationFilter
SessionManagementFilter
ExceptionTranslationFilter
FilterSecurityInterceptor
]
http.csrf().disable();
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />