shiro目录:
shior作为轻量级的权限管理框架,相较于SpringSecurity框架,没有其强大的功能,但在是学习和实际使用中,shiro可以满足基本的使用,包括有身份验证、授权、加密的功能
shiro的功能介绍,分为以下几块(官方介绍,看不懂 的可以稍微瞅一眼,然后基础代码看,回头再看更加容易理解)
Authentication:身份认证/登录,验证用户是不是拥有相应的身份;
Authorization:授权,即权限验证,验证某个已认证的用户是否拥有某个权限;即判断用户是否能做事情,常见的如:验证某个用户是否拥有某个角色。或者细粒度的验证某个用户对某个资源是否具有某个权限;
Session Manager:会话管理,即用户登录后就是一次会话,在没有退出之前,它的所有信息都在会话中;会话可以是普通 JavaSE 环境的,也可以是如 Web 环境的;
Cryptography:加密,保护数据的安全性,如密码加密存储到数据库,而不是明文存储;
Web Support:Web 支持,可以非常容易的集成到 Web 环境;
Caching:缓存,比如用户登录后,其用户信息、拥有的角色/权限不必每次去查,这样可以提高效率;
Concurrency:shiro 支持多线程应用的并发验证,即如在一个线程中开启另一个线程,能把权限自动传播过去;
Testing:提供测试支持;
Run As:允许一个用户假装为另一个用户(如果他们允许)的身份进行访问;
Remember Me:记住我,这个是非常常见的功能,即一次登录后,下次再来的话不用登录
详解:
- Authentication:
- 官方定义:Authentication: Sometimes referred to as ‘login’, this is the act of proving a user is who they say they are.
翻译:身份验证,通常是在登录是,通过对用户的信息(账号、密码)进行验证,如果登录失败会抛出异常
- 流程图:
Subject:表示“用户”,表示当前执行的用户。Subject 实例全部都绑定到了一个 SecurityManager 上,当和 Subject 交互时,它是委托给 SecurityManager 去执行的
SecurityManager:Shiro 结构的心脏,协调它内部的安全组件(如登录,授权,数据源等)。当整个应用配置好了以后,大多数时候都是直接和 Subject 的 API 打交道。
Realm:数据源,也就是抽象意义上的 DAO 层。它负责和安全数据交互(比如存储在数据库的账号、密码,权限等信息),包括获取和验证。Shiro 支持多个 Realm,但是至少也要有一个。Shiro 自带了很多开箱即用的 Reams,比如支持 LDAP、关系数据库(JDBC)、INI 和 properties 文件等。但是很多时候我们都需要实现自己的 Ream 去完成获取数据和判断的功能
登录流程:Subject 执行 login 方法,传入登录的用户名和密码,然后 SecurityManager将这个 login 操作委托给内部的登录模块,登录模块就调用 Realm 去获取安全的用户名和密码,然后对比,一致则登录,不一致则登录抛出异常
- 核心代码
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
- 通过用户名和密码生成token,调用Subject.login 进行登录验证(调用shiro的Realm 类进行验证)
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
public class ShiroLogin {
public static String login(UsernamePasswordToken token){
// 从SecurityUtils里边创建一个 subject
Subject subject = SecurityUtils.getSubject();
try {
subject.login(token);
} catch (UnknownAccountException uae) {
return "未知账户";
} catch (IncorrectCredentialsException ice) {
return "密码不正确";
} catch (LockedAccountException lae) {
return "账户已锁定";
} catch (ExcessiveAttemptsException eae) {
return "用户名或密码错误次数过多";
} catch (AuthenticationException ae) {
return "用户名或密码不正确!";
}
if (subject.isAuthenticated()) {
return "登录成功";
} else {
token.clear();
return "登录失败";
}
}
}
- Realm类包含两个方法doGetAuthorizationInfo和doGetAuthenticationInfo
- doGetAuthorizationInfo方法用来获取用户权限信息
- doGetAuthenticationInfo方法是获取用户登录凭证信息
- 代码如下:
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.SecurityUtils;
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.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import java.util.HashSet;
import java.util.Set;
public class CustomRealm extends AuthorizingRealm {
private static final transient Logger log = LoggerFactory.getLogger(CustomRealm.class);
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
log.info("------获取用户身份信息------");
String username = (String) SecurityUtils.getSubject().getPrincipal();
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
Set<String> stringSet = new HashSet<>();
stringSet.add("user:show");
stringSet.add("user:admin");
info.setStringPermissions(stringSet);
return info;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("-------身份认证方法--------");
String userName = (String) authenticationToken.getPrincipal();
String userPwd = new String((char[]) authenticationToken.getCredentials());
//模拟 根据用户名从数据库获取密码
String password = "2415b95d3203ac901e287b76fcef640b";
if (userName == null) {
throw new AccountException("用户名不正确");
} else if (!userPwd.equals(userPwd)) {
throw new AccountException("密码不正确");
}
//交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配
String name = getName();
System.out.println("name:"+name);
return new SimpleAuthenticationInfo(userName, password,
ByteSource.Util.bytes(userName + "salt"), getName());
}
}
执行登录操作:
/**
* 登录操作
* @param username
* @param password
* @return
*/
@RequestMapping(value = "/login", method = RequestMethod.POST)
@ResponseBody
public String login(@RequestParam("username") String username, @RequestParam("password") String password) {
// 在认证提交前准备 token(令牌)
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
// 执行认证登陆
return shiroLogin.login(token);
}
测试:
1.输入密码错误
2.输入密码正确
欢迎留言一起讨论
github地址:shiro