shiro修改没有登录或者session失效,根据ajax返回json

转载地址:https://blog.csdn.net/football98/article/details/76660920

当使用shiro框架,进行权限控制时,没有登录或者session失效,进行ajax请求时,不会跳转会登录页面,仅仅不返回正确结果。

因此,需要解决对ajax请求进行特殊处理。

        1、重新FormAuthenticationFilter类onAccessDenied方法。让其根据不同的请假方式,返回不同的结果。

  1. import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
  2. import javax.servlet.ServletRequest;
  3. import javax.servlet.ServletResponse;
  4. import javax.servlet.http.HttpServletRequest;
  5. import java.io.PrintWriter;
  6. public class ShiroFormAuthenticationFilter extends FormAuthenticationFilter {
  7. @Override
  8. protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
  9. if( this.isLoginRequest(request, response)) {
  10. if( this.isLoginSubmission(request, response)) {
  11. return this.executeLogin(request, response);
  12. } else {
  13. return true;
  14. }
  15. } else {
  16. String header = ((HttpServletRequest) request).getHeader( "Content-Type");
  17. if(header != null && header.equals( "application/x-www-form-urlencoded")){
  18. response.setCharacterEncoding( "UTF-8");
  19. PrintWriter out = response.getWriter();
  20. out.print( "{\"isOver\" : true }");
  21. out.flush();
  22. out.close();
  23. } else{
  24. this.saveRequestAndRedirectToLogin(request, response);
  25. }
  26. return false;
  27. }
  28. }
  29. }
       2、修改shiro配置文件,添加拦截器。

  1. <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
  2. <property name="securityManager" ref="securityManager"> </property>
  3. <property name="loginUrl" value="/"> </property>
  4. <property name="unauthorizedUrl" value="/"> </property>
  5. <property name="filters">
  6. <map>
  7. <entry key="authc">
  8. <bean class="zteict.qinhuangdao.framework.common.shiro.shiro.ShiroFormAuthenticationFilter"> </bean>
  9. </entry>
  10. </map>
  11. </property>
  12. <!-- 授权配置 -->
  13. <property name="filterChainDefinitions">
  14. <value>
  15. <!--与用户登录有关的权限-->
  16. /components/** = anon
  17. /css/** = anon
  18. /images/** = anon
  19. /lib/** = anon
  20. /LoginController.js = anon
  21. /loginController/login.do = anon
  22. <!--权限授权-->
  23. /** = authc
  24. </value>
  25. </property>
  26. </bean>
        3、前台页面统一处理ajax请求,这里系统中使用的是angularjs,分装post请求service,前台使用其他js框架的,请自行修改。

  1. /**
  2. * 封装post请求
  3. * @param url
  4. * @param data
  5. * @param callback
  6. */
  7. var commPost = function (url,data,callback) {
  8. $http({
  9. method: 'POST',
  10. url:baseUrl+url,
  11. data : data
  12. }).then( function(result) {
  13. if(result.data.isOver != undefined && result.data.isOver){
  14. //跳转页面
  15. window.location.href = baseUrl+ "pages/common/login/login.html";
  16. } else{
  17. callback(result.data);
  18. }
  19. });
  20. };


猜你喜欢

转载自blog.csdn.net/m0_38053538/article/details/80872904