经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring Boot » 查看文章
Spring Boot 集成 Shiro实现权限控制
来源:cnblogs  作者:少年喝了这个java吧  时间:2018/11/16 10:30:51  对本文有异议

前提:

本文主要讲解Spring Boot 与 Shiro的集成 与权限控制的实现方式(主要以代码实现功能为主),主要用到的技术Spring Boot+Shiro+Jpa(通过Maven构建),并不会涉及到Shiro框架的源码分析

如果有想要学习Shiro框架的小伙伴可以去http://shiro.apache.org/官网自行学习,并推荐一个中文学习Shiro的网站https://www.sojson.com/shiro(感觉挺不错的)

需求说明:

通过SpringBoot+Shiro实现用户登录验证,授权,对不同用户角色访问资源进行验证,对用户权限访问资源验证,通过迭代加密方式提高用户密码的安全性

用户 and 角色表关系 多对多

角色 and 权限表关系 多对多

废话不多说直接上代码:

此项目是Maven多模块项目 码云地址 https://gitee.com/h-java/springboot-parent-demo

小伙伴们代码里的注释我已经写的很详细了,所以博客里不做讲解,直接看代码注释讲解就可以了

SQL文件

 

  1. /*Navicat MySQL Data Transfer
  2.  
  3. Source Server         : localhost
  4. Source Server Version : 50520
  5. Source Host           : localhost:3306
  6. Source Database       : shiro-demo
  7.  
  8. Target Server Type    : MYSQL
  9. Target Server Version : 50520
  10. File Encoding         : 65001
  11.  
  12. Date: 2018-11-15 16:59:02*/SET FOREIGN_KEY_CHECKS=0;-- ----------------------------
  13. -- Table structure for hibernate_sequence-- ----------------------------DROP TABLE IF EXISTS `hibernate_sequence`;
  14. CREATE TABLE `hibernate_sequence` (
  15.   `next_val` bigint(20) DEFAULT NULL
  16. ) ENGINE=MyISAM DEFAULT CHARSET=utf8;-- ----------------------------
  17. -- Records of hibernate_sequence-- ----------------------------INSERT INTO `hibernate_sequence` VALUES ('4');
  18. INSERT INTO `hibernate_sequence` VALUES ('4');
  19. INSERT INTO `hibernate_sequence` VALUES ('4');-- ----------------------------
  20. -- Table structure for permission_t-- ----------------------------DROP TABLE IF EXISTS `permission_t`;
  21. CREATE TABLE `permission_t` (
  22.   `id` int(11) NOT NULL,
  23.   `name` varchar(255) DEFAULT NULL,
  24.   PRIMARY KEY (`id`)
  25. ) ENGINE=MyISAM DEFAULT CHARSET=utf8;-- ----------------------------
  26. -- Records of permission_t-- ----------------------------INSERT INTO `permission_t` VALUES ('1', 'Retrieve');
  27. INSERT INTO `permission_t` VALUES ('2', 'Create');
  28. INSERT INTO `permission_t` VALUES ('3', 'Update');
  29. INSERT INTO `permission_t` VALUES ('4', 'Delete');-- ----------------------------
  30. -- Table structure for role-- ----------------------------DROP TABLE IF EXISTS `role`;
  31. CREATE TABLE `role` (
  32.   `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  33.   `role` varchar(255) DEFAULT NULL,
  34.   PRIMARY KEY (`id`)
  35. ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;-- ----------------------------
  36. -- Records of role-- ----------------------------INSERT INTO `role` VALUES ('1', 'user');
  37. INSERT INTO `role` VALUES ('2', 'admin');-- ----------------------------
  38. -- Table structure for role_permission_t-- ----------------------------DROP TABLE IF EXISTS `role_permission_t`;
  39. CREATE TABLE `role_permission_t` (
  40.   `pid` int(11) NOT NULL,
  41.   `rid` int(11) NOT NULL,
  42.   KEY `FKt2l638rvh84yplqqu7odiwhdx` (`rid`),
  43.   KEY `FKh946y0ynuov5ynnrn024vapg9` (`pid`)
  44. ) ENGINE=MyISAM DEFAULT CHARSET=utf8;-- ----------------------------
  45. -- Records of role_permission_t-- ----------------------------INSERT INTO `role_permission_t` VALUES ('1', '1');
  46. INSERT INTO `role_permission_t` VALUES ('1', '2');
  47. INSERT INTO `role_permission_t` VALUES ('2', '2');
  48. INSERT INTO `role_permission_t` VALUES ('3', '2');
  49. INSERT INTO `role_permission_t` VALUES ('1', '3');
  50. INSERT INTO `role_permission_t` VALUES ('2', '3');
  51. INSERT INTO `role_permission_t` VALUES ('3', '3');
  52. INSERT INTO `role_permission_t` VALUES ('4', '3');-- ----------------------------
  53. -- Table structure for role_t-- ----------------------------DROP TABLE IF EXISTS `role_t`;
  54. CREATE TABLE `role_t` (
  55.   `id` int(11) NOT NULL,
  56.   `role` varchar(255) DEFAULT NULL,
  57.   PRIMARY KEY (`id`)
  58. ) ENGINE=MyISAM DEFAULT CHARSET=utf8;-- ----------------------------
  59. -- Records of role_t-- ----------------------------INSERT INTO `role_t` VALUES ('1', 'guest');
  60. INSERT INTO `role_t` VALUES ('2', 'user');
  61. INSERT INTO `role_t` VALUES ('3', 'admin');-- ----------------------------
  62. -- Table structure for user-- ----------------------------DROP TABLE IF EXISTS `user`;
  63. CREATE TABLE `user` (
  64.   `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  65.   `username` varchar(255) DEFAULT NULL,
  66.   `password` varchar(255) DEFAULT NULL,
  67.   `role` varchar(255) DEFAULT NULL,
  68.   PRIMARY KEY (`id`)
  69. ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;-- ----------------------------
  70. -- Records of user-- ----------------------------INSERT INTO `user` VALUES ('1', 'howie', '123456', 'user');
  71. INSERT INTO `user` VALUES ('2', 'swit', '123456789', 'admin');-- ----------------------------
  72. -- Table structure for user_role_t-- ----------------------------DROP TABLE IF EXISTS `user_role_t`;
  73. CREATE TABLE `user_role_t` (
  74.   `rid` int(11) NOT NULL,
  75.   `uid` bigint(20) NOT NULL,
  76.   KEY `FKe6b6umcoegdbmjws9e9y0n2jj` (`uid`),
  77.   KEY `FK8lhd80hb3gbdbvdmlkn2oyprl` (`rid`)
  78. ) ENGINE=MyISAM DEFAULT CHARSET=utf8;-- ----------------------------
  79. -- Records of user_role_t-- ----------------------------INSERT INTO `user_role_t` VALUES ('3', '2');
  80. INSERT INTO `user_role_t` VALUES ('2', '1');
  81. INSERT INTO `user_role_t` VALUES ('1', '3');-- ----------------------------
  82. -- Table structure for user_t-- ----------------------------DROP TABLE IF EXISTS `user_t`;
  83. CREATE TABLE `user_t` (
  84.   `id` bigint(20) NOT NULL,
  85.   `password` varchar(255) DEFAULT NULL,
  86.   `salt` varchar(255) DEFAULT NULL,
  87.   `username` varchar(255) DEFAULT NULL,
  88.   PRIMARY KEY (`id`)
  89. ) ENGINE=MyISAM DEFAULT CHARSET=utf8;-- ----------------------------
  90. -- Records of user_t-- ----------------------------INSERT INTO `user_t` VALUES ('1', 'dd531568fac3d2338bdba66b46b39fd7', '73ee684dd5a07e3b9034b02dcebf4e7c', 'hly');
  91. INSERT INTO `user_t` VALUES ('2', '7f5e269e2f52955a0bbdfdef19281fd4', 'c6dc702282fd467c2c5481617c45a014', 'dxl');
  92. INSERT INTO `user_t` VALUES ('3', 'edec83e7318071af89c8811536fd0a68', 'be535103fe5f98c4cef83cf24ab0d11b', 'zy');

View Code

 

 

 

父POM文件:

  1.  1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4     <modelVersion>4.0.0</modelVersion> 5  6     <groupId>com.boot</groupId> 7     <artifactId>springboot-parent-demo</artifactId> 8     <version>0.0.1-SNAPSHOT</version> 9     <packaging>pom</packaging>10 11     <name>springboot-parent-demo</name>12     <description>Spring Boot Parent Demo</description>13 14     <parent>15         <groupId>org.springframework.boot</groupId>16         <artifactId>spring-boot-starter-parent</artifactId>17         <version>2.0.5.RELEASE</version>18         <relativePath/> <!-- lookup parent from repository -->19     </parent>20 21     <!--编码-->22     <properties>23         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>24         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>25         <java.version>1.8</java.version>26     </properties>27 28     <!--子模块-->29     <modules>30         <module>sb-listener</module>31         <module>sb-configration-file</module>32         <module>sb-shiro</module>33         <module>sb-shiro2</module>34     </modules>35 36     <!-- 版本说明:这里统一管理依赖的版本号 -->37     <dependencyManagement>38         <dependencies>39             <dependency>40                 <groupId>com.example</groupId>41                 <artifactId>sb-listener</artifactId>42                 <version>0.0.1-SNAPSHOT</version>43             </dependency>44         </dependencies>45     </dependencyManagement>46 47     <!--父依赖-->48     <dependencies>49         <dependency>50             <groupId>org.springframework.boot</groupId>51             <artifactId>spring-boot-starter-thymeleaf</artifactId>52         </dependency>53         <dependency>54             <groupId>org.springframework.boot</groupId>55             <artifactId>spring-boot-starter-web</artifactId>56         </dependency>57 58         <dependency>59             <groupId>org.projectlombok</groupId>60             <artifactId>lombok</artifactId>61             <optional>true</optional>62         </dependency>63         <dependency>64             <groupId>org.springframework.boot</groupId>65             <artifactId>spring-boot-starter-test</artifactId>66             <scope>test</scope>67         </dependency>68     </dependencies>69 70     <!--插件依赖-->71     <build>72         <plugins>73             <plugin>74                 <groupId>org.springframework.boot</groupId>75                 <artifactId>spring-boot-maven-plugin</artifactId>76             </plugin>77         </plugins>78     </build>79 80 81 </project>

子模块项目sb-shiro2的POM文件:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3.     <modelVersion>4.0.0</modelVersion>
  4.  
  5.     <groupId>com.example</groupId>
  6.     <artifactId>sb-shiro2</artifactId>
  7.     <version>0.0.1-SNAPSHOT</version>
  8.     <packaging>jar</packaging>
  9.  
  10.     <name>sb-shiro2</name>
  11.     <description>Spring Boot Shiro Demo 2</description>
  12.  
  13.     <parent>
  14.         <groupId>com.boot</groupId>
  15.         <artifactId>springboot-parent-demo</artifactId>
  16.         <version>0.0.1-SNAPSHOT</version>
  17.     </parent>
  18.     
  19.     <dependencies>
  20.         <dependency>
  21.             <groupId>org.springframework.boot</groupId>
  22.             <artifactId>spring-boot-starter-data-jpa</artifactId>
  23.         </dependency>
  24.         <dependency>
  25.             <groupId>org.apache.shiro</groupId>
  26.             <artifactId>shiro-spring</artifactId>
  27.             <version>1.4.0</version>
  28.         </dependency>
  29.  
  30.         <dependency>
  31.             <groupId>com.alibaba</groupId>
  32.             <artifactId>druid</artifactId>
  33.             <version>1.0.19</version>
  34.         </dependency>
  35.  
  36.         <dependency>
  37.             <groupId>mysql</groupId>
  38.             <artifactId>mysql-connector-java</artifactId>
  39.         </dependency>
  40.     </dependencies>
  41.  
  42.     <build>
  43.         <plugins>
  44.             <plugin>
  45.                 <groupId>org.springframework.boot</groupId>
  46.                 <artifactId>spring-boot-maven-plugin</artifactId>
  47.             </plugin>
  48.         </plugins>
  49.     </build>
  50.  
  51.  
  52. </project>

 

 整体项目结构:

 

application.yml

  1. server:
  2.    port: 8088spring:
  3.    application:
  4.       name: shiro
  5.    datasource:
  6.       url: jdbc:mysql://localhost:3306/shiro-demo      username: root
  7.       password: 123456  driver-class-name: com.mysql.jdbc.Driver
  8.    jpa:
  9.       database: mysql
  10.       showSql: true  hibernate:
  11.          ddlAuto: update
  12.       properties:
  13.          hibernate:
  14.             dialect: org.hibernate.dialect.MySQL5Dialect
  15.             format_sql: true

View Code

 

entity包

通过Jpa生成数据库表

User类

  1. package com.example.demo.entity;import lombok.Data;import javax.persistence.*;import java.io.Serializable;import java.util.List;/**
  2.  * Created by hly on 2018\11\14 0014. */@Data
  3. @Entity
  4. @Table(name = "user_t") //数据库生成的表名public class User implements Serializable{private static final long serialVersionUID = 6469007496170509665L;/** * 用户id     */@Id
  5.     @GeneratedValueprivate long id;/** * 用户名     */private String username;/** * 用户密码     */private String password;/** * yan     */private String salt;/** * 用户表和角色表的多对多关联     */@ManyToMany(fetch = FetchType.EAGER)
  6.     @JoinTable(name = "user_role_t",joinColumns = {@JoinColumn(name = "uid")},
  7.             inverseJoinColumns = {@JoinColumn(name = "rid")})private List<SysRole> roles;/** * 对盐进行再次加密
  8.      * @return */public String getCredentialsSalt() {return username + salt + salt;
  9.     }
  10.  
  11. }

