Apache Shiro代码示例
时间: 2023-07-02 14:18:03 浏览: 109
apache shiro 实例
4星 · 用户满意度95%
以下是一个简单的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");
```
阅读全文