Shiro学习笔记

spring zhichi
http://shiro.apache.org/spring.html

1
步骤 解压缩 unzip shiro-root-1.4.1-source-release.zip 进入目录 cd shiro-root-1.4.1/samples/quickstar 运行 mvn compile exec:java 概念 subject/session,然后判断user是否登录,没有则用subject(user)来使用 token登录, subject 是用户,但不这么叫,安全领域都这么做,session的好处是 不需要web Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); session.setAttribute( "someKey", "aValue" ); if ( !currentUser.isAuthenticated() ) { //collect user principals and credentials in a gui specific manner //such as username/password html form, X509 certificate, OpenID, etc. //We'll use the username/password example here since it is the most common. //(do you know what movie this is from? ;) UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa"); //this is all you have to do to support 'remember me' (no config - built in!): token.setRememberMe(true); currentUser.login(token); } 如果失败的话会有四种 错误 try { currentUser.login( token ); //if no exception, that's it, we're done! } catch ( UnknownAccountException uae ) { //username wasn't in the system, show them an error message? } catch ( IncorrectCredentialsException ice ) { //password didn't match, try again? } catch ( LockedAccountException lae ) { //account for that username is locked - can't login. Show them a message? } ... more types exceptions to check if you want ... } catch ( AuthenticationException ae ) { //unexpected condition - error? } 获取 principal就是用户名,判断角色和权限 log.info( "User [" + currentUser.getPrincipal() + "] logged in successfully." ); if ( currentUser.hasRole( "schwartz" ) ) { log.info("May the Schwartz be with you!" ); } else { log.info( "Hello, mere mortal." ); } 检测访问特定类型的示例 if ( currentUser.isPermitted( "lightsaber:weild" ) ) { log.info("You may use a lightsaber ring. Use it wisely."); } else { log.info("Sorry, lightsaber rings are for schwartz masters only."); } 用户的退出 currentUser.logout(); 2 具体的流程 1) 认证,remberme就是记住了用户标示,有两个概念 主体和 凭证,主体Principals 是用户名,凭证是秘钥Credentials UsernamePasswordToken token = new UsernamePasswordToken(username, password); //"Remember Me" built-in: token.setRememberMe(true); 2)登录 3)处理异常,和上面代码一样,处理异常确保有人是否是黑客输入了错误密码 4) 记住我和认证过是互斥的,记住我只记住了名字,认证是登录后的认证 记住我不适合做敏感操作,比如买书会推荐给你,但 交易会让强制登录 ,退出后建议重定向新页面为了清理cookie,因为也要清理rememberme 认证流程就是上四个,涉及到了realm 授权的流程: 分为单个realm和多个,单个直接,多个会有策略,如必须全部,第三个第一个必须成功,其他无所谓,任何一个等等 配置文件例子 [main] ... authenticator = com.foo.bar.CustomAuthenticator securityManager.authenticator = $authenticator AtLeastOneSuccessfulStrategy FirstSuccessfulStrategy AllSuccessfulStrategy 策略配置: [main] ... authcStrategy = org.apache.shiro.authc.pam.FirstSuccessfulStrategy securityManager.authenticator.authenticationStrategy = $authcStrategy 还有认证的顺序排序: http://shiro.apache.org/authentication.html 3 ) 授权 http://shiro.apache.org/authorization.html#Authorization-ObjectbasedPermissionChecks 各种的 check / is / role /permission/ string /object 检查的,权限的,字符串的,对象的,全部的,单个的等等的组合 4)各种注解版 @RequiresPermissions("account:create") @RequiresRoles("administrator")

 

4 jsp web的标签

添加 标签 的方法
配置个人拦截器
<listener>
<listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
</listener>

<filter>
<filter-name>ShiroFilter</filter-name>
<filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>ShiroFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
<dispatcher>ERROR</dispatcher>
</filter-mapping>
[main]

shiro.loginUrl = /login.jsp

# Stuff we've configured here previously is omitted for brevity

[urls]
/login.jsp = authc
/logout = logout

<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

添加user和guest的方法
<shiro:user><a href="<c:url value="/logout"/>">Log out</a></shiro:user>
<shiro:guest><a href="<c:url value="/login.jsp"/>">Log in</a></shiro:guest>

配置 shiro.ini
/account/** = authc


认证过的没认证过的
<shiro:authenticated><p>Visit your <a href="<c:url value="/account"/>">account page</a>.</p></shiro:authenticated>
<shiro:notAuthenticated>
<p>If you want to access the authenticated-only <a href="<c:url value="/account"/>">account page</a>, you will need to log-in first.</p>
</shiro:notAuthenticated>


关于role权限的:
<p>
<shiro:hasRole name="Captains">Captains<br/></shiro:hasRole>
<shiro:hasRole name="Officers">Bad Guys<br/></shiro:hasRole>
<shiro:hasRole name="Enlisted">Enlisted<br/></shiro:hasRole>
</p>

<h3>Roles you DON'T have:</h3>

<p>
<shiro:lacksRole name="Captains">Captains<br/></shiro:lacksRole>
<shiro:lacksRole name="Officers">Officers<br/></shiro:lacksRole>
<shiro:lacksRole name="Enlisted">Enlisted<br/></shiro:lacksRole>
</p>

<shiro:hasPermission>
<shiro:lacksPermission name="user:${account.username}:edit">

====================J>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

currentUser.logout(); //removes all identifying information and invalidates their session too.

if ( currentUser.isPermitted( "winnebago:drive:eagle5" ) ) {
log.info("You are permitted to 'drive' the 'winnebago' with license plate (id) 'eagle5'. " +
"Here are the keys - have fun!");
} else {
log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
}


if ( currentUser.hasRole( "schwartz" ) ) {
log.info("May the Schwartz be with you!" );
} else {
log.info( "Hello, mere mortal." );
}


if ( !currentUser.isAuthenticated() ) {
//collect user principals and credentials in a gui specific manner
//such as username/password html form, X509 certificate, OpenID, etc.
//We'll use the username/password example here since it is the most common.
//(do you know what movie this is from? ;)
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
//this is all you have to do to support 'remember me' (no config - built in!):
token.setRememberMe(true);
currentUser.login(token);
}


try {
currentUser.login( token );
//if no exception, that's it, we're done!
} catch ( UnknownAccountException uae ) {
//username wasn't in the system, show them an error message?
} catch ( IncorrectCredentialsException ice ) {
//password didn't match, try again?
} catch ( LockedAccountException lae ) {
//account for that username is locked - can't login. Show them a message?
}
... more types exceptions to check if you want ...
} catch ( AuthenticationException ae ) {
//unexpected condition - error?
}


Session session = currentUser.getSession();
session.setAttribute( "someKey", "aValue" );


Subject currentUser = SecurityUtils.getSubject();

=====================>>>>>>>>>>>>>>>>
安全 ,提供了 toHex() and toBase64() methods.
16进制,和 base64加密的学习

import junit.framework.Assert;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.codec.Hex;
import org.junit.Test;

public class Shiro_1 {
@Test
public void test(){
String str1 = "hello";
//base64进行编码
String base64Encoded = Base64.encodeToString(str1.getBytes());
//base64进行解码
String str2 = Base64.decodeToString(base64Encoded);
//16进制编码
String hexEncoded = Hex.encodeToString(str1.getBytes());
//16进制解码
String str3 = new String(Hex.decode(hexEncoded.getBytes()));
Assert.assertEquals(str1,str2);
Assert.assertEquals(str1, str3);
}

===============================================================>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

ehcache


----------------------->>>>>>>>>>>>>>>>>>>>>>>>>>

授权问题:
blahRealm = com.company.blah.Realm
...
fooRealm = com.company.foo.Realm
...
barRealm = com.company.another.Realm

securityManager.realms = $fooRealm, $barRealm, $blahRealm
...


又顺序
可以设置realm的错略

authcStrategy = org.apache.shiro.authc.pam.FirstSuccessfulStrategy

securityManager.authenticator.authenticationStrategy = $authcStrategy

================》》》》》》》》》》
web


$ mvn jetty:run

<shiro:lacksPermission name="user:${account.username}:edit"> ...

cacheManager = org.apache.shiro.cache.MemoryConstrainedCacheManager
securityManager.cacheManager = $cacheManager

开始添加拦截器:
<listener>
<listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
</listener>

<filter>
<filter-name>ShiroFilter</filter-name>
<filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>ShiroFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
<dispatcher>ERROR</dispatcher>
</filter-mapping>


[main]

shiro.loginUrl = /login.jsp

# Stuff we've configured here previously is omitted for brevity

[urls]
/login.jsp = authc
/logout = logout


<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


/account/** = authc


<p>
<shiro:hasRole name="Captains">Captains<br/></shiro:hasRole>
<shiro:hasRole name="Officers">Bad Guys<br/></shiro:hasRole>
<shiro:hasRole name="Enlisted">Enlisted<br/></shiro:hasRole>
</p>

<h3>Roles you DON'T have:</h3>

<p>
<shiro:lacksRole name="Captains">Captains<br/></shiro:lacksRole>
<shiro:lacksRole name="Officers">Officers<br/></shiro:lacksRole>
<shiro:lacksRole name="Enlisted">Enlisted<br/></shiro:lacksRole>
</p>

<ul>
<li>You may <shiro:lacksPermission name="ship:NCC-1701-D:command"><b>NOT</b> </shiro:lacksPermission> command the <code>NCC-1701-D</code> Starship!</li>
<li>You may <shiro:lacksPermission name="user:${account.username}:edit"><b>NOT</b> </shiro:lacksPermission> edit the ${account.username} user!</li>
</ul>

/index.html = anon
/user/create = anon
/user/** = authc
/admin/** = authc, roles[administrator]
/rest/** = authc, rest
/remoting/rpc/** = authc, perms["remote:invoke"]


Filter Name Class
anon org.apache.shiro.web.filter.authc.AnonymousFilter
authc org.apache.shiro.web.filter.authc.FormAuthenticationFilter
authcBasic org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter
logout org.apache.shiro.web.filter.authc.LogoutFilter
noSessionCreation org.apache.shiro.web.filter.session.NoSessionCreationFilter
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

[main]
...
rememberMeManager = com.my.impl.RememberMeManager
securityManager.rememberMeManager = $rememberMeManager


securityManager.rememberMeManager.cookie.name = foo
securityManager.rememberMeManager.cookie.maxAge = blah
...

UsernamePasswordToken token = new UsernamePasswordToken(username, password);

token.setRememberMe(true);

SecurityUtils.getSubject().login(token);


[main]
...
# configure Shiro's default 'ssl' filter to be disabled while testing:
ssl.enabled = false

[urls]
...
/some/path = ssl, authc
/another/path = ssl, roles[admin]

原文地址:https://www.cnblogs.com/genestart/p/11364420.html