Shiro的Demo示例

多余的就不说了,,

直接上代码了。


package com.shiro.lh.demo2;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.HashRequest;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.Factory;
import org.apache.shiro.crypto.hash.DefaultHashService;
import org.apache.shiro.util.SimpleByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class ShiroDemo2
{
private static Logger logger = LoggerFactory.getLogger(ShiroDemo2.class); 

public static void main(String[] args)
{
//获取SecurityManagerFactory工厂,也可以使用数据库来获取,这里使用ini文件来初始化
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");

//得到SecurityManger,并且进行绑定到SecuriUtils
SecurityManager securityManager = (SecurityManager)factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);

//得到Subject及创建用户名/密码身份验证Token(用户身份或者是凭证)
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("lh", "123123");

try
{
subject.login(token);
}

catch (UnknownAccountException uae)
{
logger.info("用户名为【" + token.getPrincipal() + "】不存在");
}
catch (IncorrectCredentialsException ice)
{
logger.info("用户名为【 " + token.getPrincipal() + " 】密码错误!");
}
catch (LockedAccountException lae)
{
logger.info("用户名为【" + token.getPrincipal() + " 】的账户锁定,请联系管理员。");
}
catch(DisabledAccountException dax)
{
logger.info("用户名为:【" + token.getHost() + "】用户已经被禁用.");
}
catch(ExcessiveAttemptsException eae)
{
logger.info("用户名为:【" + token.getHost() + "】的用户登录次数过多,有暴力破解的嫌疑.");
}
catch(ExpiredCredentialsException eca)
{
logger.info("用户名为:【" + token.getHost() + "】用户凭证过期.");
}
catch (AuthenticationException ae)
{
logger.info("用户名为:【" + token.getHost() + "】用户验证失败.");
}
catch(Exception e)
{
logger.info("别的异常信息。。。。具体查看继承关系");
}


//
logger.info("用户名 【" + subject.getPrincipal() + "】密码:【" + subject.getPrincipal() + "】登录成功.");

if(subject.hasRole("user"))
{
logger.info("拥有【user】角色。");
}
else
{
logger.info("不存在user权限。");
}

try
{
subject.checkPermission("users:create:del:upd");
}
catch (AuthorizationException e)
{
e.printStackTrace();
}


if(subject.isPermitted("users:create"))
{
logger.info("拥有【users:del】删除权限");
}
else
{
logger.info("不存在【users:del】删除权限");
}

logger.info(subject.getPrincipal().toString() + "用户 登录状态:" + subject.isAuthenticated());

subject.logout();

//对密码md5加密,并且进行私盐
String baseCode = new Md5Hash("123123", "1223").toString();
// System.out.println(baseCode);

/**使用私盐和公盐进行加密****/
DefaultHashService hashService = new DefaultHashService(); //默认算法SHA-512
hashService.setHashAlgorithmName("SHA-384");
hashService.setPrivateSalt(new SimpleByteSource("zhongguo")); //私盐,默认无
hashService.setRandomNumberGenerator(new SecureRandomNumberGenerator());//用于生成公盐。默认就是这个
hashService.setHashIterations(2); //生成Hash值的迭代次数
hashService.setGeneratePublicSalt(true); //是否生成公盐,默认false


HashRequest request = new HashRequest.Builder()
.setAlgorithmName("MD5").setSource(ByteSource.Util.bytes("Rayn123"))
.setSalt(ByteSource.Util.bytes("123123")).setIterations(2).build();



String hex = hashService.computeHash(request).toHex();


System.out.println(hex);

}
}



转载于:https://my.oschina.net/Rayn/blog/214708

以下是一个简单的Apache Shiro代码示例,包括如何创建Shiro安全管理器,如何配置Shiro的认证和授权策略,以及如何使用Shiro进行认证和授权。 1. 创建Shiro安全管理器 ```java DefaultSecurityManager securityManager = new DefaultSecurityManager(); ``` 2. 配置Shiro的认证和授权策略 ```java // 配置认证策略 HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher("SHA-256"); credentialsMatcher.setHashIterations(2); MyRealm realm = new MyRealm(); realm.setCredentialsMatcher(credentialsMatcher); securityManager.setRealm(realm); // 配置授权策略 SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); authorizationInfo.addRole("admin"); authorizationInfo.addStringPermission("user:create"); authorizationInfo.addStringPermission("user:update"); authorizationInfo.addStringPermission("user:delete"); securityManager.setAuthorizationInfo(authorizationInfo); ``` 3. 实现Shiro的Realm接口 ```java public class MyRealm extends AuthorizingRealm { // 实现认证方法 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken upToken = (UsernamePasswordToken) token; String username = upToken.getUsername(); String password = getPasswordByUsername(username); if (password == null) { throw new UnknownAccountException("用户名不存在!"); } SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username, password, getName()); return authenticationInfo; } // 实现授权方法 @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { String username = (String) principals.getPrimaryPrincipal(); SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); authorizationInfo.setRoles(getRolesByUsername(username)); authorizationInfo.setStringPermissions(getPermissionsByUsername(username)); return authorizationInfo; } // 模拟数据库查询用户密码 private String getPasswordByUsername(String username) { return "123456"; } // 模拟数据库查询用户角色 private Set<String> getRolesByUsername(String username) { Set<String> roles = new HashSet<>(); roles.add("admin"); return roles; } // 模拟数据库查询用户权限 private Set<String> getPermissionsByUsername(String username) { Set<String> permissions = new HashSet<>(); permissions.add("user:create"); permissions.add("user:update"); permissions.add("user:delete"); return permissions; } } ``` 4. 使用Shiro进行认证和授权 ```java // 创建Subject对象 Subject subject = SecurityUtils.getSubject(); // 创建认证Token UsernamePasswordToken token = new UsernamePasswordToken("admin", "123456"); // 进行认证 subject.login(token); // 进行授权 boolean hasRole = subject.hasRole("admin"); boolean hasPermission = subject.isPermitted("user:create"); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值