赞
踩
- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <groupId>com.bobo</groupId>
- <artifactId>ShiroDemo01</artifactId>
- <version>1.0-SNAPSHOT</version>
-
- <dependencies>
- <dependency>
- <groupId>org.apache.shiro</groupId>
- <artifactId>shiro-core</artifactId>
- <version>1.1.0</version>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-simple</artifactId>
- <version>1.6.1</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.12</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>commons-logging</groupId>
- <artifactId>commons-logging</artifactId>
- <version>1.2</version>
- </dependency>
-
- </dependencies>
-
- </project>
- [users]
- root=123456
- # 账号是root,密码是123456
- package com.bobo.shiro.test;
-
- import org.apache.shiro.SecurityUtils;
- import org.apache.shiro.authc.AuthenticationToken;
- import org.apache.shiro.authc.UsernamePasswordToken;
- import org.apache.shiro.config.IniSecurityManagerFactory;
- import org.apache.shiro.mgt.SecurityManager;
- import org.apache.shiro.subject.Subject;
- import org.apache.shiro.util.Factory;
-
- public class Test01 {
-
- /**
- * Shiro的入门案例
- * 账号密码是定义在ini文件中的
- * @param args
- */
- public static void main(String[] args) {
- // 1.获取一个SecurityManager工厂对象
- Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
- // 2.通过SecurityManager工厂对象创建SecurityManager对象
- SecurityManager securityManager = factory.getInstance();
- // 3.将SecurityManager对象添加到当前的运行环境中去
- SecurityUtils.setSecurityManager(securityManager);
- // 4.获取Subject对象
- Subject subject = SecurityUtils.getSubject();
- // 5.获取用户提交的要认证的账号密码
- String userName = "root";
- String password = "1234561";
- // 6.将用户提交的账号密码封装为一个Token对象
- AuthenticationToken token = new UsernamePasswordToken(userName,password);
- // 7.完成认证操作 login
- subject.login(token);
- // 8.获取认证状态
- System.out.println(subject.isAuthenticated());
- }
- }
- package com.bobo.shiro.test;
-
- import org.apache.shiro.SecurityUtils;
- import org.apache.shiro.authc.AuthenticationToken;
- import org.apache.shiro.authc.IncorrectCredentialsException;
- import org.apache.shiro.authc.UnknownAccountException;
- import org.apache.shiro.authc.UsernamePasswordToken;
- import org.apache.shiro.config.IniSecurityManagerFactory;
- import org.apache.shiro.mgt.SecurityManager;
- import org.apache.shiro.subject.Subject;
- import org.apache.shiro.util.Factory;
-
- public class Test02 {
-
- /**
- * Shiro的入门案例
- * 账号密码是定义在ini文件中的
- * @param args
- */
- public static void main(String[] args) {
- // 1.获取一个SecurityManager工厂对象
- Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
- // 2.通过SecurityManager工厂对象创建SecurityManager对象
- SecurityManager securityManager = factory.getInstance();
- // 3.将SecurityManager对象添加到当前的运行环境中去
- SecurityUtils.setSecurityManager(securityManager);
- // 4.获取Subject对象
- Subject subject = SecurityUtils.getSubject();
- // 5.获取用户提交的要认证的账号密码
- String userName = "root1";
- String password = "123456";
- // 6.将用户提交的账号密码封装为一个Token对象
- AuthenticationToken token = new UsernamePasswordToken(userName,password);
- // 7.完成认证操作 login
- try{
- subject.login(token);
- System.out.println("登录成功....");
- }catch (UnknownAccountException e){
- System.out.println("账号错误...");
- }catch (IncorrectCredentialsException e){
- System.out.println("密码错误...");
- }
-
-
- }
- }
- package com.bobo.shiro.realm;
-
- import org.apache.shiro.authc.*;
- import org.apache.shiro.authz.AuthorizationInfo;
- import org.apache.shiro.realm.AuthorizingRealm;
- import org.apache.shiro.subject.PrincipalCollection;
-
- /**
- * 自定义的Realm
- */
- public class MyRealm extends AuthorizingRealm {
-
-
- /**
- * 认证操作
- * @param authenticationToken
- * @return
- * @throws AuthenticationException
- */
- @Override
- protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
- throws AuthenticationException {
- UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
- String userName = token.getUsername();
- String password = new String(token.getPassword());
- System.out.println("登录的账号密码是:" + userName + " " + password);
- // 通过JDBC操作和数据库中的账号密码匹配
- if("zhang".equals(userName) ){
- // 账号正确 假设查询出的zhang的密码是 123
- AuthenticationInfo info =
- new SimpleAuthenticationInfo(userName,"123","myrealm");
- return info;
- }
- return null;
- }
-
- /**
- * 授权操作
- * @param principalCollection
- * @return
- */
- @Override
- protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
- return null;
- }
- }
- [main]
- # 自定义Realm
- customeRealm=com.bobo.shiro.realm.MyRealm
- # 将自定义的Realm设置到SecurityManager中
- securityManager.realms=$customeRealm
- package com.bobo.shiro.test;
-
- import org.apache.shiro.SecurityUtils;
- import org.apache.shiro.authc.AuthenticationToken;
- import org.apache.shiro.authc.IncorrectCredentialsException;
- import org.apache.shiro.authc.UnknownAccountException;
- import org.apache.shiro.authc.UsernamePasswordToken;
- import org.apache.shiro.config.IniSecurityManagerFactory;
- import org.apache.shiro.mgt.SecurityManager;
- import org.apache.shiro.subject.Subject;
- import org.apache.shiro.util.Factory;
-
- public class Test02 {
-
- /**
- * Shiro的入门案例
- * 账号密码是定义在ini文件中的
- * @param args
- */
- public static void main(String[] args) {
- // 1.获取一个SecurityManager工厂对象
- Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
- // 2.通过SecurityManager工厂对象创建SecurityManager对象
- SecurityManager securityManager = factory.getInstance();
- // 3.将SecurityManager对象添加到当前的运行环境中去
- SecurityUtils.setSecurityManager(securityManager);
- // 4.获取Subject对象
- Subject subject = SecurityUtils.getSubject();
- // 5.获取用户提交的要认证的账号密码
- String userName = "zhang";
- String password = "123";
- // 6.将用户提交的账号密码封装为一个Token对象
- AuthenticationToken token = new UsernamePasswordToken(userName,password);
- // 7.完成认证操作 login
- try{
- subject.login(token);
- System.out.println("登录成功....");
- }catch (UnknownAccountException e){
- System.out.println("账号错误...");
- }catch (IncorrectCredentialsException e){
- System.out.println("密码错误...");
- }
-
-
- }
- }
- public void login(AuthenticationToken token) throws AuthenticationException {
- this.clearRunAsIdentities();
- // 进入securityManager的login方法中
- Subject subject = this.securityManager.login(this, token);
- // 认证完成后的操作....
- String host = null;
- PrincipalCollection principals;
- if (subject instanceof DelegatingSubject) {
- DelegatingSubject delegating = (DelegatingSubject)subject;
- principals = delegating.principals;
- host = delegating.host;
- } else {
- principals = subject.getPrincipals();
- }
- if (principals != null && !principals.isEmpty()) {
- this.principals = principals;
- this.authenticated = true;
- if (token instanceof HostAuthenticationToken) {
- host = ((HostAuthenticationToken)token).getHost();
- }
- if (host != null) {
- this.host = host;
- }
- Session session = subject.getSession(false);
- if (session != null) {
- this.session = this.decorate(session);
- this.runAsPrincipals = this.getRunAsPrincipals(this.session);
- } else {
- this.session = null;
- }
- ThreadContext.bind(this);
- } else {
- String msg = "Principals returned from securityManager.login( token ) returned a null or empty value. This value must be non null and populated with one or more elements.";
- throw new IllegalStateException(msg);
- }
- }
- public Subject login(Subject subject, AuthenticationToken token) throws AuthenticationException {
- AuthenticationInfo info;
- try {
- // 关键方法 认证方法
- info = this.authenticate(token);
- } catch (AuthenticationException var7) {
- AuthenticationException ae = var7;
- try {
- this.onFailedLogin(token, ae, subject);
- } catch (Exception var6) {
- if (log.isInfoEnabled()) {
- log.info("onFailedLogin method threw an exception. Logging and propagating original AuthenticationException.", var6);
- }
- }
- throw var7;
- }
- Subject loggedIn = this.createSubject(token, info, subject);
- this.bind(loggedIn);
- this.onSuccessfulLogin(token, info, loggedIn);
- return loggedIn;
- }
- public final AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {
- if (token == null) {
- throw new IllegalArgumentException("Method argumet (authentication token) cannot be null.");
- } else {
- log.trace("Authentication attempt received for token [{}]", token);
- AuthenticationInfo info;
- try {
- // 关键代码 完成认证
- info = this.doAuthenticate(token);
- if (info == null) {
- String msg = "No account information found for authentication token [" + token + "] by this " + "Authenticator instance.Please check that it is configured correctly.";
- throw new AuthenticationException(msg);
- }
- } catch (Throwable var8) {
- AuthenticationException ae = null;
- if (var8 instanceof AuthenticationException) {
- ae = (AuthenticationException)var8;
- }
- if (ae == null) {
- String msg = "Authentication failed for token submission [" + token + "]. Possible unexpected " + "error? (Typical or expected login exceptions should extend from AuthenticationException).";
- ae = new AuthenticationException(msg, var8);
- }
- try {
- this.notifyFailure(token, ae);
- } catch (Throwable var7) {
- if (log.isWarnEnabled()) {
- String msg = "Unable to send notification for failed authentication attempt - listener error?. Please check your AuthenticationListener implementation(s). Logging sending exception and propagating original AuthenticationException instead...";
- log.warn(msg, var7);
- }
- }
- throw ae;
- }
- log.debug("Authentication successful for token [{}]. Returned account [{}]", token, info);
- this.notifySuccess(token, info);
- return info;
- }
- }
- protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
- this.assertRealmsConfigured();
- // 获取到自定义的realm
- Collection<Realm> realms = this.getRealms();
- // 判断是否进入单域还是多域验证
- return realms.size() == 1 ?
- this.doSingleRealmAuthentication((Realm)realms.iterator().next(),authenticationToken) : this.doMultiRealmAuthentication(realms,authenticationToken);
- }
- protected AuthenticationInfo doSingleRealmAuthentication(Realm realm,AuthenticationToken token) {
- if (!realm.supports(token)) {
- String msg = "Realm [" + realm + "] does not support authentication token [" + token + "]. Please ensure that the appropriate Realm implementation is " + "configured correctly or that the realm accepts AuthenticationTokens of this type.";
- throw new UnsupportedTokenException(msg);
- } else {
- // 具体的验证操作
- AuthenticationInfo info = realm.getAuthenticationInfo(token);
- if (info == null) {
- String msg = "Realm [" + realm + "] was unable to find account data for the " + "submitted AuthenticationToken [" + token + "].";
- // 这是我们熟悉的异常,账号错误的异常信息
- throw new UnknownAccountException(msg);
- } else {
- return info;
- }
- }
- }
- public final AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
- // 其实就是会执行我们自定义的MyRealm中的认证方法
- AuthenticationInfo info = this.doGetAuthenticationInfo(token);
- if (info == null) {
- if (log.isDebugEnabled()) {
- String msg = "No authentication information found for submitted authentication token [" + token + "]. " + "Returning null.";
- log.debug(msg);
- }
- return null;
- } else {
- CredentialsMatcher cm = this.getCredentialsMatcher();
- if (cm != null) {
- // 密码匹配
- if (!cm.doCredentialsMatch(token, info)) {
- String msg = "The credentials provided for account [" + token + "] did not match the expected credentials.";
- // 密码错误 抛出的异常信息
- throw new IncorrectCredentialsException(msg);
- } else {
- return info;
- }
- } else {
- throw new AuthenticationException("A CredentialsMatcher must be configured in order to verify credentials during authentication. If you do not wish for credentials to be examined, you can configure an " + AllowAllCredentialsMatcher.class.getName() + " instance.");
- }
- }
- }
- package com.bobo.shiro.md5;
-
- import org.apache.shiro.crypto.hash.Md5Hash;
-
- public class Md5Demo01 {
-
- /**
- * MD5算法的使用
- * @param args
- */
- public static void main(String[] args) {
- // 单个信息加密
- Md5Hash md5Hash = new Md5Hash("123456");
- System.out.println(md5Hash);
- // 加密添加盐值 增大破解难度
- md5Hash = new Md5Hash("123456","123");
- System.out.println(md5Hash);
- // 加密添加盐值 及增加迭代次数
- md5Hash = new Md5Hash("123456","123",1024);
- System.out.println(md5Hash);
- }
- }
- e10adc3949ba59abbe56e057f20f883e
- 1e191d851b3b49a248f4ea62f6b06410
- b2793335f43645fd8e00c7d18e14e05f
- package com.bobo.shiro.realm;
-
- import org.apache.shiro.authc.*;
- import org.apache.shiro.authz.AuthorizationInfo;
- import org.apache.shiro.realm.AuthorizingRealm;
- import org.apache.shiro.subject.PrincipalCollection;
- import org.apache.shiro.util.SimpleByteSource;
-
- /**
- * 自定义的Realm
- */
- public class MyRealm extends AuthorizingRealm {
-
-
- /**
- * 认证操作
- * @param authenticationToken
- * @return
- * @throws AuthenticationException
- */
- @Override
- protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
- throws AuthenticationException {
- UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
- String userName = token.getUsername();
- String password = new String(token.getPassword());
- System.out.println("登录的账号密码是:" + userName + " " + password);
- // 通过JDBC操作和数据库中的账号密码匹配
- if("zhang".equals(userName) ){
- // 账号正确 假设查询出的zhang的密码是 123
- String pwd = "b2793335f43645fd8e00c7d18e14e05f";
- String salt = "123";
- AuthenticationInfo info =
- new SimpleAuthenticationInfo(userName
- ,pwd
- ,new SimpleByteSource(salt) // salt
- ,"myrealm" // 自定义的 this 名称
- );
- return info;
- }
- return null;
- }
-
- /**
- * 授权操作
- * @param principalCollection
- * @return
- */
- @Override
- protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
- return null;
- }
- }
- [main]
- # 定义凭证匹配器
- credentialsMathcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher
- # 散列的算法
- credentialsMathcher.hashAlgorithmName=md5
- # 散列迭代的次数
- credentialsMathcher.hashIterations=1024
- # 自定义Realm
- customeRealm=com.bobo.shiro.realm.MyRealm
- customeRealm.credentialsMatcher=$credentialsMathcher
- # 将自定义的Realm设置到SecurityManager中
- securityManager.realms=$customeRealm
- Subject subject = SecurityUtils.getSubject();
- if(subject.hasRole(“admin”)) {
- //有权限
- } else {
- //无权限
- }
- 123456
- @RequiresRoles("admin")
- public void hello() {
- //有权限
- }
- 1234
- <shiro:hasRole name="admin">
- <!— 有权限—>
- </shiro:hasRole>
- 123
- [users]
- root=123456,role1,role2
- # 账号是root,密码是123456 具有的角色是 role1,role2
-
- [roles]
- # 角色role1具有的权限
- role1=user:create,user:update
- role2=user:query,user:create
- role3=user:delete,user:query
- package com.bobo.shiro.test;
-
- import org.apache.shiro.SecurityUtils;
- import org.apache.shiro.authc.AuthenticationToken;
- import org.apache.shiro.authc.IncorrectCredentialsException;
- import org.apache.shiro.authc.UnknownAccountException;
- import org.apache.shiro.authc.UsernamePasswordToken;
- import org.apache.shiro.config.IniSecurityManagerFactory;
- import org.apache.shiro.mgt.SecurityManager;
- import org.apache.shiro.subject.Subject;
- import org.apache.shiro.util.Factory;
-
- import java.util.Arrays;
-
- public class Test02 {
-
- /**
- * Shiro的入门案例
- * 账号密码是定义在ini文件中的
- * @param args
- */
- public static void main(String[] args) {
- // 1.获取一个SecurityManager工厂对象
- Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
- // 2.通过SecurityManager工厂对象创建SecurityManager对象
- SecurityManager securityManager = factory.getInstance();
- // 3.将SecurityManager对象添加到当前的运行环境中去
- SecurityUtils.setSecurityManager(securityManager);
- // 4.获取Subject对象
- Subject subject = SecurityUtils.getSubject();
- // 5.获取用户提交的要认证的账号密码
- String userName = "root";
- String password = "123456";
- // 6.将用户提交的账号密码封装为一个Token对象
- AuthenticationToken token = new UsernamePasswordToken(userName,password);
- // 7.完成认证操作 login
- try{
- subject.login(token);
- System.out.println("登录成功....");
- // 做角色的验证操作
- System.out.println("认证状态:"+subject.isAuthenticated());
- System.out.println("是否具有role1角色:"+subject.hasRole("role1"));
- System.out.println("是否具有role3角色:"+subject.hasRole("role3"));
- boolean[] types = subject.hasRoles(Arrays.asList("role1", "role2", "role3"));
- System.out.println(Arrays.toString(types));
- System.out.println(subject.getPrincipal()+"是否具有role1和role2两个角色:"
- + subject.hasAllRoles(Arrays.asList("role1","role2")));
- System.out.println(subject.getPrincipal()+"是否具有role1和role3两个角色:"
- + subject.hasAllRoles(Arrays.asList("role1","role3")));
- // check开头的方法校验不通过会抛出对应异常
- subject.checkRole("role1");
- // 做权限的验证
- System.out.println(subject.getPrincipal()+"是否具有user:create权限:"+
- subject.isPermitted("user:create"));
- System.out.println(subject.getPrincipal()+"是否具有user:delete权限:"+
- subject.isPermitted("user:delete"));
- // check开头的校验方法不通过同样抛出异常信息
- subject.checkPermission("user:delete");
-
- }catch (UnknownAccountException e){
- System.out.println("账号错误...");
- }catch (IncorrectCredentialsException e){
- System.out.println("密码错误...");
- }
-
-
- }
- }
- 登录成功....
- 认证状态:true
- 是否具有role1角色:true
- 是否具有role3角色:false
- [true, true, false]
- root是否具有role1和role2两个角色:true
- root是否具有role1和role3两个角色:false
- root是否具有user:create权限:true
- root是否具有user:delete权限:false
- Exception in thread "main" org.apache.shiro.authz.UnauthorizedException: Subject does not have permission [user:delete]
- at
- org.apache.shiro.authz.ModularRealmAuthorizer.checkPermission(ModularRealmAuthorizer.java:321)
- at
- org.apache.shiro.mgt.AuthorizingSecurityManager.checkPermission(AuthorizingSecurityManager.java:137)
- at
- org.apache.shiro.subject.support.DelegatingSubject.checkPermission(DelegatingSubject.java:198)
- at com.bobo.shiro.test.Test02.main(Test02.java:57)
- /**
- * 授权操作
- * 认证成功后会执行的授权方法
- * 要注意的是 doGetAuthorizationInfo方法的形参的实际数据是
- * 认证方法中返回的 SimpleAuthenticationInfo中的第一个参数
- * @param principalCollection
- * @return
- */
- @Override
- protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
- // 获取到当前登录的账号
- String userName = principalCollection.getPrimaryPrincipal().toString();
- System.out.println("当前登录的账号是:" + userName);
- // 根据登录的账号去数据库中查询对应的角色和权限信息
- SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
- info.addRole("role1");
- info.addRole("role2");
- info.addStringPermission("user:create");
- info.addStringPermission("user:update");
- return info;
- }
- [main]
- # 自定义Realm
- customeRealm=com.bobo.shiro.realm.MyRealm
- # 将自定义的Realm设置到SecurityManager中
- securityManager.realms=$customeRealm
- package com.bobo.shiro.test;
-
- import org.apache.shiro.SecurityUtils;
- import org.apache.shiro.authc.AuthenticationToken;
- import org.apache.shiro.authc.IncorrectCredentialsException;
- import org.apache.shiro.authc.UnknownAccountException;
- import org.apache.shiro.authc.UsernamePasswordToken;
- import org.apache.shiro.config.IniSecurityManagerFactory;
- import org.apache.shiro.mgt.SecurityManager;
- import org.apache.shiro.subject.Subject;
- import org.apache.shiro.util.Factory;
-
- import java.util.Arrays;
-
- public class Test02 {
-
- /**
- * Shiro的入门案例
- * 账号密码是定义在ini文件中的
- * @param args
- */
- public static void main(String[] args) {
- // 1.获取一个SecurityManager工厂对象
- Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
- // 2.通过SecurityManager工厂对象创建SecurityManager对象
- SecurityManager securityManager = factory.getInstance();
- // 3.将SecurityManager对象添加到当前的运行环境中去
- SecurityUtils.setSecurityManager(securityManager);
- // 4.获取Subject对象
- Subject subject = SecurityUtils.getSubject();
- // 5.获取用户提交的要认证的账号密码
- String userName = "zhang";
- String password = "123";
- // 6.将用户提交的账号密码封装为一个Token对象
- AuthenticationToken token = new UsernamePasswordToken(userName,password);
- // 7.完成认证操作 login
- try{
- subject.login(token);
- System.out.println("登录成功....");
- // 做角色的验证操作
- System.out.println("认证状态:"+subject.isAuthenticated());
- System.out.println("是否具有role1角色:"+subject.hasRole("role1"));
- System.out.println("是否具有role3角色:"+subject.hasRole("role3"));
- boolean[] types = subject.hasRoles(Arrays.asList("role1", "role2", "role3"));
- System.out.println(Arrays.toString(types));
- System.out.println(subject.getPrincipal()+"是否具有role1和role2两个角色:"
- + subject.hasAllRoles(Arrays.asList("role1","role2")));
- System.out.println(subject.getPrincipal()+"是否具有role1和role3两个角色:"
- + subject.hasAllRoles(Arrays.asList("role1","role3")));
- // check开头的方法校验不通过会抛出对应异常
- subject.checkRole("role1");
- // 做权限的验证
- System.out.println(subject.getPrincipal()+"是否具有user:create权限:"+
- subject.isPermitted("user:create"));
- System.out.println(subject.getPrincipal()+"是否具有user:delete权限:"+
- subject.isPermitted("user:delete"));
- // check开头的校验方法不通过同样抛出异常信息
- subject.checkPermission("user:delete");
- }catch (UnknownAccountException e){
- System.out.println("账号错误...");
- }catch (IncorrectCredentialsException e){
- System.out.println("密码错误...");
- }
-
-
- }
- }
- 登录的账号密码是:zhang 123
- 登录成功....
- 认证状态:true
- 当前登录的账号是:zhang
- 是否具有role1角色:true
- 当前登录的账号是:zhang
- 是否具有role3角色:false
- 当前登录的账号是:zhang
- 当前登录的账号是:zhang
- 当前登录的账号是:zhang
- [true, true, false]
- 当前登录的账号是:zhang
- 当前登录的账号是:zhang
- zhang是否具有role1和role2两个角色:true
- 当前登录的账号是:zhang
- 当前登录的账号是:zhang
- zhang是否具有role1和role3两个角色:false
- 当前登录的账号是:zhang
- 当前登录的账号是:zhang
- zhang是否具有user:create权限:true
- 当前登录的账号是:zhang
- zhang是否具有user:delete权限:false
- 当前登录的账号是:zhang
- Exception in thread "main" org.apache.shiro.authz.UnauthorizedException: Subject does not have permission [user:delete]
- at
- org.apache.shiro.authz.ModularRealmAuthorizer.checkPermission(ModularRealmAuthorizer.java:321)
- at
- org.apache.shiro.mgt.AuthorizingSecurityManager.checkPermission(AuthorizingSecurityManager.java:137)
- at
- org.apache.shiro.subject.support.DelegatingSubject.checkPermission(DelegatingSubject.java:198)
- at com.bobo.shiro.test.Test02.main(Test02.java:58)
- CREATE TABLE `t_user_new` (
- `id` int NOT NULL AUTO_INCREMENT,
- `username` varchar(30) NOT NULL,
- `password` varchar(100) DEFAULT NULL,
- `salt` varchar(100) DEFAULT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
- <!-- shiro相关的依赖 -->
- <dependency>
- <groupId>org.apache.shiro</groupId>
- <artifactId>shiro-spring</artifactId>
- <version>1.5.3</version>
- </dependency>
- <!DOCTYPE web-app PUBLIC
- "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
- "http://java.sun.com/dtd/web-app_2_3.dtd" >
-
- <web-app version="2.5"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <display-name>Archetype Created Web Application</display-name>
-
- <!-- 配置Spring -->
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:applicationContext-*.xml</param-value>
- </context-param>
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
-
- <!-- 配置Servlet的前端控制器 -->
- <servlet>
- <servlet-name>springmvc</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <!-- 关联自定义的Spring MVC的配置文件 -->
- <init-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:spring-mvc.xml</param-value>
- </init-param>
- </servlet>
-
- <servlet-mapping>
- <servlet-name>springmvc</servlet-name>
- <!-- 支持Restful风格编程 -->
- <url-pattern>/</url-pattern>
- </servlet-mapping>
- <!-- 配置字符编码的过滤器 -->
- <!-- 配置设置编码的过滤器 -->
- <filter>
- <filter-name>encodingFilter</filter-name>
- <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
- <init-param>
- <param-name>encoding</param-name>
- <param-value>UTF-8</param-value>
- </init-param>
- <init-param>
- <param-name>forceRequestEncoding</param-name>
- <param-value>true</param-value>
- </init-param>
- <init-param>
- <param-name>forceResponseEncoding</param-name>
- <param-value>true</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>encodingFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <!-- default 防止静态资源拦截 -->
- <servlet-mapping>
- <servlet-name>default</servlet-name>
- <url-pattern>*.html</url-pattern>
- </servlet-mapping>
- <servlet-mapping>
- <servlet-name>default</servlet-name>
- <url-pattern>*.css</url-pattern>
- </servlet-mapping>
- <servlet-mapping>
- <servlet-name>default</servlet-name>
- <url-pattern>*.js</url-pattern>
- </servlet-mapping>
- <servlet-mapping>
- <servlet-name>default</servlet-name>
- <url-pattern>*.jpg</url-pattern>
- </servlet-mapping>
- <servlet-mapping>
- <servlet-name>default</servlet-name>
- <url-pattern>*.png</url-pattern>
- </servlet-mapping>
- <!-- 注册一个Shiro的过滤器 -->
- <filter>
- <filter-name>shiroFilter</filter-name>
- <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
- <!-- 设置Filter的声明周期和Servlet容器绑定 -->
- <init-param>
- <param-name>targetFilterLifecycle</param-name>
- <param-value>true</param-value>
- </init-param>
- <!-- 设置Spring容器Filter的bean id -->
- <init-param>
- <param-name>targetBeanName</param-name>
- <param-value>shiro</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>shiroFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- </web-app>
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
-
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context.xsd">
-
- <!-- 定义凭证匹配器 -->
- <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher" id="credentialsMatcher">
- <!-- 配置加密算法 -->
- <property name="hashAlgorithmName" value="md5" />
- <!-- 配置迭代的次数-->
- <property name="hashIterations" value="1024" />
- </bean>
-
- <!-- 配置自定义Realm -->
- <bean class="com.bobo.realm.MyRealm" id="myRealm" >
- <!-- 配置Realm对应的凭证匹配器 -->
- <property name="credentialsMatcher" ref="credentialsMatcher" />
- </bean>
-
- <!-- 配置SecurityManager -->
- <bean class="org.apache.shiro.web.mgt.DefaultWebSecurityManager" id="securityManager" >
- <!-- 关联自定义Realm -->
- <property name="realm" ref="myRealm" />
- </bean>
-
- <!-- 注册一个ShiroFilterFactoryBean对象 注意id必须和web.xml文件中注册的targetBeanName要一致-->
- <bean class="org.apache.shiro.spring.web.ShiroFilterFactoryBean" id="shiro">
- <!-- 注册SecurityManager对象 -->
- <property name="securityManager" ref="securityManager" />
- <!-- 注册登录地址 -->
- <property name="loginUrl" value="/login.do" />
- <!-- 登录成功的跳转地址 -->
- <property name="successUrl" value="/success.jsp" />
- <!-- 设置过滤器链 -->
- <property name="filterChainDefinitions">
- <value>
- /login.do=authc
- /**=anon
- </value>
- </property>
- </bean>
- </beans>
- package com.bobo.realm;
-
- import com.bobo.pojo.User;
- import com.bobo.service.IUserService;
- import org.apache.shiro.authc.*;
- import org.apache.shiro.authz.AuthorizationInfo;
- import org.apache.shiro.authz.SimpleAuthorizationInfo;
- import org.apache.shiro.realm.AuthorizingRealm;
- import org.apache.shiro.subject.PrincipalCollection;
- import org.apache.shiro.util.SimpleByteSource;
- import org.springframework.beans.factory.annotation.Autowired;
-
- public class MyRealm extends AuthorizingRealm {
-
- @Autowired
- private IUserService userService;
-
-
- /***
- * 认证方法
- * @param authenticationToken
- * @return
- * @throws AuthenticationException
- */
- @Override
- protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
- UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
-
- User user = userService.login(token.getUsername());
- if(user == null){
- return null;
- }
-
- return new SimpleAuthenticationInfo(user
- ,user.getPassword()
- ,new SimpleByteSource(user.getSalt())
- ,"myRealm"
- );
- }
-
-
- /**
- * 授权方法
- * @param principalCollection
- * @return
- */
- @Override
- protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
- User user = (User) principalCollection.getPrimaryPrincipal();
- System.out.println("--->" + user.getUsername());
- SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
- info.addRole("admin");
- info.addRole("root");
- return info;
- }
- }
- package com.bobo.controller;
-
- import com.bobo.pojo.User;
- import com.bobo.service.IUserService;
- import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.Model;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.ResponseBody;
- import org.springframework.web.bind.annotation.RestController;
-
- import javax.servlet.http.HttpServletRequest;
- import java.util.List;
-
- @Controller
- public class UserController {
-
- @Autowired
- private IUserService service;
-
- @GetMapping("/user/query")
- @ResponseBody
- public String query(){
- return service.query(new User()).toString();
- }
-
- /**
- * 本方法是Realm认证失败后会进入的方法
- * @param model
- * @param request
- * @return
- */
- @RequestMapping("/login.do")
- public String login(Model model, HttpServletRequest request){
- // 当认证失败的时候会将失败信息保存的request对应的属性中
- Object obj = request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
- System.out.println("错误信息:" + obj);
- return "/login.jsp";
- }
-
- }
- <%--
- Created by IntelliJ IDEA.
- User: dpb
- Date: 2021/2/19
- Time: 20:31
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <html>
- <head>
- <title>Title</title>
- </head>
- <body>
-
- <form action="login.do" method="post">
- 账号:<input type="text" name="username" ><br/>
- 密码:<input type="password" name="password"><br/>
- <input type="submit" value="提交">
- </form>
-
- </body>
- </html>
- @RequestMapping("/logout.do")
- public void logout(){
- SecurityUtils.getSubject().logout();
- }
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-aspects</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop.xsd
- ">
- <!-- 配置扫描路径 -->
- <context:component-scan base-package="com.bobo.controller" use-default-filters="false" >
- <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
- </context:component-scan>
- <!-- 开启注解 -->
- <mvc:annotation-driven ></mvc:annotation-driven>
- <!-- 开启Shiro的注解 -->
- <aop:config proxy-target-class="true" />
- <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor" >
- <property name="securityManager" ref="securityManager" />
- </bean>
- </beans>
- /**
- * 授权方法
- * @param principalCollection
- * @return
- */
- @Override
- protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
- User user = (User) principalCollection.getPrimaryPrincipal();
- System.out.println("--->" + user.getUsername());
- SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
- info.addRole("admin");
- info.addRole("root");
- return info;
- }
- package com.bobo.controller;
-
- import org.apache.shiro.authz.annotation.Logical;
- import org.apache.shiro.authz.annotation.RequiresRoles;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
-
- @RestController
- @RequestMapping("/order")
- public class OrderController {
-
- @RequiresRoles(value = {"admin"},logical = Logical.AND)
- @GetMapping("/query")
- public String query(){
- return "query ... ";
- }
-
- @RequiresRoles(value = {"root","root1"},logical = Logical.AND)
- @GetMapping("/add")
- public String add(){
- return "add ... ";
- }
- @RequiresRoles(value = {"root","root1"},logical = Logical.OR)
- @GetMapping("/update")
- public String update(){
- return "update ... ";
- }
-
- @GetMapping("/delete")
- public String delete(){
- return "delete ... ";
- }
- }
- <%--
- Created by IntelliJ IDEA.
- User: dpb
- Date: 2021/2/21
- Time: 14:06
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <html>
- <head>
- <title>Title</title>
- </head>
- <body>
- <h3>您没有访问当前请求的权限!请联系系统管理员:xxxxxxxxx</h3>
- </body>q
- </html>
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop.xsd
- ">
- <!-- 配置扫描路径 -->
- <context:component-scan base-package="com.bobo.controller" use-default-filters="false" >
- <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
- </context:component-scan>
- <!-- 开启注解 -->
- <mvc:annotation-driven ></mvc:annotation-driven>
- <!-- 开启Shiro的注解 -->
- <aop:config proxy-target-class="true" />
- <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor" >
- <property name="securityManager" ref="securityManager" />
- </bean>
-
- <!-- 配置SpringMVC的全局异常处理器 -->
- <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
- <property name="exceptionMappings">
- <props>
- <prop key="org.apache.shiro.authz.UnauthorizedException">redirect:/unauthorized.jsp</prop>
- </props>
- </property>
- </bean>
- </beans>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
- <%--
- Created by IntelliJ IDEA.
- User: dpb
- Date: 2021/2/21
- Time: 14:16
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
- <html>
- <head>
- <title>Title</title>
- </head>
- <body>
- <h1>用户管理</h1>
- <shiro:authenticated>
- <label>
- 用户已登录:<shiro:principal property="username"/>
- </label>
-
- </shiro:authenticated>
- <br>
- <shiro:hasRole name="root">
- <a href="#">查询用户</a><br>
- </shiro:hasRole>
- <shiro:hasRole name="admin">
- <a href="#">添加用户</a><br>
- </shiro:hasRole>
- <shiro:hasRole name="root1">
- <a href="#">更新用户</a><br>
- </shiro:hasRole>
- <shiro:hasAnyRoles name="root1,admin">
- <a href="#">删除用户</a><br>
- </shiro:hasAnyRoles>
- </body>
- </html>
- <shiro:authenticated>
- <label>用户身份验证已通过 </label>
- </shiro:authenticated>
- 123
- <shiro:guest>
- <label>您当前是游客,</label><a href="/login.jsp" >请登录</a>
- </shiro:guest>
- 123
- <shiro:hasRole name="admin">
- <label>这个用户拥有的角色是admin</label>
- </shiro:hasRole>
- 123
- <shiro:hasAnyRoles name="admin,user">
- <label>这是拥有admin或者是user角色的用户</label>
- </shiro:hasAnyRoles>
- 123
- <shiro:hasPermission name="admin:add">
- <label>这个用户拥有admin:add的权限</label>
- </shiro:hasPermission>
- 123
- <shiro:lacksRole name="admin">
- <label>这个用户不拥有admin的角色</label>
- </shiro:lacksRole>
- 123
- <shiro:lacksPermission name="admin:delete">
- <label>这个用户不拥有admin:delete的权限</label>
- </shiro:lacksPermission>
- 123
- <shiro:notAuthenticated>
- <label>用户身份验证没有通过(包括通过记住我(remember me)登录的) </label>
- </shiro:notAuthenticated>
- 123
- <!--取到username-->
- <shiro: principal/>
- <!--需要指定property-->
- <shiro:principal property="username"/>
- <shiro:user>
- <label>欢迎[<shiro:principal/>],</label><a href="/logout.jsp">退出</a>
- </shiro:user>
- <dependency>
- <groupId>org.apache.shiro</groupId>
- <artifactId>shiro-spring</artifactId>
- <version>1.2.3</version>
- </dependency>
- <dependency>
- <groupId>org.apache.shiro</groupId>
- <artifactId>shiro-ehcache</artifactId>
- <version>1.2.3</version>
- </dependency>
- <dependency>
- <groupId>net.sf.ehcache</groupId>
- <artifactId>ehcache-core</artifactId>
- <version>2.5.0</version>
- </dependency>
- <?xml version="1.0" encoding="UTF-8"?>
- <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
- <!--diskStore:缓存数据持久化的目录 地址 -->
- <diskStore path="C:\tools\ehcache" />
- <!--
- eternal:缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。
- maxElementsInMemory:缓存中允许创建的最大对象数
- overflowToDisk:内存不足时,是否启用磁盘缓存。
- timeToIdleSeconds:缓存数据的钝化时间,也就是在一个元素消亡之前, 两次访问时间的最大时间间隔值,这只能在元素不是永久驻留时有效,如果该值是 0 就意味着元素可以停顿无穷长的时间。
- timeToLiveSeconds:缓存数据的生存时间,也就是一个元素从构建到消亡的最大时间间隔值,这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间。
- memoryStoreEvictionPolicy:缓存满了之后的淘汰算法。
- diskPersistent:设定在虚拟机重启时是否进行磁盘存储,默认为false
- diskExpiryThreadIntervalSeconds: 属性可以设置该线程执行的间隔时间(默认是120秒,不能太小
- 1 FIFO,先进先出
- 2 LFU,最少被使用,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
- 3 LRU,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
- -->
- <defaultCache
- maxElementsInMemory="1000"
- maxElementsOnDisk="10000000"
- eternal="false"
- overflowToDisk="false"
- diskPersistent="false"
- timeToIdleSeconds="120"
- timeToLiveSeconds="120"
- diskExpiryThreadIntervalSeconds="120"
- memoryStoreEvictionPolicy="LRU">
- </defaultCache>
- </ehcache>
- <!-- 配置缓存管理器 -->
- <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
- <!-- 关联配置文件 -->
- <property name="cacheManagerConfigFile" value="classpath:shiroehcache.xml"/>
- </bean>
-
- <!-- 注册SecurityManager -->
- <bean class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"id="securityManager">
- <!-- 配置自定义Realm -->
- <property name="realm" ref="myRealm"/>
- <property name="cacheManager" ref="cacheManager"/>
- </bean>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。