View Code

 

 

SysRole类 

  1. package com.example.demo.entity;import lombok.Data;import javax.persistence.*;import java.io.Serializable;import java.util.List;/**
  2.  * Created by hly on 2018\11\14 0014. */@Data
  3. @Entity
  4. @Table(name = "role_t")public class SysRole implements Serializable {private static final long serialVersionUID = 8215278487246865520L;/** * 角色id     */@Id
  5.     @GeneratedValueprivate Integer id;/** * 角色名称     */private String role;/** * 权限与用户的多对多关联     */@ManyToMany
  6.     @JoinTable(name = "user_role_t",joinColumns = {@JoinColumn(name = "rid")},
  7.             inverseJoinColumns = {@JoinColumn(name = "uid")})
  8.     List<User> users;/** * 角色与权限的多对多关联     */@ManyToMany(fetch = FetchType.EAGER)
  9.     @JoinTable(name = "role_permission_t",joinColumns = {@JoinColumn(name = "rid")},
  10.             inverseJoinColumns = {@JoinColumn(name = "pid")})
  11.     List<SysPermission> permissions ;
  12.  
  13. }

View Code

 

 

SysPermission类

  1. package com.example.demo.entity;import lombok.Data;import javax.persistence.*;import java.io.Serializable;import java.util.List;/**
  2.  * Created by hly on 2018\11\14 0014. */@Data
  3. @Entity
  4. @Table(name = "role_t")public class SysRole implements Serializable {private static final long serialVersionUID = 8215278487246865520L;/** * 角色id     */@Id
  5.     @GeneratedValueprivate Integer id;/** * 角色名称     */private String role;/** * 权限与用户的多对多关联     */@ManyToMany
  6.     @JoinTable(name = "user_role_t",joinColumns = {@JoinColumn(name = "rid")},
  7.             inverseJoinColumns = {@JoinColumn(name = "uid")})
  8.     List<User> users;/** * 角色与权限的多对多关联     */@ManyToMany(fetch = FetchType.EAGER)
  9.     @JoinTable(name = "role_permission_t",joinColumns = {@JoinColumn(name = "rid")},
  10.             inverseJoinColumns = {@JoinColumn(name = "pid")})
  11.     List<SysPermission> permissions ;
  12.  
  13. }

