本文共 14212 字,大约阅读时间需要 47 分钟。
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
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
@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; }}
//标注当前工程是一个配置类@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(); }}
//控制器增强 异常捕获类@ControllerAdvicepublic class PermissionExcepitonController { //告诉控制器 捕捉什么类型的异常 以及对异常进行处理 @ExceptionHandler(value = AuthorizationException.class) public String excepiton(){ return "unauth"; } @ExceptionHandler(value = ArithmeticException.class) public String urithmeticException(){ return "error"; }}
@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(){ Listlist = 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"; }}
public interface PersonDao extends JpaRepository{ }
@Mapperpublic interface TbSysPermissionDao { ListfindPermissonByLoginName(@Param("loginName") String loginName);}
@Mapperpublic interface TbUserDao { TbSysUser login(@Param("loginName") String loginName);}
@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;}
@Datapublic class TbSysPermissions { private Integer permissionId; private String perName;}
@Datapublic class TbSysUser { private Integer userid; private String loginName; private String password;}
public interface PersonService { public ListfindAll(); public Person findById(int id); public void deleteById(int id); public void update(Person person);}
@Servicepublic class PersonServiceImpl implements PersonService { @Autowired PersonDao personDao; @Override public ListfindAll() { 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); }}
MyRealm
@Componentpublic class MyRealm extends AuthorizingRealm { @Autowired TbUserDao tbUserDao; @Autowired TbSysPermissionDao tbSysPermissionDao; @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { //获取到前端传输用户名 String username = (String) principalCollection.getPrimaryPrincipal(); //使用用户名查询该用户的权限 ListpermissonByLoginName = 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; }}
@SpringBootApplicationpublic class SpringbootWangApplication { // public static void main(String[] args) { SpringApplication.run(SpringbootWangApplication.class, args); }}
Title 您当前的操作有误,请稍后再试
Title =========王沁狄==========
接口页面-----退出登录
新增
序号 ID 姓名 年龄 性别 生日 婚姻 地址 操作 男 女 已婚 未婚 删除 修改
Title
Title 您没有权限,请联系管理员
Title
转载地址:http://pcezi.baihongyu.com/