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.hqwc.cn/news/438622.html

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

相关文章

幻兽帕鲁服务器出租,腾讯云PK阿里云怎么收费?

幻兽帕鲁服务器价格多少钱&#xff1f;4核16G服务器Palworld官方推荐配置&#xff0c;阿里云4核16G服务器32元1个月、96元3个月&#xff0c;腾讯云换手帕服务器服务器4核16G14M带宽66元一个月、277元3个月&#xff0c;8核32G22M配置115元1个月、345元3个月&#xff0c;16核64G3…

SpringBoot项目接入MQTT协议

mqtt是一种类似于mq的通讯技术 1、mqtt服务端搭建 创建docker网络 docker network create --driver bridge --subnet 172.18.0.0/24 --gateway 172.18.0.1 emqx-net创建容器 docker run -d \--name emqx1 \-e "EMQX_NODE_NAMEemqx172.18.0.2" \--network emqx-ne…

【LeetCode每日一题】56. 合并区间插入区间

一、判断区间是否重叠 力扣 252. 会议室 给定一个会议时间安排的数组 intervals &#xff0c;每个会议时间都会包括开始和结束的时间 intervals[i] [starti, endi] &#xff0c;请你判断一个人是否能够参加这里面的全部会议。 思路分析 因为一个人在同一时刻只能参加一个会…

Zygote的启动流程

在zygote进程对应的文件是app_main.cpp文件&#xff0c;在app_main.cpp文件的main()方法中先解析了init.rc中配置的参数并根据配置的参数设置zygote的状态。 在状态设置阶段主要做了&#xff1a; 设置进程名称为zygote通过startSystemServer true标示启动的是systemServer调…

SpringSecurity笔记

SpringSecurity 本笔记来自三更草堂&#xff1a;https://www.bilibili.com/video/BV1mm4y1X7Hc/?spm_id_from333.337.search-card.all.click&#xff0c;仅供个人学习使用 简介 Spring Security是Spring家族中的一个安全管理框架。相比与另外一个安全框架Shiro&#xff0c;…

消息中间件RabbitMQ介绍

一、基础知识 1. 什么是RabbitMQ RabbitMQ是2007年发布&#xff0c;是一个在AMQP(高级消息队列协议)基础上完成的&#xff0c;简称MQ全称为Message Queue, 消息队列&#xff08;MQ&#xff09;是一种应用程序对应用程序的通信方法&#xff0c;由Erlang&#xff08;专门针对于大…

What is Rust? Why Rust?

why Rust&#xff1f; 目前&#xff0c;Rust 变得越来越流行。然而&#xff0c;仍然有很多人&#xff08;和公司&#xff01;&#xff09;误解了 Rust 的主张价值是什么&#xff0c;甚至误解了它是什么。在本文中&#xff0c;我们将讨论 Rust 是什么以及为什么它是一种可以增强…

基于springboot+vue的医院管理系统(前后端分离)

博主主页&#xff1a;猫头鹰源码 博主简介&#xff1a;Java领域优质创作者、CSDN博客专家、公司架构师、全网粉丝5万、专注Java技术领域和毕业设计项目实战 主要内容&#xff1a;毕业设计(Javaweb项目|小程序等)、简历模板、学习资料、面试题库、技术咨询 文末联系获取 研究背景…

###C语言程序设计-----C语言学习(6)#

前言&#xff1a;感谢老铁的浏览&#xff0c;希望老铁可以一键三连加个关注&#xff0c;您的支持和鼓励是我前进的动力&#xff0c;后续会分享更多学习编程的内容。 一. 主干知识的学习 1. while语句 除了for语句以外&#xff0c;while语句也用于实现循环&#xff0c;而且它…

Kotlin快速入门系列7

Kotlin的数据类、密封类、枚举类 数据类 与Java等语言不同&#xff0c;kotlin创建只包含数据的类时&#xff0c;需要在类名前声明关键字&#xff1a;data。 data class KotlinBean (val brand : String) 在kotlin中&#xff0c;编译器会自动的从主构造函数中根据所有声明的…

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

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

【数据分析】numpy基础第一天

文章目录 前言本文代码&#xff1a;使用jupyter notebook打开本文的代码操作示例步骤1.打开Anaconda Powershell Prompt步骤2.复制代码文件地址步骤3.在Anaconda Powershell Prompt中打开jupyter notebook步骤3.5.解决一个可能的问题步骤4.在浏览器中查看ipynb文件步骤5.运行代…