View Code

 

mapper接口

  1. package com.example.demo.dao;import com.example.demo.entity.User;import org.springframework.data.jpa.repository.JpaRepository;/**
  2.  * Created by hly on 2018\11\14 0014. */public interface UserMapper extends JpaRepository<User,Long>{
  3.     User findUserByUsername(String username);
  4. }

View Code

 

UserService

  1. package com.example.demo.service;import com.example.demo.dao.UserMapper;import com.example.demo.entity.User;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;/**
  2.  * Created by hly on 2018\11\14 0014. */@Servicepublic class UserService {
  3.  
  4.     @Autowiredprivate UserMapper userMapper;public User findUserByName(String username){return userMapper.findUserByUsername(username);
  5.     }public User saveUser(User user){return userMapper.save(user);
  6.     }
  7. }

View Code

 

Shiro包

ShiroConfig

  1. package com.example.demo.shiro;import org.apache.shiro.authc.credential.HashedCredentialsMatcher;import org.apache.shiro.mgt.SecurityManager;import org.apache.shiro.spring.web.ShiroFilterFactoryBean;import org.apache.shiro.web.mgt.DefaultWebSecurityManager;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import java.util.HashMap;import java.util.Map;/**
  2.  * Created by hly on 2018\11\14 0014. */@Configurationpublic class ShiroConfig {// shiro filter    @Beanpublic ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
  3.         ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
  4.         shiroFilterFactoryBean.setSecurityManager(securityManager);
  5.  
  6.         Map<String, String> filterChainDefinitionMap = new HashMap<String, String>();//登录界面,没有登录的用户访问授权的界面就会跳转到该界面shiroFilterFactoryBean.setLoginUrl("/login");//没有授权的资源,都可以访问,用户访问授权的资源无权限时跳转到该界面shiroFilterFactoryBean.setUnauthorizedUrl("/unauthc");
  7.         shiroFilterFactoryBean.setSuccessUrl("/home/index");//所有路径都拦截filterChainDefinitionMap.put("/*", "anon");//授权资源,只有登录了才能访问,并且有该对应权限的用户才可以访问filterChainDefinitionMap.put("/authc/index", "authc");
  8.         filterChainDefinitionMap.put("/authc/admin", "roles[admin]");
  9.         filterChainDefinitionMap.put("/authc/renewable", "perms[Create,Update]");
  10.         filterChainDefinitionMap.put("/authc/removable", "perms[Delete]");
  11.         filterChainDefinitionMap.put("/authc/retrievable", "perms[Retrieve]");
  12.         shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
  13.         System.out.println("shirFilter配置成功");return shiroFilterFactoryBean;
  14.     }//授权管理者    @Beanpublic SecurityManager securityManager() {
  15.         DefaultWebSecurityManager  securityManager = new DefaultWebSecurityManager();
  16.         securityManager.setRealm(shiroRealm());return securityManager;
  17.     }//shiro realm    @Beanpublic EnceladusShiroRealm shiroRealm() {
  18.         EnceladusShiroRealm shiroRealm = new EnceladusShiroRealm();
  19.         shiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());return shiroRealm;
  20.     }//设置算法和迭代    @Beanpublic HashedCredentialsMatcher hashedCredentialsMatcher() {
  21.         HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
  22.         hashedCredentialsMatcher.setHashAlgorithmName(PasswordHelper.ALGORITHM_NAME);// 散列算法hashedCredentialsMatcher.setHashIterations(PasswordHelper.HASH_ITERATIONS);// 散列次数return hashedCredentialsMatcher;
  23.     }//密码加密    @Beanpublic PasswordHelper passwordHelper() {return new PasswordHelper();
  24.     }
  25. }

