Spring Security的入门案例!!!

      一、导入依赖

<dependencies><!--web--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--security--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency></dependencies>

二、创建启动类:

/** Copyright (c) 2020, 2024,  All rights reserved.**/
package com.by;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;/*** <p>Project: ican_parent - SpringSecurityApplication</p>* <p>Powered by scl On 2024-01-29 10:44:12</p>* <p>描述:<p>** @author 孙臣龙 [1846080280@qq.com]* @version 1.0* @since 17*/
@SpringBootApplication
//Map<"springSecurityFilterChain",FilterChainProxy> -----> FilterChainProxy ----->doFilterInternal()方法
@EnableWebSecurity //启动security
public class SpringSecurityApplication {public static void main(String[] args) {ConfigurableApplicationContext applicationContext = SpringApplication.run(SpringSecurityApplication.class, args);Object bean = applicationContext.getBean("springSecurityFilterChain");System.out.println("-----------------:"+bean.getClass());}
}

三、编写配置类

/** Copyright (c) 2020, 2024,  All rights reserved.**/
package com.by.config;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;/*** <p>Project: ican_parent - SecurityConfig</p>* <p>Powered by scl On 2024-01-29 11:36:09</p>* <p>描述:<p>** @author 孙臣龙 [1846080280@qq.com]* @version 1.0* @since 17*/
@Component
@EnableGlobalMethodSecurity(prePostEnabled = true) //开启权限注解支持
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate PasswordEncoder passwordEncoder;@Autowiredprivate UserDetailsService userDetailsService;@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);}/*** 配置要放开的页面和配置静态资源** @param web* @throws Exception*/@Overridepublic void configure(WebSecurity web) throws Exception {//web.ignoring().antMatchers("/pages/a.html");//web.ignoring().antMatchers("/pages/**");web.ignoring().antMatchers("/login.html");}@Overrideprotected void configure(HttpSecurity http) throws Exception {//super.configure(http);//关闭跨站请求http.csrf().disable();//认证http.formLogin().loginPage("/login.html") //登录页面.loginProcessingUrl("/login") //表单的请求路径.usernameParameter("username").passwordParameter("password").defaultSuccessUrl("/pages/index.html", true);//登录成功后跳转的页面//授权http.authorizeRequests()//.antMatchers("/pages/a.html").hasAuthority("aaa")//.antMatchers("/pages/b.html").hasAuthority("bbb")//.antMatchers("/pages/c.html").hasRole("CCC") //角色标识符不能用ROLE_开头.anyRequest().authenticated();//登录成后,放开权限能够访问其它页面//退出登录http.logout().logoutUrl("/logout").logoutSuccessUrl("/login.html").invalidateHttpSession(true);}/*** 加密方法,使用直接注入** @return*/@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}
}

四、UserServiceImpl

