近日用spring security 3 配置权限,遇到不少问题。网上查找,学习,一个一个的问题迎刃而解,现记录于此,备忘。

在spring security 3配置文件中配置<access-denied-handler error-page="" />后, 在自定义AccessDecisionManager类中抛出AccessDeniedException异常的时候并没有跳入相应的error- page页面, 所以只要通过加入AccessDeniedHandler来控制跳转到相应的路径。跳转路径可以在mvc的controller中映射并处理相关数据。

1. 修改

<access-denied-handler error-page="" />

<access-denied-handler ref="accessDeniedHandler" />

accessDeniedHandler为自定义的Handler


2. 在SS3配置文件中加入

<beans:bean id="accessDeniedHandler"
class="com.hhdem.laihecai.security.LaihecaiAccessDeniedHandler">
<beans roperty name="accessDeniedUrl" value="/accessDenied" />
</beans:bean>

此处的class="com.hhdem.laihecai.security.LaihecaiAccessDeniedHandler"是AccessDeniedHandler的实现类,也可以直接配置成spring security 的默认实现类,为errorPage指定转向页面。

<beans:bean id="accessDeniedHandler"
     class="org.springframework.security.web.access.AccessDeniedHandlerImpl">
  <beans:property name="errorPage" value="/backend/admin/error403"/>
</beans:bean>


其实如果只是简单的指定转向页面,到这一些就可以完成功能了,如果还需要处理一些其他数据,就需要新建实现AccessDeniedHandler的类,

3. 新建AccessDeniedHandler自定义类

public class LaihecaiAccessDeniedHandler implements AccessDeniedHandler {
    private String accessDeniedUrl;
 
    public LaihecaiAccessDeniedHandler() {
    }
 
    public LaihecaiAccessDeniedHandler(String accessDeniedUrl) {
        this.accessDeniedUrl = accessDeniedUrl;
    }
 
   
 public void handle(HttpServletRequest request, HttpServletResponse 
response, AccessDeniedException accessDeniedException) throws 
IOException, ServletException {
        response.sendRedirect(accessDeniedUrl);
        String deniedMessage = accessDeniedException.getMessage();
        String rp = request.getRequestURI();
        request.getSession().setAttribute(Constants.ACCESS_DENIED_MSG, deniedMessage);
    }
 
    public String getAccessDeniedUrl() {
        return accessDeniedUrl;
    }
 
    public void setAccessDeniedUrl(String accessDeniedUrl) {
        this.accessDeniedUrl = accessDeniedUrl;
    }
}



相关推荐:java - Proper way to determine required authority in spring security access denied handler

o a url to which access is denied based on @Secured("role") annotations, I need to know why access was denied in the access denied handler (or actually the role(s) required to access the resource) so I can redirect the u

相关推荐:java - spring security - access-denied-handler

security is working but when I visit /admin without the required privileges (ROLE_ADMIN), Spring Security is just redirecting to the root page which is my login form page.I want to be able to redirect the user to /acc

快照源:http://my.oschina.net/guhai2004/blog/369496