View Code

 

EnceladusShiroRealm

  1. package com.example.demo.shiro;import com.example.demo.entity.SysPermission;import com.example.demo.entity.SysRole;import com.example.demo.entity.User;import com.example.demo.service.UserService;import org.apache.shiro.authc.AuthenticationException;import org.apache.shiro.authc.AuthenticationInfo;import org.apache.shiro.authc.AuthenticationToken;import org.apache.shiro.authc.SimpleAuthenticationInfo;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.springframework.beans.factory.annotation.Autowired;/**
  2.  * Created by hly on 2018\11\14 0014.
  3.  * shiro中用户自定义登录验证和授权认证的地方(realm) */public class EnceladusShiroRealm extends AuthorizingRealm{
  4.  
  5.     @Autowiredprivate UserService userService;/** * 授权认证
  6.      * @param principal
  7.      * @return */@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {//负责装载role和permission的对象SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();//获取用户名String username = (String) principal.getPrimaryPrincipal();//获取用户User user = userService.findUserByName(username);//遍历角色和权限,并把名称加入到authorizationInfo中for (SysRole role:user.getRoles()) {
  8.             authorizationInfo.addRole(role.getRole());for(SysPermission permission:role.getPermissions()) {
  9.                 authorizationInfo.addStringPermission(permission.getName());
  10.             }
  11.         }return authorizationInfo;
  12.     }/** * 登录验证
  13.      * @param token
  14.      * @return * @throws AuthenticationException     */@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {//获取用户名String username = (String)token.getPrincipal();//查寻用户User user = userService.findUserByName(username);//逻辑if (user == null) {return null;
  15.         }//包装对象(用户名、密码、用户Salt、抽象类CachingRealm的getName())SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(),
  16.                 ByteSource.Util.bytes(user.getCredentialsSalt()),getName());
  17.         System.out.println("getName():"+getName());//返回SimpleAuthenticationInfo对象return authenticationInfo;
  18.     }
  19. }

