shiro简介
shiro介绍
实现原理理解:
也就是说对于我们而言,最简单的一个 Shiro 应用:
应用代码通过 Subject 来进行认证和授权,而 Subject 又委托给 SecurityManager; 我们需要给 Shiro 的 SecurityManager 注入 Realm,从而让 SecurityManager 能得到合法
的用户及其权限进行判断。
环境搭建
1、pom文件
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yun</groupId>
<artifactId>springboot-shiro</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-shiro</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.19</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<!--shiro-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2、application.yml
server:
port: 8081
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/shiro_use?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
type: com.alibaba.druid.pool.DruidDataSource
mybatis:
mapper-locations: classpath:mybatis/*
type-aliases-package: com.yun.pojo
3、实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Long id;
private String name;
private Integer password;
private String permission;
}
shiro配置类
package com.yun.config;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap;
import java.util.Map;
@Configuration
public class ShiroConfig {
//ShiroFilterFactoryBean 过滤对象
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager securityManager){
ShiroFilterFactoryBean bean=new ShiroFilterFactoryBean();
//设置安全管理器
bean.setSecurityManager(securityManager);
//添加shiro的内置过滤器
/**
*
* anon:无需认证就可以访问
* authc:必须认证才可访问
* user:必须有记住我才可以访问
* perms:拥有某个权限才可以访问
* role:拥有某个角色权限才可以访问
*/
Map<String,String> filterMap=new LinkedHashMap<>();
// filterMap.put("/user/*","authc");
filterMap.put("/user/add","perms[add]");
bean.setFilterChainDefinitionMap(filterMap);
bean.setLoginUrl("/login");
return bean;
}
//DefaultwebSecurityManager 安全对象:2
@Bean("securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
//关联userRealm
securityManager.setRealm(userRealm);
return securityManager;
}
//创建 realm 对象,需要自定义类去继承AuthorizingRealm:1
@Bean("userRealm")
public UserRealm userRealm(){
return new UserRealm();
}
}
package com.yun.config;
import com.yun.pojo.User;
import com.yun.service.UserService;
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.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
public class UserRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了授权==>doGetAuthorizationInfo");
SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
//拿到当前用户
Subject subject=SecurityUtils.getSubject();
User currentUser=(User) subject.getPrincipal();
//设置当前用户权限
info.addStringPermission(currentUser.getPermission());
return info;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("执行了认证==>doGetAuthenticationInfo");
UsernamePasswordToken userToken=(UsernamePasswordToken)authenticationToken;
User user=userService.findByName(userToken.getUsername());
if (user==null){
return null;
}
//密码认证
return new SimpleAuthenticationInfo(user,user.getPassword().toString(),"");//此处password为string类型
}
}
LoginController
package com.yun.controller;
import com.yun.pojo.User;
import com.yun.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class LoginController {
@Autowired
private UserService userService;
@RequestMapping("/logout")
public String logout(){
Subject subject=SecurityUtils.getSubject();
subject.logout();
return "logout";
}
@RequestMapping("/login")
public String login(@RequestBody User user){
// Integer password=user.getPassword();
// User user1=userService.findByName(user.getName());
// if (password.equals(user1.getPassword())){
// return "login,Ok";
//
// }else {
// return "login ,error";
// }
Subject subject=SecurityUtils.getSubject();
UsernamePasswordToken token=new UsernamePasswordToken(user.getName(),user.getPassword().toString());
try {
subject.login(token);
return "ok";
}catch (UnknownAccountException e){
return "用户名错误";
}catch (IncorrectCredentialsException e){
return "密码错误";
}
}
}