| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx
jopen
9年前发布

shrio自定义realm,权限拦截

一,自定义realm,重写认证,授权,验证权限三个方法

public class UserRealm extends AuthorizingRealm {        @Autowired      private SysUserService userService;        @Autowired      private UserAuthService userAuthService;        private Logger logger = LoggerFactory.getLogger(this.getClass());        /**       * 授权       */      @Override      protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {            SysUser user = (SysUser) principals.getPrimaryPrincipal();          SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();          authorizationInfo.setRoles(userAuthService.findStringRoles(user.getId()));          authorizationInfo.setStringPermissions(userAuthService.findStringPermissions(user.getId()));            return authorizationInfo;      }        /**       * 认证       */      @Override      protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {            logger.info("----------------认证----------------");            UsernamePasswordToken upToken = (UsernamePasswordToken) token;          String username = upToken.getUsername().trim();          String password = "";          if (upToken.getPassword() != null) {              password = new String(upToken.getPassword());          }          SysUser user = userService.login(username, password);            if (user != null) {              SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password.toCharArray(), getName());              return info;          }          return null;      }        //重写权限判断方法,加入正则判断      @Override      public boolean isPermitted(PrincipalCollection principals, String permission) {          AuthorizationInfo info = getAuthorizationInfo(principals);          Collection<String> permissions = info.getStringPermissions();          return permissions.contains(permission) || patternMatch(permissions, permission);      }        /**       * 正则       * @param patternUrlList       * @param requestUri       * @return       */      public boolean patternMatch(Collection<String> patternUrlList, String requestUri) {          boolean flag = false;          for (String patternUri : patternUrlList) {              if (StringUtils.isNotEmpty(patternUri)) {                  Pattern pattern = Pattern.compile(patternUri);                  Matcher matcher = pattern.matcher(requestUri);                  if (matcher.matches()) {                      flag = true;                      break;                  }              }          }          return flag;      }

二、授权filter

isAccessAllowed,拦截方法,返回true表示通过验证,返回false会执行onAccessDenied方法。

public class LoginCheckPermissionFilter extends AuthorizationFilter {        public Logger logger = LoggerFactory.getLogger(getClass());        @Override      protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {          HttpServletRequest httpServletRequest = (HttpServletRequest) request;          String url = httpServletRequest.getRequestURI();          try {              Subject user = SecurityUtils.getSubject();                return user.isPermitted(url);          } catch (Exception e) {              logger.error("check permission error", e);          }          return true;      }        @Override      protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {          Subject subject = getSubject(request, response);          HttpServletRequest httpServletRequest = (HttpServletRequest) request;          HttpServletResponse httpServletResponse = (HttpServletResponse) response;          String method = httpServletRequest.getMethod();          if (subject.getPrincipal() == null) {              saveRequestAndRedirectToLogin(request, response);          } else {              String unauthorizedUrl = getUnauthorizedUrl();              if (StringUtils.hasText(unauthorizedUrl)) {                  if (method.equals("POST")) {                      httpServletResponse.setHeader("Content-Type", "application/json;charset=UTF-8");                      String result = JSON.toJSONString(new BaseResp("没有权限,请联系管理员!", BizConstants.FAIL));                      httpServletResponse.getWriter().write(result);                  } else {                      WebUtils.issueRedirect(request, response, unauthorizedUrl);                  }              } else {                  WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);              }          }          return false;      }  }

三、shiro部分配置

 <property name="securityManager" ref="securityManager"/>      <property name="loginUrl" value="/login"/>      <!--<property name="successUrl" value="/loginOK" />-->      <property name="unauthorizedUrl" value="/noPermission"/>      <property name="filters">          <map>              <entry key="perms" value-ref="loginCheckPermissionFilter"/>              <entry key="user" value-ref="myUserFilter"/>          </map>      </property>        <property name="filterChainDefinitions">          <value>              /favicon.ico = anon              /resources/** = anon              /PoiTemplate/** = anon              /login = anon              /logout = user              /** = user,perms          </value>      </property>  </bean>


来自: http://my.oschina.net/sheldon1/blog/603351

 本文由用户 jopen 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
 转载本站原创文章,请注明出处,并保留原始链接、图片水印。
 本站是一个以用户分享为主的开源技术平台,欢迎各类分享!
 本文地址:https://www.open-open.com/lib/view/open1452912486511.html
Shiro 安全相关