View Code

 

PasswordHelper

  1. package com.example.demo.shiro;import com.example.demo.entity.User;import org.apache.shiro.crypto.RandomNumberGenerator;import org.apache.shiro.crypto.SecureRandomNumberGenerator;import org.apache.shiro.crypto.hash.SimpleHash;import org.apache.shiro.util.ByteSource;/**
  2.  * Created by hly on 2018\11\14 0014.
  3.  * 对密码进行迭代加密,保证用户密码的安全 */public class PasswordHelper {//安全的随机字符private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();//算法名称public static final String ALGORITHM_NAME = "md5";//迭代次数public static final int HASH_ITERATIONS = 2;public void encryptPassword(User user) {//随机字符串作为用户的Salt        user.setSalt(randomNumberGenerator.nextBytes().toHex());//算法、用户密码、用户Salt、迭代次数String newPassword = new SimpleHash(ALGORITHM_NAME,user.getPassword(),
  4.                 ByteSource.Util.bytes(user.getCredentialsSalt()),HASH_ITERATIONS).toHex();//对用户设置新密码        user.setPassword(newPassword);
  5.     }
  6.  
  7.  
  8. }

View Code

 

Controller包

AuthcController

  1. package com.example.demo.controller;import com.example.demo.entity.User;import org.apache.shiro.SecurityUtils;import org.apache.shiro.subject.Subject;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;/**
  2.  * 验证的接口 */@RestController
  3. @RequestMapping("authc")public class AuthcController {
  4.  
  5.     @GetMapping("index")public Object index() {
  6.         Subject subject = SecurityUtils.getSubject();
  7.         User user = (User) subject.getSession().getAttribute("user");return user.toString();
  8.     }
  9.  
  10.     @GetMapping("admin")public Object admin() {return "Welcome Admin";
  11.     }// delete@GetMapping("removable")public Object removable() {return "removable";
  12.     }// creat & update@GetMapping("renewable")public Object renewable() {return "renewable";
  13.     }
  14.  
  15.     @GetMapping("retrievable")public Object retrievable() {return "retrievable";}
  16.  
  17. }

