博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
实战:Springboot整合shiro实现权限控制实战
阅读量:3961 次
发布时间:2019-05-24

本文共 14212 字,大约阅读时间需要 47 分钟。

目录

1.项目结构

在这里插入图片描述

2.pom

4.0.0
com.wo
home_shiro_springboot
1.0-SNAPSHOT
org.springframework.boot
spring-boot-starter-parent
2.0.3.RELEASE
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.1.1
mysql
mysql-connector-java
org.springframework.boot
spring-boot-starter-thymeleaf
org.apache.shiro
shiro-spring
1.4.0
org.springframework.boot
spring-boot-starter-data-jpa
org.projectlombok
lombok
true
io.springfox
springfox-swagger2
2.8.0
io.springfox
springfox-swagger-ui
2.8.0

3.application.yml

server:  port: 8088spring:  datasource:    driver-class-name: com.mysql.jdbc.Driver    username: root    password: 123456    url: jdbc:mysql:///qf?useUnicode=true&characterEncoding=utf8&useSSL=false  jpa:    database: mysql    show-sql: true    generate-ddl: truemybatis:  mapper-locations: classpath:mapper/*Mapper.xml

4.config

4.1.ShiroConfig

@Configurationpublic class ShiroConfig {
//1.获取到我们的myrealm @Bean(name = "myRealm") public MyRealm myRealm(@Qualifier("hashedCredentialsMatcher")HashedCredentialsMatcher matcher){
MyRealm myRealm = new MyRealm(); myRealm.setAuthorizationCachingEnabled(false); myRealm.setCredentialsMatcher(matcher); return myRealm; } //2.声明securityManager @Bean(name = "defaultWebSecurityManager") public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("myRealm") MyRealm myRealm){
//shiro核心 DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager(); //在核心中设置我们自定义的realm defaultWebSecurityManager.setRealm(myRealm); return defaultWebSecurityManager; } //3.工厂 @Bean public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager")DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager); //权限 //声明没有权限的情况下走的接口名称 shiroFilterFactoryBean.setUnauthorizedUrl("/unauth");// //告诉shiro有用什么权限可以访问什么接口 //如果不加注解不加map,默认没有权限控制// Map map = new HashMap<>();// map.put("/findAll","perms[user_findAll]");// map.put("/deleteById","perms[user_delete]");// //将访问接口的权限放置到shiroFileter中// shiroFilterFactoryBean.setFilterChainDefinitionMap(map); return shiroFilterFactoryBean; } //使用aop注解模式来使用权限 //使用aop扫描包含shiro注解的类 @Bean public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){
DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator(); defaultAdvisorAutoProxyCreator.setProxyTargetClass(true); return defaultAdvisorAutoProxyCreator; } //将WebSecurityManager 交给spring aop来进行管理 @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(@Qualifier("defaultWebSecurityManager")DefaultWebSecurityManager defaultWebSecurityManager){
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); authorizationAttributeSourceAdvisor.setSecurityManager(defaultWebSecurityManager); return authorizationAttributeSourceAdvisor; } /** * 密码校验规则HashedCredentialsMatcher * 这个类是为了对密码进行编码的 , * 防止密码在数据库里明码保存 , 当然在登陆认证的时候 , * 这个类也负责对form里输入的密码进行编码 * 处理认证匹配处理器:如果自定义需要实现继承HashedCredentialsMatcher */ @Bean("hashedCredentialsMatcher") public HashedCredentialsMatcher hashedCredentialsMatcher() {
HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher(); //指定加密方式为MD5 credentialsMatcher.setHashAlgorithmName("MD5"); //加密次数 credentialsMatcher.setHashIterations(1); credentialsMatcher.setStoredCredentialsHexEncoded(true); return credentialsMatcher; }}

4.2.Swagger2Config(接口文档)

//标注当前工程是一个配置类@Configuration//开启swagger的配置@EnableSwagger2public class Swagger2Config {
//将该Docket交给了spring中的ioc @Bean public Docket api() {
return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() // swagger进行包扫描,扫描你当前的controller层路径 .apis(RequestHandlerSelectors.basePackage("com.wo.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() {
return new ApiInfoBuilder() .title("java-swagger") .description("swagger接入教程,简单好用") //服务条款网址 .version("1.0") .build(); }}

5.controller

5.1PermissionExcepitonController

//控制器增强  异常捕获类@ControllerAdvicepublic class PermissionExcepitonController {
//告诉控制器 捕捉什么类型的异常 以及对异常进行处理 @ExceptionHandler(value = AuthorizationException.class) public String excepiton(){
return "unauth"; } @ExceptionHandler(value = ArithmeticException.class) public String urithmeticException(){
return "error"; }}

5.2PersonController

