在spring security 3中,对于某些需要保护的url,可以很容易地实现当没权限的时候,
redirect到一个页面(比如自定义的404.jsp页面)进行显示没权限的信息;
但有的时候,必须要对一些AJAX的请求url也同时判断其是否有权限输出;
如果没权限的话,一般要以JSON的方式返回给用户端,比如弹出一个提示框,显示没权限;
在SPRING security 3中,当没权限的时候,会由spring security 自己的拦截器
AccessDeniedHandler 进行拦截的,因此,可以在这个地方进行扩展自定义,
然后统一返回给前端的都是json的方式,并且在前端的jquery js中,扩展jquery post的
方法,如果对json返回的结果中,有相关“没权限操作”的信息,则弹出错误提示框,
这样,只需要在要用到$ajax提交的页面中,引入js就可以了,下面看代码实现。
1) 首先,实现AccessDeniedHandler 类;
- public class MyAccessDeniedHandlerImpl implements AccessDeniedHandler {
-
-
- public MyAccessDeniedHandlerImpl()
- {
-
- }
- public String getAccessDeniedUrl() {
- return accessDeniedUrl;
- }
-
-
- public void setAccessDeniedUrl(String accessDeniedUrl) {
- this.accessDeniedUrl = accessDeniedUrl;
- }
-
- public MyAccessDeniedHandlerImpl(String accessDeniedUrl)
- {
- this.accessDeniedUrl=accessDeniedUrl;
- }
- private String accessDeniedUrl;
-
-
- @Override
- public void handle(HttpServletRequest req,
- HttpServletResponse resp, AccessDeniedException reason) throws ServletException,
- IOException {
- boolean isAjax = "XMLHttpRequest".equals(req.getHeader("X-Requested-With"));
-
-
- if (isAjax) {
-
- String jsonObject = "{\"message\":\"You are not privileged to request this resource.\","+
-
- String contentType = "application/json";
- resp.setContentType(contentType);
- String jsonObject="noright";
- PrintWriter out = resp.getWriter();
- out.print(jsonObject);
- out.flush();
- out.close();
- return;
- }
- else
- {
-
- String path = req.getContextPath();
- String basePath = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+path+"/";
- resp.sendRedirect(basePath+accessDeniedUrl);
- }
-
-
- }
在上面的处理中,判断如果是ajax处理,则输出json字符串给客户端,否则就
redirect到指定的accessDeniedUrl,
2) 在applicationContext-security.xml中进行设置,如下:
- <http auto-config="true">
- <intercept-url pattern="/admin*" access="ROLE_ADMIN" />
- <access-denied-handler ref="accessDeniedHandler"/>
- </http>
-
-
- <beans:bean id="accessDeniedHandler"
- class="com.test.MyAccessDeniedHandlerImpl">
- <beans:property name="accessDeniedUrl" value="403.jsp" />
- </beans:bean>
3) springsecurity.js
- (function($){
-
- var $_ajax = $.ajax;
-
- $.ajax = function(options){
- var originalSuccess,
- mySuccess,
- success_context;
-
- if (options.success) {
-
- originalSuccess = options.success;
- success_context = options.context ? options.context : $;
-
-
- mySuccess = function(data) {
-
-
-
-
- if (data['access-denied']) {
- if (data.cause==='AUTHENTICATION_FAILURE') {
- alert('登录超时,请重新登录.');
- window.location.href = contextPath + '/';
- } else if (data.cause==='AUTHORIZATION_FAILURE') {
- if (data=="noright")
- {
- alert('对不起,你没有访问该资源的权限.');
- }
- }
- return;
-
-
-
- originalSuccess.apply(success_context, arguments);
- };
-
- options.success = mySuccess;
- }
-
-
- $_ajax.apply($, arguments);
- };
-
- })(jQuery);
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。