java揭开Shiro神秘面纱
1. Shiro是什么?能干嘛
Shiro是一个安全框架,主要做认证和授权,权限管理框架,一般我们都会在SpringSecurity和Shiro中选一个,拦截器思想Aop
它能在我们登录的时候验证身份,在登录完后对身份权限做出对应的面板功能显示等,在安全管理方面比较强
工欲善其事必先利其器,
//和thymeleaf整合的shiro
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
//Shiro起步依赖
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
1.1 Shiro.ini
Shiro的使用,必须要有一个ini文件配置信息还有个可选的log4j日志文件
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n
# General Apache libraries
log4j.logger.org.apache=WARN
# Spring
log4j.logger.org.springframework=WARN
# Default Shiro logging
log4j.logger.org.apache.shiro=INFO
# Disable verbose logging
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN
Shiro.ini
[users] #角色
# user 'root' with password 'secret' and the 'admin' role
root = secret, admin
# user 'guest' with the password 'guest' and the 'guest' role
guest = guest, guest
# user 'presidentskroob' with password '12345' ("That's the same combination on
# my luggage!!!" ;)), and role 'president'
presidentskroob = 12345, president
# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
darkhelmet = ludicrousspeed, darklord, schwartz
# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
lonestarr = vespa, goodguy, schwartz
# -----------------------------------------------------------------------------
# Roles with assigned permissions
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc
# -----------------------------------------------------------------------------
[roles] #权限
# 'admin' role has all permissions, indicated by the wildcard '*'
admin = *
# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*
# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with
# license plate 'eagle5' (instance specific id)
goodguy = winnebago:drive:eagle5
上面是固定的模板套路,按照官网的QuickStart来的
QuickStart.class
public class Quickstart {
//日志打印
private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
public static void main(String[] args) {
// 创建配置了Shiro SecurityManager的最简单方法
// 领域、用户、角色和权限使用简单的INI配置。
// 我们将使用一个可以摄取.ini文件的工厂来实现这一点
// 返回一个SecurityManager实例:
// 在类路径的根目录下使用shiro.ini文件
// (file:和url:前缀分别从文件和url加载):
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
//简单的Shiro环境已经设置好了,让我们看看你能做些什么:
// 获取当前执行的用户:
Subject currentUser = SecurityUtils.getSubject();
// 使用会话做一些事情(不需要web或EJB容器!!
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Retrieved the correct value! [" + value + "]");
}
// 让我们登录当前用户,这样我们可以检查角色和权限:
if (!currentUser.isAuthenticated()) {
//Token: 令牌
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
token.setRememberMe(true);
try {
currentUser.login(token);
} catch (UnknownAccountException uae) {
log.info("There is no user with username of " + token.getPrincipal());
} catch (IncorrectCredentialsException ice) {
log.info("Password for account " + token.getPrincipal() + " was incorrect!");
} catch (LockedAccountException lae) {
log.info("The account for username " + token.getPrincipal() + " is locked. " +
"Please contact your administrator to unlock it.");
}
// 在这里捕获更多的异常
catch (AuthenticationException ae) {
//unexpected condition? error?
}
}
//打印它们的标识主体(在本例中为用户名):
log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
//test a role:
if (currentUser.hasRole("schwartz")) {
log.info("May the Schwartz be with you!");
} else {
log.info("Hello, mere mortal.");
}
//test a typed permission (not instance-level)
if (currentUser.isPermitted("lightsaber:wield")) {
log.info("You may use a lightsaber ring. Use it wisely.");
} else {
log.info("Sorry, lightsaber rings are for schwartz masters only.");
}
//a (very powerful) Instance Level permission:
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!");
}
//注销
currentUser.logout();
System.exit(0);
}
}
接下来就可以启动主启动类看看日志有无报错,没有就成功了
2. Shiro配置类
首先我们需要一个Relam对象继承AuthorizingRealm,里面有两个方法,认证和授权,
下面这个例子是连接数据库获取的对象信息
public class UserRealm extends AuthorizingRealm {
@Autowired
EmployeeService employeeService;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了授权doGetAuthorizationInfo");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// info.addStringPermission("user:add"); //登录的用户都给一个可以去add的权限
//拿到当前用户对象
Subject subject = SecurityUtils.getSubject();
Employee CurrentEmployee = (Employee)subject.getPrincipal();//拿到employee
info.addStringPermission(CurrentEmployee.getName()); //本来应该单独设置权限字段,这里用名字代替权限
return info;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("认证doGetAuthenticationInfo");
// //用户名,密码,数据中取
// String name="root";
// String password="123456";
UsernamePasswordToken userToken= (UsernamePasswordToken) token;
// if(!userToken.getUsername().equals((name))){
// return null; //抛出异常
// }
//连接真实数据库
Employee employee = employeeService.queryByName(userToken.getUsername());
if(employee==null){
return null; //UnknowAccountExpection
}
Subject CurrentSubject=SecurityUtils.getSubject();
Session session=CurrentSubject.getSession();
session.setAttribute("loginUser","employee");
//密码认证,shiro做 可以加密MD5 子类继承了,有加密类
return new SimpleAuthenticationInfo(employee,employee.getPassword(),"");
}
}
2.1 Shiro之Subject 用户
Subject currentUser=SecurityUtils.getSubject(); //获得当前用户
Session session=currentUser.getSession(); //开启Session
currentUser.isAuthenticated(); //是否认证
currentUser.getPrincipal() //获取权限
currentUser.hasRole("schwartz"); //是否拥有schwartz权限
currentUser.isPermitted("lightsaber:wield"); //允许lightsaber:wield访问
currentUser.logout(); //登出注销
2.1.1 ShiroCofig
UserRealm->DefaultWebSecurityManager->ShiroFilterFactoryBean
三大步骤
- 创建realm对象 需要自定义 第一步
- DefaultWebSecurityManager 安全对象 第二步
- ShiroFilterFactoryBean Shiro过滤对象工厂 第三步 这个里面可以写权限
@Configuration
public class ShiroCofig {
//ShiroFilterFactoryBean Shiro过滤对象工厂 第三步
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//设置安全管理器
bean.setSecurityManager(defaultWebSecurityManager);
//添加Shiro的内置过滤器
/*
* anon 无需认证就可以访问
* authc 必须认证了才能访问
* user 必须有 记住我功能才能用
* perms 拥有堆某个资源的权限才能访问
* role 拥有某个角色
* */
//设置一个过滤器的链 Map
//拦截
Map<String, String> filterMap=new LinkedHashMap<>();
// filterMap.put("/user/add","authc");
// filterMap.put("/user/update","authc");
//授权 正常情况下未授权会401
filterMap.put("/user/add","perms[2]"); //名字为2的才能访问add页面
filterMap.put("/user/update","perms[root]"); //名字为root的才能访问update页面
filterMap.put("/user/*","authc");
bean.setFilterChainDefinitionMap(filterMap);
//设置登录的请求
bean.setLoginUrl("/toLogin");
//设置未授权的请求 页面
bean.setUnauthorizedUrl("/noauth");
return bean;
}
//DefaultWebSecurityManager 安全对象 第二步
//Qualifier 绑定到一个方法上
@Bean(name="securityManager")
public DefaultWebSecurityManager getdefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
//关联UserRelam
securityManager.setRealm(userRealm);
return securityManager;
}
//创建realm对象 需要自定义 第一步
@Bean
public UserRealm userRealm(){
return new UserRealm();
}
//整合ShiroDialect: 用来整合 shiro thymeleaf
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
}
登录认证拦截
filterMap.put("/user/add",“authc”);
filterMap.put("/user/update",“authc”);
bean.setFilterChainDefinitionMap(filterMap); map参数生效
代表了这个两个路劲要认证了才能访问,也就是登录
2.2 Shiro之SecurityMannager 用户管理类
//主要是做一个呈上启下的作用给过滤工作返回一个管理类,
对下就是封装来自userRelam的用户数据信息
DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
//关联UserRelamjava
securityManager.setRealm(userRealm);
return securityManager;
2.3 Shiro之Realm 真实对象数据
2.3.1 认证
Controller层提交登录用户
@RequestMapping({"/login"})
public String login(String username,String password,Model model){
//获取当前的用户
Subject subject = SecurityUtils.getSubject();
//封装用户的登陆数据
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try {
subject.login(token); //登录的方法,没有异常就ok
return "index";
}catch (UnknownAccountException e){
model.addAttribute("msg","用户名错误");
return "login";
}catch (IncorrectCredentialsException e){
model.addAttribute("msg","密码错误");
return "login";
}
}
只要进了登录Controller就会去subject.login(token),走UserRealm认证方法
在自己写的UserRealm类里面有个认证AuthenticationInfo方法里面
它可以直接这样拿到提交的token用户信息然后判断是否数据库对等
UsernamePasswordToken userToken= (UsernamePasswordToken) token;
//连接真实数据库
Employee employee = employeeService.queryByName(userToken.getUsername());
if(employee==null){
return null; //UnknowAccountExpection
}
密码认证就交给Shiro做
return new SimpleAuthenticationInfo(employee,employee.getPassword(),"");
2.3.2 授权
认证返回了employee的用户对象信息,里面有权限字段
return new SimpleAuthenticationInfo(employee,employee.getPassword(),"");
这个方法主要是从认证的时候封装的Subject拿到的用户权限字段,然后给用户赋予这个权限
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了授权doGetAuthorizationInfo");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// info.addStringPermission("user:add"); //登录的用户都给一个可以去add的权限
//拿到当前用户对象
Subject subject = SecurityUtils.getSubject();
Employee CurrentEmployee = (Employee)subject.getPrincipal();//拿到employee
info.addStringPermission(CurrentEmployee.getName()); //本来应该单独设置权限字段,这里用名字代替权限
return info;
}
3. 前端小细节
如果开启这个
//设置未授权的请求 页面
bean.setUnauthorizedUrl("/noauth");
@RequestMapping({"/noauth"})
@ResponseBody
public String unauthorized(){
return "未经授权无法访问此页面";
}
那么如果是访问到没有授权的就会显示这些字,因为会走/noauth路劲
//整合ShiroDialect: 用来整合 shiro thymeleaf
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
上面的写在ShiroConfig里面可以让thymeleaf实现权限展示,有权限的才看的到
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.thymeleaf-extras-shiro">
//头部声明使用shiro和thymeleaf
<div shiro:hasPermission="2">
<a th:href="@{/user/add}">add</a>
</div>
<div shiro:hasPermission="root">
<a th:href="@{/user/update}">update</a>
</div>
有对应权限的才会显示
前后端分离 同源策略如何破
重写一个过滤器,重写请求,通过请求头允许跨域
@Order(-100)
@Component
@ServletComponentScan
@WebFilter(urlPatterns = "/*",filterName = "shiroLoginFilter")
public class ShiroLoginFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpServletRequest request = (HttpServletRequest) servletRequest;
// 允许哪些Origin发起跨域请求
String orgin = request.getHeader("Origin");
// response.setHeader( "Access-Control-Allow-Origin", config.getInitParameter( "AccessControlAllowOrigin" ) );
response.setHeader( "Access-Control-Allow-Origin", orgin );
// 允许请求的方法
response.setHeader( "Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE,PUT" );
//多少秒内,不需要再发送预检验请求,可以缓存该结果
response.setHeader( "Access-Control-Max-Age", "3600" );
// 表明它允许跨域请求包含xxx头
response.setHeader( "Access-Control-Allow-Headers", "x-auth-token,Origin,Access-Token,X-Requested-With,Content-Type, Accept" );
//是否允许浏览器携带用户身份信息(cookie)
response.setHeader( "Access-Control-Allow-Credentials", "true" );
//prefight请求
if (request.getMethod().equals( "OPTIONS" )) {
response.setStatus( 200 );
return;
}
chain.doFilter( servletRequest, response );
}
@Override
public void destroy() {
}
}