View Code

 

HomeController

  1. package com.example.demo.controller;import com.example.demo.entity.User;import com.example.demo.service.UserService;import com.example.demo.shiro.PasswordHelper;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.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;/**
  2.  * 不验证的接口 */@RestController
  3. @RequestMappingpublic class HomeController {
  4.  
  5.     @Autowiredprivate UserService userService;
  6.  
  7.     @Autowiredprivate PasswordHelper passwordHelper;
  8.  
  9.     @GetMapping("/login")public Object login() {return "Here is Login page";
  10.     }
  11.  
  12.     @GetMapping("/unauthc")public Object unauthc() {return "Here is Unauthc page";
  13.     }
  14.  
  15.     @GetMapping("doLogin")public Object doLogin(@RequestParam String username, @RequestParam String password) {
  16.         UsernamePasswordToken token = new UsernamePasswordToken(username, password);
  17.         Subject subject = SecurityUtils.getSubject();try {
  18.             subject.login(token);
  19.         } catch (IncorrectCredentialsException ice) {return "password error!";
  20.         } catch (UnknownAccountException uae) {return "username error!";
  21.         }
  22.  
  23.         User user = userService.findUserByName(username);
  24.         subject.getSession().setAttribute("user", user);return "SUCCESS";
  25.     }
  26.  
  27.     @GetMapping("/register")public Object register(@RequestParam String username, @RequestParam String password) {
  28.         User user = new User();
  29.         user.setUsername(username);
  30.         user.setPassword(password);
  31.         passwordHelper.encryptPassword(user);
  32.  
  33.         userService.saveUser(user);return "注册用户SUCCESS";
  34.     }
  35. }

View Code

 

之后运行项目通过rest接口测试

  1. localhost:8088/login
  2. localhost:8088/unauthc
  3. localhost:8088/doLogin?username=hly&password=123等等通过controller里的接口进行运行测试就好了,看运行效果,我就不一一往下copy

 

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号