[转] shiro简单配置

shiro(1)

注:这里只介绍spring配置模式。

因为官方例子虽然中有更加简洁的ini配置形式,但是使用ini配置无法与spring整合。而且两种配置方法一样,只是格式不一样。

涉及的jar包

Jar包名称

版本

核心包shiro-core

1.2.0

Web相关包shiro-web

1.2.0

缓存包shiro-ehcache

1.2.0

与spring整合包shiro-spring

1.2.0

Ehcache缓存核心包ehcache-core

2.5.3

Shiro自身日志包slf4j-jdk14

1.6.4
使用maven时,在pom中添加依赖包

[html] view plain copy
在CODE上查看代码片派生到我的代码片


org.apache.shiro
shiro-core
1.2.0


org.apache.shiro
shiro-web
1.2.0


org.apache.shiro
shiro-ehcache
1.2.0


org.apache.shiro
shiro-spring
1.2.0


net.sf.ehcache
ehcache-core
2.5.3


org.slf4j
slf4j-jdk14
1.6.4

Spring整合配置

1.在web.xml中配置shiro的过滤器
[html] view plain copy
在CODE上查看代码片派生到我的代码片



shiroFilter

org.springframework.web.filter.DelegatingFilterProxy



shiroFilter
/*

2.在Spring的applicationContext.xml中添加shiro配置
[html] view plain copy
在CODE上查看代码片派生到我的代码片








/home* = anon
/ = anon
/logout = logout
/role/** = roles[admin]
/permission/** = perms[permssion:look]
/** = authc


securityManager:这个属性是必须的。

loginUrl:没有登录的用户请求需要登录的页面时自动跳转到登录页面,不是必须的属性,不输入地址的话会自动寻找项目web项目的根目录下的”/login.jsp”页面。

successUrl:登录成功默认跳转页面,不配置则跳转至”/”。如果登陆前点击的一个需要登录的页面,则在登录自动跳转到那个需要登录的页面。不跳转到此。

unauthorizedUrl:没有权限默认跳转的页面。

过滤器简称

过滤器简称

对应的java类

anon

org.apache.shiro.web.filter.authc.AnonymousFilter

authc

org.apache.shiro.web.filter.authc.FormAuthenticationFilter

authcBasic

org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter

perms

org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter

port

org.apache.shiro.web.filter.authz.PortFilter

rest

org.apache.shiro.web.filter.authz.HttpMethodPermissionFilter

roles

org.apache.shiro.web.filter.authz.RolesAuthorizationFilter

ssl

org.apache.shiro.web.filter.authz.SslFilter

user

org.apache.shiro.web.filter.authc.UserFilter

logout

org.apache.shiro.web.filter.authc.LogoutFilter

anon:例子/admins/**=anon 没有参数,表示可以匿名使用。

authc:例如/admins/user/**=authc表示需要认证(登录)才能使用,没有参数

roles:例子/admins/user/=roles[admin],参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,当有多个参数时,例如admins/user/=roles["admin,guest"],每个参数通过才算通过,相当于hasAllRoles()方法。

perms:例子/admins/user/=perms[user:add:*],参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,例如/admins/user/=perms["user:add:,user:modify:"],当有多个参数时必须每个参数都通过才通过,想当于isPermitedAll()方法。

rest:例子/admins/user/=rest[user],根据请求的方法,相当于/admins/user/=perms[user:method] ,其中method为post,get,delete等。

port:例子/admins/user/**=port[8081],当请求的url的端口不是8081是跳转到schemal://serverName:8081?queryString,其中schmal是协议http或https等,serverName是你访问的host,8081是url配置里port的端口,queryString

是你访问的url里的?后面的参数。

authcBasic:例如/admins/user/**=authcBasic没有参数表示httpBasic认证

ssl:例子/admins/user/**=ssl没有参数,表示安全的url请求,协议为https

user:例如/admins/user/**=user没有参数表示必须存在用户,当登入操作时不做检查

注:anon,authcBasic,auchc,user是认证过滤器,

perms,roles,ssl,rest,port是授权过滤器
3.在applicationContext.xml中添加securityManagerper配置

[html] view plain copy
在CODE上查看代码片派生到我的代码片





[html] view plain copy
在CODE上查看代码片派生到我的代码片

4.配置jdbcRealm

[html] view plain copy
在CODE上查看代码片派生到我的代码片









dataSource数据源,配置不说了。

authenticationQuery登录认证用户的查询SQL,需要用登录用户名作为条件,查询密码字段。

userRolesQuery用户角色查询SQL,需要通过登录用户名去查询。查询角色字段

permissionsQuery用户的权限资源查询SQL,需要用单一角色查询角色下的权限资源,如果存在多个角色,则是遍历每个角色,分别查询出权限资源并添加到集合中。

permissionsLookupEnabled默认false。False时不会使用permissionsQuery的SQL去查询权限资源。设置为true才会去执行。

saltStyle密码是否加盐,默认是NO_SALT不加盐。加盐有三种选择CRYPT,COLUMN,EXTERNAL。详细可以去看文档。这里按照不加盐处理。

credentialsMatcher密码匹配规则。下面简单介绍。
[html] view plain copy
在CODE上查看代码片派生到我的代码片





hashAlgorithmName必须的,没有默认值。可以有MD5或者SHA-1,如果对密码安全有更高要求可以用SHA-256或者更高。这里使用MD5

storedCredentialsHexEncoded默认是true,此时用的是密码加密用的是Hex编码;false时用Base64编码

hashIterations迭代次数,默认值是1。

登录JSP页面
[html] view plain copy
在CODE上查看代码片派生到我的代码片

[html] view plain copy
在CODE上查看代码片派生到我的代码片

用户名:

[html] view plain copy
在CODE上查看代码片派生到我的代码片

密码:

[html] view plain copy
在CODE上查看代码片派生到我的代码片

记住我

注:登录JSP,表单action与提交方式固定,用户名与密码的name也是固定。
5.配置shiro注解模式

[html] view plain copy
在CODE上查看代码片派生到我的代码片





注意:在与springMVC整合时必须放在springMVC的配置文件中。

Shiro在注解模式下,登录失败,与没有权限均是通过抛出异常。并且默认并没有去处理或者捕获这些异常。在springMVC下需要配置捕获相应异常来通知用户信息,如果不配置异常会抛出到页面
[html] view plain copy
在CODE上查看代码片派生到我的代码片





/unauthorized


/unauthenticated



@RequiresAuthentication

验证用户是否登录,等同于方法subject.isAuthenticated() 结果为true时。

@RequiresUser

验证用户是否被记忆,user有两种含义:

一种是成功登录的(subject.isAuthenticated() 结果为true);

另外一种是被记忆的(subject.isRemembered()结果为true)。

@RequiresGuest

验证是否是一个guest的请求,与@RequiresUser完全相反。

换言之,RequiresUser == !RequiresGuest。

此时subject.getPrincipal() 结果为null.

@RequiresRoles

例如:@RequiresRoles("aRoleName");

void someMethod();

如果subject中有aRoleName角色才可以访问方法someMethod。如果没有这个权限则会抛出异常AuthorizationException。

@RequiresPermissions

例如: @RequiresPermissions({"file:read", "write:aFile.txt"} )
void someMethod();

要求subject中必须同时含有file:read和write:aFile.txt的权限才能执行方法someMethod()。否则抛出异常AuthorizationException。

三.简单扩展
1.自定义realm:
[html] view plain copy
在CODE上查看代码片派生到我的代码片


[html] view plain copy
在CODE上查看代码片派生到我的代码片

//这是授权方法
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String userName = (String) getAvailablePrincipal(principals);
//TODO 通过用户名获得用户的所有资源,并把资源存入info中
…………………….
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.setStringPermissions(set集合);
info.setRoles(set集合);
info.setObjectPermissions(set集合);
return info;
}

[html] view plain copy
在CODE上查看代码片派生到我的代码片

//这是认证方法
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//token中储存着输入的用户名和密码
UsernamePasswordToken upToken = (UsernamePasswordToken)token;
//获得用户名与密码
String username = upToken.getUsername();
String password = String.valueOf(upToken.getPassword());
//TODO 与数据库中用户名和密码进行比对。比对成功则返回info,比对失败则抛出对应信息的异常AuthenticationException
…………………..
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, password .toCharArray(),getName());
return info;
}

2.自定义登录

[html] view plain copy
在CODE上查看代码片派生到我的代码片

//创建用户名和密码的令牌
UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(),user.getPassWord());
//记录该令牌,如果不记录则类似购物车功能不能使用。
token.setRememberMe(true);
//subject理解成权限对象。类似user
Subject subject = SecurityUtils.getSubject();
try {
subject.login(token);
} catch (UnknownAccountException ex) {//用户名没有找到。
} catch (IncorrectCredentialsException ex) {//用户名密码不匹配。
}catch (AuthenticationException e) {//其他的登录错误
}
//验证是否成功登录的方法
if (subject.isAuthenticated()) {
}

3.自定义登出

[html] view plain copy
在CODE上查看代码片派生到我的代码片

Subject subject = SecurityUtils.getSubject();
subject.logout();

4.基于编码的角色授权实现

[html] view plain copy
在CODE上查看代码片派生到我的代码片

Subject currentUser = SecurityUtils.getSubject();
if (currentUser.hasRole("administrator")) {
//拥有角色administrator
} else {
//没有角色处理
}

断言方式控制
[html] view plain copy
在CODE上查看代码片派生到我的代码片

Subject currentUser = SecurityUtils.getSubject();
//如果没有角色admin,则会抛出异常,someMethod()也不会被执行
currentUser.checkRole(“admin");
someMethod();

5.基于编码的资源授权实现
[html] view plain copy
在CODE上查看代码片派生到我的代码片

Subject currentUser = SecurityUtils.getSubject();
if (currentUser.isPermitted("permssion:look")) {
//有资源权限
} else {
//没有权限
}

断言方式控制
[html] view plain copy
在CODE上查看代码片派生到我的代码片

Subject currentUser = SecurityUtils.getSubject();
//如果没有资源权限则会抛出异常。
currentUser.checkPermission("permssion:look");
someMethod();

6.在JSP上的TAG实现

标签名称

标签条件(均是显示标签内容)

shiro:authenticated

登录之后

shiro:notAuthenticated

不在登录状态时

shiro:guest

用户在没有RememberMe时

shiro:user

用户在RememberMe时

<shiro:hasAnyRoles name="abc,123" >

在有abc或者123角色时

<shiro:hasRole name="abc">

拥有角色abc

<shiro:lacksRole name="abc">

没有角色abc

<shiro:hasPermission name="abc">

拥有权限资源abc

<shiro:lacksPermission name="abc">

没有abc权限资源

shiro:principal

默认显示用户名称

默认,添加或删除用户的角色 或资源 ,系统不需要重启,但是需要用户重新登录。

即用户的授权是首次登录后第一次访问需要权限页面时进行加载。

但是需要进行控制的权限资源,是在启动时就进行加载,如果要新增一个权限资源需要重启系统。

Springsecurity 与apache shiro差别:
a)shiro配置更加容易理解,容易上手;security配置相对比较难懂。
b)在spring的环境下,security整合性更好。Shiro对很多其他的框架兼容性更好,号称是无缝集成。
c)shiro不仅仅可以使用在web中,它可以工作在任何应用环境中。
d)在集群会话时Shiro最重要的一个好处或许就是它的会话是独立于容器的。
e)Shiro提供的密码加密使用起来非常方便。

控制精度:

注解方式控制权限只能是在方法上控制,无法控制类级别访问。

过滤器方式控制是根据访问的URL进行控制。允许使用*匹配URL,所以可以进行粗粒度,也可以进行细粒度控制。

posted @ 2016-08-09 18:02  我不会游泳  阅读(336)  评论(0)    收藏  举报