@Controllerpublic class PersonController {
@Autowired PersonService personService; @RequestMapping("/tologin") public String tologin(){
return "login"; } @RequestMapping("/login") public String login(TbSysUser tbSysUser){
Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(tbSysUser.getLoginName(), tbSysUser.getPassword()); try {
subject.login(token); }catch (IncorrectCredentialsException ini){
System.out.println(ini.getMessage()); } if (subject.isAuthenticated()){
return "redirect:findAll"; }else{
return "login"; } } @RequestMapping("/logout") public String logout(){
Subject subject = SecurityUtils.getSubject(); subject.logout(); return "login"; } @RequiresPermissions(value = {
"user_findAll"}) @RequestMapping("/findAll") public ModelAndView findAll(){
List
list = personService.findAll(); ModelAndView modelAndView=new ModelAndView(); modelAndView.addObject("list",list); modelAndView.setViewName("index"); return modelAndView; } @RequiresPermissions(value = {
"user_update"}) @RequestMapping("/findById") public ModelAndView findById(@RequestParam ("id")int id){
Person person = personService.findById(id); ModelAndView modelAndView=new ModelAndView(); modelAndView.addObject("person",person); modelAndView.setViewName("update"); return modelAndView; } @RequiresPermissions(value = {
"user_delete"}) @RequestMapping("/deleteById") public String deleteById(@RequestParam ("id")int id){
personService.deleteById(id); return "redirect:/findAll"; } @RequiresPermissions(value = {
"user_update"}) @RequestMapping("/update") public String update(Person person){
personService.update(person); return "redirect:/findAll"; } @RequiresPermissions(value = {
"user_update"}) @RequestMapping("/goUpadatePage") public ModelAndView goUpadatePage(){
Person person=new Person(); ModelAndView modelAndView=new ModelAndView(); modelAndView.addObject("person",person); modelAndView.setViewName("update"); return modelAndView; } @RequestMapping("/unauth") public String unauth(){
return "unauth"; }}

6.dao和mapper

6.1 PersonDao

public interface PersonDao  extends JpaRepository
{
}

6.2 TbSysPermissionDao

@Mapperpublic interface TbSysPermissionDao {
List
findPermissonByLoginName(@Param("loginName") String loginName);}

6.3 TbUserDao

@Mapperpublic interface TbUserDao {
TbSysUser login(@Param("loginName") String loginName);}

6.4 TbPermissionMapper.xml

6.5 TbUserMapper.xml

7.pojo

7.1 Person

@Data@Entity@Table(name = "tb_person")public class Person {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private int age; private int is_marry; private String user_name; private int sex; private String address; @DateTimeFormat(pattern = "yyyy-MM-ss") private Date birthday;}

7.2 TbSysPermissions

@Datapublic class TbSysPermissions {
private Integer permissionId; private String perName;}

7.3 TbSysUser

@Datapublic class TbSysUser {
private Integer userid; private String loginName; private String password;}

8.service

8.1 PersonService

public interface PersonService {
public List
findAll(); public Person findById(int id); public void deleteById(int id); public void update(Person person);}

8.2 PersonServiceImpl

@Servicepublic class PersonServiceImpl implements PersonService {
@Autowired PersonDao personDao; @Override public List
findAll() {
return personDao.findAll(); } @Override public Person findById(int id) {
Optional
byId = personDao.findById(id); if(byId.isPresent()){
Person person=byId.get(); return person; } return null; } @Override public void deleteById(int id) {
personDao.deleteById(id); } @Override public void update(Person person) {
personDao.saveAndFlush(person); }}

9. shiro

MyRealm

@Componentpublic class MyRealm extends AuthorizingRealm {
@Autowired TbUserDao tbUserDao; @Autowired TbSysPermissionDao tbSysPermissionDao; @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//获取到前端传输用户名 String username = (String) principalCollection.getPrimaryPrincipal(); //使用用户名查询该用户的权限 List
permissonByLoginName = tbSysPermissionDao.findPermissonByLoginName(username); //声明set进行去重 HashSet
set=new HashSet<>(); for (TbSysPermissions tb:permissonByLoginName) {
set.add(tb.getPerName()); } SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(); simpleAuthorizationInfo.setStringPermissions(set); return simpleAuthorizationInfo; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//获得到用户名 String username = (String) authenticationToken.getPrincipal(); //使用用户名查询密码 TbSysUser user = tbUserDao.login(username); //不使用加盐加密 SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username, user.getPassword(), getName()); //使用加盐加密 //SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username, user.getPassword(),ByteSource.Util.bytes("wang"), getName()); return simpleAuthenticationInfo; }}

10.SpringbootWangApplication

@SpringBootApplicationpublic class SpringbootWangApplication {
// public static void main(String[] args) {
SpringApplication.run(SpringbootWangApplication.class, args); }}

11.templates

11.1 error.html

    
Title

您当前的操作有误,请稍后再试

11.2 index.html

    
Title

=========王沁狄==========

接口页面-----退出登录

新增
序号 ID 姓名 年龄 性别 生日 婚姻 地址 操作
已婚 未婚 删除 修改

11.3 login.html

    
Title
用户名:
密码:

11.4 unauth.html

    
Title

您没有权限,请联系管理员

11.5 update.html

    
Title
姓名:
年龄:
性别:
生日:
婚姻:
地址:

转载地址:http://pcezi.baihongyu.com/

你可能感兴趣的文章
Source Insight的对齐问题
查看>>
ubuntu设置开机默认进入字符界面方法
查看>>
chrome 快捷键
查看>>
Linux下buffer和cache的区别
查看>>
程序员不应该再犯的五大编程错误
查看>>
[转载][转帖]Hibernate与Sleep的区别
查看>>
Linux系统的默认编码设置
查看>>
Linux系统调用
查看>>
Linux 信号signal处理机制
查看>>
Linux 信号signal处理函数
查看>>
perror简介
查看>>
linux的system () 函数详解
查看>>
在shell脚本的第一行中,必须写#!/bin/bash
查看>>
一句话##错误 'ASP 0116' 丢失脚本关闭分隔符
查看>>
文件上传漏洞之.htaccess
查看>>
常见网络安全设备默认口令
查看>>
VirtualBox虚拟机网络配置
查看>>
oracle vm virtualbox虚拟机下,CentOS7系统网络配置
查看>>
解决Linux CentOS中cp -f 复制强制覆盖的命令无效的方法
查看>>
wdcpv3升级到v3.2后,多PHP版本共存的安装方法
查看>>