springboot中实现权限认证的两个框架
web开发安全框架
提供认证和授权功能!
一.SpringSecurity
1.导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>2.6.9</version>
</dependency>
2.实现授权和认证功能
package com.springboot.config;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
/**
* @author panglili
* @create 2022-07-10-17:18
*/
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//http Security认证,首页所有人都可以访问,功能页只有相应权限的人才能访问
//授权
http.authorizeHttpRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
//没有权限默认跳登录页面
http.formLogin();
}
@Override
//认证
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("tata").password(new BCryptPasswordEncoder().encode("123123")).roles("vip1","vip2")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123123")).roles("vip1","vip2","vip3")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("123123")).roles("vip1");
}
}
3.超简单的注销功能
前端界面中,注销按钮处,使用thymeleaf点击到后端的security控制类中的logout
<!--注销-->
<a class="item" th:href="@{/logout}">
<i class="sign-out icon"></i> 注销
</a>
security中的logout是spring security自己提供的,只需要用它的参数http.logout()即可。
http.logout()
4.权限控制
此功能展示相应的界面给不同用户,上面实现的功能会展示所有界面,只是不同用户点击不是自己的权限内的页面会无法展示。
导入依赖包,使得可以在thymeleaf中调用security的变量。
<!--security和thymeleaf整合包-->
<!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity4 -->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
在html头文件记得导入,才会有提示!!!
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
实现不同用户的权限功能,只需要在不同前端内容中使用security的语句加以判断即可。
<div class="column" sec:authorize="hasRole('vip3')">
<div class="ui raised segment">
<div class="ui">
<div class="content" >
<h5 class="content">Level 3</h5>
<hr>
<div><a th:href="@{/level3/1}"><i class="bullhorn icon"></i> Level-3-1</a></div>
<div><a th:href="@{/level3/2}"><i class="bullhorn icon"></i> Level-3-2</a></div>
<div><a th:href="@{/level3/3}"><i class="bullhorn icon"></i> Level-3-3</a></div>
</div>
</div>
</div>
</div>
当用户角色为vip3时才展示div下面的内容。
5.记住我功能实现
后端security的参数http调用方法rememberme
http.rememberMe().rememberMeParameter("remember");
前端设置一个选择框,命名为remember
<div class="field">
<input type="checkbox" name="remember"/>记住我
</div>
二.shrio
1.导入jar
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.theborakompanioni/thymeleaf-extras-shiro -->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.3.2</version>
</dependency>
2.写配置功能
subject用户,securityManager管理所有用户,realm连接数据。
三大对象
package com.springboot.config;
import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
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;
/**
* @author panglili
* @create 2022-07-10-21:15
*/
@Configuration
public class ShrioConfig {
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("getDefault") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean Bean = new ShiroFilterFactoryBean();
Bean.setSecurityManager(defaultWebSecurityManager);
//添加shrio内置过滤器
Map<String,String> filterMap=new LinkedHashMap<>();
//只允许带有user:add的用户去访问add页面
filterMap.put("/user/add","perms[user:add]");
filterMap.put("/user/update","perms[user:update]");
Bean.setUnauthorizedUrl("/unauth");
//设置页面认证后才能访问
filterMap.put("/user/*","authc");
Bean.setFilterChainDefinitionMap(filterMap);
//设置登录页面
Bean.setLoginUrl("/toLogin");
return Bean;
}
@Bean(name="getDefault")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm")UserRealm userRealm){
DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
securityManager.setRealm(userRealm);
return securityManager;
}
@Bean(name = "userRealm")
public UserRealm userRealm(){
return new UserRealm();
}
//整合shrio和thymeleaf
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
}
3.realm类实现授权和认证
package com.springboot.config;
import com.springboot.pojo.userDao;
import com.springboot.service.userDaoService;
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;
import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;
/**
* @author panglili
* @create 2022-07-10-21:16
*/
public class UserRealm extends AuthorizingRealm {
@Autowired
userDaoService userDaoService;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("授权功能=====>");
//获取当前登录的对象
Subject subject = SecurityUtils.getSubject();
//通过当前对象取到认证里的userdao
userDao currentUser = (userDao) subject.getPrincipal();
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//设置当前用户权限
info.addStringPermission(currentUser.getPerms());
return info;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("认证功能======>");
UsernamePasswordToken usertoken = (UsernamePasswordToken) authenticationToken;
//获取数据库中的名字
userDao userDao = userDaoService.queryByName(usertoken.getUsername());
if(userDao==null){
return null; //返回null为一个异常,在controller中被捕获,会显示用户名错误。
}
return new SimpleAuthenticationInfo(userDao,usertoken.getPassword(),"");
}
}
4.controller密码认证判断
//登录界面
@RequestMapping("/toLogin")
public String toLogin(){
return "login";
}
//shrio的登录权限认证
@RequestMapping("/login")
public String login(String username,String password,Model md){
System.out.println("进入了login");
System.out.println(username+password);
//获取当前用户
Subject subject = SecurityUtils.getSubject();
//封装用户的登录数据
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
//执行登录方法
try{
subject.login(token);
return "index";
}catch (UnknownAccountException e){
md.addAttribute("msg","用户名错误");
return "login";
}catch (IncorrectCredentialsException e){
md.addAttribute("msg","密码错误");
return "login";
}
}
//没有权限的情况
@RequestMapping("/unauth")
@ResponseBody
public String unauth(){
return "没有权限访问!";
}
//退出登陆
@RequestMapping("/logout")
public String logOut(){
Subject subject = SecurityUtils.getSubject();
subject.logout();
return "login";
}
springboot中实现权限认证的两个框架的更多相关文章
- springboot集成轻量级权限认证框架sa-token
sa-token是什么? sa-token是一个JavaWeb轻量级权限认证框架,主要解决项目中登录认证.权限认证.Session会话等一系列由此衍生的权限相关业务.相比于其他安全性框架较容易上手. ...
- 在springboot中使用Mybatis Generator的两种方式
介绍 Mybatis Generator(MBG)是Mybatis的一个代码生成工具.MBG解决了对数据库操作有最大影响的一些CRUD操作,很大程度上提升开发效率.如果需要联合查询仍然需要手写sql. ...
- Django 中使用权限认证
权限认证 权限概念 """ 在实际开发中,项目中都有后台运营站点,运营站点里面会存在多个管理员, 那么不同的管理员会具备不同的任务和能力,那么要实现这样的管理员功能,那么 ...
- 权限认证与授权(Shrio 框架)
权限概述 认证: 系统提供的用于识别用户身份的功能, 通常登录功能就是认证功能; -- 让系统知道你是谁 授权: 系统授予用户可以访问哪些功能的证书. -- 让系统知道你能做什么! 常见的权限控制方式 ...
- ubuntu 14.04中Elasticsearch 2.3 中 Nginx 权限认证
前言:本文实现了nginx简单保护elasticsearch,类似的保护也可以采用elasticsearch 官方插件shield 一.准备密码 1.确认htpasswd是否已经安装 which ht ...
- Codeigniter-实现权限认证
两种方法 钩子函数 集成核心Controller 方法一,钩子函数: 一直没找到CI的权限认证扩展,以前好像找到过一个老外的扩展,不过不怎么好用,现在记不清了,后来仿着jsp firter的方式用CI ...
- SpringBoot中使用Fastjson/Jackson对JSON序列化格式化输出的若干问题
来源 :https://my.oschina.net/Adven/blog/3036567 使用springboot-web编写rest接口,接口需要返回json数据,目前国内比较常用的fastjso ...
- **[权限控制] 利用CI钩子实现权限认证
http://codeigniter.org.cn/forums/thread-10877-1-1.html 一直没找到CI的权限认证扩展,以前好像找到过一个老外的扩展,不过不怎么好用,现在记不清了, ...
- 【Shiro】Apache Shiro架构之权限认证(Authorization)
Shiro系列文章: [Shiro]Apache Shiro架构之身份认证(Authentication) [Shiro]Apache Shiro架构之集成web [Shiro]Apache Shir ...
随机推荐
- 【Vagrant】启动安装Homestead卡在 SSH auth method: private key
注意:通过查找资料发现,导致这个问题的原因有很多,我的这个情况只能是一个参考. 问题描述 今天在使用虚拟机的时候,由于存放虚拟机的虚拟磁盘(vmdk文件)的逻辑分区容量不足(可用容量为0了).然后在使 ...
- 跨域原因及SpringBoot、Nginx跨域配置
目录 概述 简单请求 跨域解决方案 概述 SpringBoot跨域配置 Nginx跨域配置 概述 MDN文档 Cross-Origin Resource Sharing (CORS) 跨域的英文是Cr ...
- 关于 MyBatis-Plus 分页查询的探讨 → count 都为 0 了,为什么还要查询记录?
开心一刻 记得上初中,中午午休的时候,我和哥们躲在厕所里吸烟 听见外面有人进来,哥们猛吸一口,就把烟甩了 进来的是教导主任,问:你们干嘛呢? 哥们鼻孔里一边冒着白烟一边说:我在生气 环境搭建 依赖引入 ...
- API Schema in kubernetes
目录 什么是schema 数据库中的schema Kubernetes中的schema 通过示例了解schema 什么是schema schema一词起源于希腊语中的form或figure,但具体应该 ...
- 戏说领域驱动设计(廿七)——Saga设计模型
上一节我们讲解了常用的事务,也提及了Saga,这是在分布式环境下被经常使用的一种处理复杂业务和分布式事务的设计模式.本章我们的主要目标是编写一个简单版本的Saga处理器,不同于Seata框架中那种可独 ...
- git指令使用
仓库为空,本地创建git项目之后提交到仓库中1.创建项目文件夹(本地git仓库)2.在项目文件夹中右键:选择Git Bash3.初始化项目:git init -- 会出现一个.git的隐藏文件夹4.将 ...
- Python趣味入门9:函数是你走过的套路,详解函数、调用、参数及返回值
1.概念 琼恩·雪诺当上守夜人的司令后,为训练士兵对付僵尸兵团,把成功斩杀僵尸的一系列动作编排成了"葵花宝典剑法",这就是函数.相似,在计算机世界,一系列前后连续的计算机语句组合在 ...
- CF1580E Railway Construction
CF1580E Railway Construction 铁路系统中有 \(n\) 个车站和 \(m\) 条双向边,有边权,无重边.这些双向边使得任意两个车站互相可达. 你现在要加一些单向边 \((u ...
- 软件构造Lab2实验总结
本次实验训练抽象数据类型(ADT)的设计.规约.测试,并使用面向对象编程(OOP)技术实现ADT.具体来说内容如下: 针对给定的应用问题,从问题描述中识别所需的ADT: 设计ADT规约(pre-con ...
- jenkins 自动化部署vue前端+java后端项目 进阶一
今天又不想写了,那么我来将我参考的文章直接分享给大家好了,大家也可以直接进行参考: 这里以centos7为例搭建自动化部署项目: 1.搭建部署前端服务代理nginx: 借鉴于:https://blog ...