spring security与 shiro的 简单对比

spring security 接口 RequestMatcher 用于匹配路径,对路径做特殊的请求,类似于shiro的

抽象类 PathMatchingFilter,但是 RequestMatcher 作用粒度更细,例如可只另某些路径受

csrf保护,spring security也 可以自定义filter,来干扰正常的filter运作 

下面是 shiro 与 spring security 部分实现

shiro 自定义过滤器部分实现

public class SysUserFilter extends PathMatchingFilter {

    @Autowired
    private UserService userService;

    @Override
    protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {

        String username = (String) SecurityUtils.getSubject().getPrincipal();
        request.setAttribute(Constants.CURRENT_USER, userService.list("username",username).get(0));
        return true;
    }
}

 spring security 请求匹配器

public class CsrfSecurityRequestMatcher implements RequestMatcher {
    protected Log log = LogFactory.getLog(getClass());
    private Pattern allowedMethods = Pattern
            .compile("^(GET|HEAD|TRACE|OPTIONS)$");
    /**
     * 需要排除的url列表
     */
    private List<String> execludeUrls;

    @Override
    public boolean matches(HttpServletRequest request) {
        if (execludeUrls != null && execludeUrls.size() > 0) {
            String servletPath = request.getServletPath();
            for (String url : execludeUrls) {
                if (servletPath.contains(url)) {
                    log.info("++++"+servletPath);
                    return false;
                }
            }
        }

        System.out.println("*****:-:"+!allowedMethods.matcher(request.getMethod()).matches());
        return !allowedMethods.matcher(request.getMethod()).matches();
    }

    public List<String> getExecludeUrls() {
        return execludeUrls;
    }

    public void setExecludeUrls(List<String> execludeUrls) {
        this.execludeUrls = execludeUrls;
    }
}
扫描二维码关注公众号,回复: 3346220 查看本文章

spring security 和 shiro 对加密都提供了各种各样的支持 例如 BCryptPasswordEncoder 采用 SHA-256 + 随机盐 + 秘钥 对密码进行加密。shrio 的 SimpleHash 提供散列算法的支持,生成数据的摘要信息.

shiro 散列 加密

String newPassword = new SimpleHash(
algorithmName,
user.getPassword(),
ByteSource.Util.bytes(user.getCredentialsSalt()),
hashIterations).toHex();

spring security

BCryptPasswordEncoder bpe = new BCryptPasswordEncoder();
user.setPassword(bpe.encode(user.getPassword()));

shiro 的 AuthorizingRealm 的 doGetAuthorizationInfo方法 与 doGetAuthenticationInfo 一个 是定义 获取 用户权限信息 的方法,一 个 是 定义用户身份认证及获取用户身份的方法,

而 spring security 也有 资源 角色 授权器 FilterInvocationSecurityMetadataSource,定义资源url 与 角色权限的关系 , 决策 管理器 AccessDecisionManager 定义权限满足的规则,

下面是 shiro realm 部分 代码例子

shiro 自定义 realm

@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
// 最终判断逻辑是 WildcardPermission implies resource [role *]

String username = (String)principals.getPrimaryPrincipal();
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

RoleVo roleVo = userService.findRoles(username);
Set<String> roleNameSet = roleVo.getRoleNameSet();
Set<String> resourceNameSet = roleVo.getResourceNameSet();

System.out.println("boolean:"+ resourceNameSet.contains("user:view"));

authorizationInfo.setRoles(roleNameSet);
authorizationInfo.setStringPermissions(resourceNameSet);




return authorizationInfo;
}



/*
用于身份认证, 一般登录时就会调用此方法
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = (String)token.getPrincipal();
try {
List<User> userList = userService.list("username", username);
User user = userList.get(0);

if(user == null) {
throw new UnknownAccountException();//没找到帐号
}

if(Boolean.TRUE.equals(false)) {
throw new LockedAccountException(); //帐号锁定
}

//交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配,如果觉得人家的不好可以自定义实现
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
user.getUsername(), //用户名
user.getPassword(), //密码
ByteSource.Util.bytes(user.getUsername()+user.getSalt()),//salt=username+salt
getName() //realm name
);
return authenticationInfo;

} catch (Exception e) {
e.printStackTrace();
}

return null;




}

spring security 对 前端安全 有 很好的实现,

例如 防止

CSRF 跨站请求伪造,是一种挟制用户在当前已登录的web应用上执行非本意操作的攻击方法

XSS 跨站脚本,是 一种 网站应用程序的安全漏洞攻击,是代码注入的一种,它允许恶意用户将代码注入到网页上,其他用户在观看网页时就会受到影响

欢迎加入 微服务交流群 222700500

猜你喜欢

转载自blog.csdn.net/weixin_39639119/article/details/82714312