成功登录后弹簧安全始终给予拒绝访问页面
问题描述:
我为我的crud应用程序使用弹簧安全功能。即使成功登录后,spring也会重定向到访问被拒绝的页面。成功登录后弹簧安全始终给予拒绝访问页面
这是我的配置文件
<security:global-method-security secured-annotations="enabled" pre-post-annotations="enabled"/>
<security:http auto-config="true" use-expressions="true">
<security:intercept-url pattern="/" access="permitAll"/>
<security:intercept-url pattern="/**" access="hasRole('ROLE_ADMIN')"/>
<security:form-login default-target-url="/employees"
authentication-failure-url="/" always-use-default-target="true"
authentication-success-handler-ref="UrlAuthenticationSuccessHandler"/>
</security:http>
<beans:bean id="UrlAuthenticationSuccessHandler"
class="com.sowmith.security.UrlAuthenticationSuccessHandler" />
<security:authentication-manager erase-credentials="false">
<security:authentication-provider>
<security:user-service>
<security:user name="sowmith" password="reddy" authorities="hasRole('ROLE_ADMIN')"/>
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
控制器类
@RequestMapping(value="/")
public String welcome(){
return "welcome";
}
@RequestMapping(value = "/employees", method = RequestMethod.GET)
//@PreAuthorize("isAuthenticated()")
public String listEmployee(Model model) {
model.addAttribute("employee", new Employee());
model.addAttribute("listEmployee", employeeService.listEmployee());
model.addAttribute("user", getPrincipal());
return "employee";
}
AuthenticationsuccessHandler类
protected void handle(HttpServletRequest request,HttpServletResponse response,
Authentication authentication) throws IOException{
String targetUrl = determineTargetUrl(authentication);
if(response.isCommitted()){
log.debug("Response has already been committed. Unable to redirect to " + targetUrl);
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
protected String determineTargetUrl(Authentication authentication){
boolean permitAll = false;
boolean isAdmin = false;
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
for(GrantedAuthority grantedAuthority : authorities){
if (grantedAuthority.getAuthority().equals("permitAll")) {
permitAll = true;
} else if (grantedAuthority.getAuthority().equals("hasRole('ROLE_ADMIN')")) {
isAdmin = true;
}
}
if (permitAll){
return "/";
} else if (isAdmin) {
return "/employees";
} else {
throw new IllegalStateException();
}
在确定目标URL方法,是检查的作用,并重定向到目标网址。但它没有击中控制器。
答
指定这样
<security:user name="sowmith" password="reddy" authorities="ROLE_ADMIN"/>
你的春季安全XML文件的认证管理器标签管理员然后改变,如果这是检查你的AuthenticationSuccessHandler类角色
else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN"))
+0
我条件已经通过“hasRole(ROLE_ADMIN)”指定角色 –
+0
在基于xml的配置中,我怀疑hasRole表达式适用于指定用户权限,就像它可以用来确定acc对于给定的url模式,这是正确的。尽管如此,我仍然有待纠正。这就是我建议你应该排除其他因素而不是使事情复杂化的原因。 – Perry
分享您UrlAuthenticationSuccessHandler类 –