/** Copyright (c) 2020, 2024,  All rights reserved.**/
package com.by.service;import com.by.pojo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;/*** <p>Project: ican_parent - UserServiceImpl</p>* <p>Powered by scl On 2024-01-29 16:37:34</p>* <p>描述:<p>** @author 孙臣龙 [1846080280@qq.com]* @version 1.0* @since 17*/
@Component
public class UserServiceImpl implements UserDetailsService {@Autowiredprivate PasswordEncoder passwordEncoder;private Map<String, UserInfo> mysql = new HashMap<>();public void initMysql() {mysql.put("admin", new UserInfo("admin", passwordEncoder.encode("111")));mysql.put("test", new UserInfo("test", passwordEncoder.encode("111")));}@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {//初始化数据(类似与数据库)initMysql();//根据前端传过来的参数去数据库中查询UserInfo userInfo = mysql.get(username);if (userInfo == null) {return null;}String password = userInfo.getPassword();//密码为明文//模拟从数据库查询权限List<GrantedAuthority> list = new ArrayList<>();//通过用户名配置权限if (username.equals("admin")) {list.add(new SimpleGrantedAuthority("aaa"));list.add(new SimpleGrantedAuthority("bbb"));} else {list.add(new SimpleGrantedAuthority("ROLE_CCC"));}//为什么不对比密码?程序员只需提供数据,对比密码归security管return new User(username, password, list);}}

五、使用注解配置权限

/** Copyright (c) 2020, 2024,  All rights reserved.**/
package com.by.controller;import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.Collection;/*** <p>Project: ican_parent - HelloController</p>* <p>Powered by scl On 2024-01-29 19:50:41</p>* <p>描述:<p>** @author 孙臣龙 [1846080280@qq.com]* @version 1.0* @since 17*/
@RestController
public class HelloController {@RequestMapping("/aaa")@PreAuthorize("hasAuthority('aaa')")public String aaa() {return "aaa";}@RequestMapping("/bbb")@PreAuthorize("hasAuthority('bbb')")public String bbb() {return "bbb";}@RequestMapping("/ccc")@PreAuthorize("hasRole('CCC')")public String ccc() {return "ccc";}@RequestMapping("/ddd")@PreAuthorize("isAuthenticated()")public String ddd() {return "ddd";}/*** 获取用户名* @param authentication* @return*/@GetMapping("/user")public String getCurrentUser(Authentication authentication) {UserDetails userDetails = (UserDetails) authentication.getPrincipal();String username = userDetails.getUsername();Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();// 这里可以根据需要获取更多的用户信息return "用户名:" + username + ";角色:" + authorities;}}

六、实体类

package com.by.pojo;public class UserInfo {String username;String password;public UserInfo(String username,String password){this.username = username;this.password = password;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}@Overridepublic String toString() {return "UserInfo{" +"username='" + username + '\'' +", password='" + password + '\'' +'}';}
}

七、html页面

a.html、b.html、c.html:

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<h1>a 页面,你瞅啥!!!!</h1>
</body>
</html>

index.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
就这就这就这!!!!<a href="/logout">退出登录</a><br>
<a href="/user">获取用户名</a>
</body>
</html>

login.html:

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>登录页面</title>
</head>
<body>
<h3>自定义登录页面</h3>
<form action="/login" method="post">username:<input type="text" name="username"><br>password:<input type="password" name="password"><br><input type="submit" value="登录">
</form>
</body>
</html>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/654895.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

laravel框架项目对接小程序实战经验回顾

一.对接小程序总结 1.状态转换带来的问题&#xff0c;如下 问题原因&#xff1a;由于status 传参赋值层级较多&#xff0c;导致后续查询是数组但是传参是字符串&#xff0c; 解决方案&#xff1a;互斥的地方赋值为空数组&#xff0c;有状态冲突的地方unset掉不需要的参数 2参…

【数据结构1-1】线性表

线性表是最简单、最基本的一种数据结构&#xff0c;线性表示多个具有相同类型数据“串在一起”&#xff0c;每个元素有前驱&#xff08;前一个元素&#xff09;和后继&#xff08;后一个元素&#xff09;。根据不同的特性&#xff0c;线性表也分为数组&#xff08;vector&#…

代码随想录算法训练营DAY6 | 哈希表(1)

DAY5休息一天&#xff0c;今天重启~ 哈希表理论基础&#xff1a;代码随想录 Java hash实现 &#xff1a;java 哈希表-CSDN博客 一、LeetCode 242 有效的字母异位词 题目链接&#xff1a;242.有效的字母异位词 思路&#xff1a;设置字典 class Solution {public boolean isAnag…

分布式事务:2PC、3PC、TCC、zab协议回顾

2PC&#xff1a;两阶段提交协议。 事务分为提交和执行两个阶段。 阶段一&#xff1a;协调者发送事务的请求到事务的执行方&#xff0c;执行方执行事务并记录undo和redo&#xff0c;但不提交事务。然后返回执行情况。 阶段二&#xff1a;协调者发送提交事务请求到各执行方&…

“语法糖“

在计算机编程中&#xff0c;"语法糖"是指一种编程语言的语法特性或语法结构&#xff0c;它在语法上提供了更简洁、易读、易写的方式来表达某些常见的操作或模式&#xff0c;而不是引入新的功能或概念。语法糖是一种语法上的改进&#xff0c;旨在使代码更加清晰和易于…

shell脚本5 函数 数组

函数 试题1 查看版本 如果想更方便&#xff0c;可以建立一个专门存函数的文件 将func.sh里面的命令都移到func文件夹里面&#xff0c;在脚本里面执行文件夹更方便 输入echo $?反馈的结果都是0&#xff0c;都认为是正确的 无法使用$?去检验是否正确&#xff0c;所以要在后面增…

【Java反序列化】Shiro-550漏洞分析笔记

目录 前言 一、漏洞原理 二、Shiro环境搭建 三、Shiro-550漏洞分析 解密分析 加密分析 四、URLDNS 链 前言 shiro-550反序列化漏洞大约在2016年就被披露了&#xff0c;在上学时期也分析过&#xff0c;最近在学CC链时有用到这个漏洞&#xff0c;重新分析下并做个笔记&…

代码随想录算法训练营第十九天|654 最大二叉树、617 合并二叉树、700 二叉搜索树中的搜索、98 验证二叉搜索树

654 最大二叉树 题目链接&#xff1a;最大二叉树 思路 这道题目是让我们构造最大二叉树并返回根节点。谈及二叉树&#xff0c;首先要确定遍历方式&#xff0c;这道题目一个符合思维的遍历方式是前序遍历(中左右)&#xff0c;先有中间节点&#xff0c;然后递归构造左节点和右…

LocalContainerEntityManagerFactoryBean源码

是 Spring Data JPA 中的一个类&#xff0c;它用于创建 EntityManagerFactory 的实例&#xff0c;获取EntityManager实例 public class LocalContainerEntityManagerFactoryBean extends AbstractEntityManagerFactoryBeanimplements ResourceLoaderAware, LoadTimeWeaverAwar…

Java 集合 04 综合练习-查找用户是否存在

练习、 代码&#xff1a; public class User{private String id;private String username;private int password;public User() {}public User(String id, String username, int password) {this.id id;this.username username;this.password password;}public String getI…

Linux提权:Docker组挂载 Rsync未授权 Sudo-CVE Polkit-CVE

目录 Rsync未授权访问 docker组挂载 Sudo-CVE漏洞 Polkit-CVE漏洞 这里的提权手法是需要有一个普通用户的权限&#xff0c;一般情况下取得的webshell权限可能不够 Rsync未授权访问 Rsync是linux下一款数据备份工具&#xff0c;默认开启873端口 https://vulhub.org/#/envir…

如何制作一个简单的HTML个人网页

在当今的数字化时代&#xff0c;个人网页已经成为展示个人品牌、项目或兴趣爱好的重要平台。对于许多初学者来说&#xff0c;如何制作一个简单而精美的个人网页可能会有些困惑。本文将向您介绍如何制作一个简单的HTML个人网页&#xff0c;帮助您轻松入门网页制作。 一、准备工…

系统架构设计师-21年-论文题目

系统架构设计师-21年-论文题目 更多软考知识请访问 https://ruankao.blog.csdn.net/ 摘要字数在400字以内&#xff0c;可以分条叙述&#xff0c;但不允许有图、表、流程图。 正文字数为2000字至300字&#xff0c;文中可以分条叙述&#xff0c;但不要全部用分条叙述的方式。 …

go-zero 统一返回

1、整体目录结构 2、全局处理主入口 package manageimport ("net/http""github.com/zeromicro/go-zero/rest/httpx" )type Body struct {Code int json:"code"Message string json:"message"Result interface{} jso…

RocketMq源码搭建报错No route info of this topic: TopicTest

原因 因为broker没有注册到namsesrv中&#xff0c;导致无法创建Topic 解决办法 启动Borker时&#xff0c;指定namsesrv地址 over!!!

防御保护常用知识

防火墙的主要职责在于&#xff1a;控制和防护 --- 安全策略 --- 防火墙可以根据安全策略来抓取流量之 后做出对应的动作 防火墙分类主要有四类&#xff1a; 防火墙吞吐量 --- 防火墙同一时间能处理的数据量多少 防火墙的发展主要经过以下阶段&#xff1b; 传统防火墙&#xf…

SpringBoot之JWT登录

JWT JSON Web Token&#xff08;JSON Web令牌&#xff09; 是一个开放标准(rfc7519)&#xff0c;它定义了一种紧凑的、自包含的方式&#xff0c;用于在各方之间以JSON对象安全地传输信息。此信息可以验证和信任&#xff0c;因为它是数字签名的。jwt可以使用秘密〈使用HNAC算法…

Element table组件内容\n换行

漂亮的页面总是让人心旷神怡&#xff0c;层次清晰的页面让用户操作起来也是易于上手及展示。 如下的页面展示就是非常low的&#xff1a;用户根本阅读其中的数据。 在这个页面&#xff0c;根据用户填写过程生成多次填写记录&#xff0c;如果不进行层次性的展示&#xff0c;数据…

【python】积分

scipy.integrate 函数说明quad(func,a,b,args)一重积分 &#xff0c;a,b&#xff1a;x方向的积分区间dblquad(func, a, b, gfun, hfun, args())二重积分&#xff0c;gfun、hfun&#xff1a;y方向的积分区间tplquad(func, a, b, gfun, hfun, qfun, rfun, args())三重积分&#…

多重背包I

多重背包I 有 N 种物品和一个容量是 V 的背包。 第 i 种物品最多有 si 件&#xff0c;每件体积是 vi&#xff0c;价值是 wi。 求解将哪些物品装入背包&#xff0c;可使物品体积总和不超过背包容量&#xff0c;且价值总和最大。 输出最大价值。 输入格式 第一行两个整数&…