springSecurity简单直接说明

server/2024/10/19 9:36:17/

引入依赖

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><!-- fastjson依赖 --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.76</version></dependency>

1,编辑实体类 用力存储用户数据

package com.mydemo.springbootdocker.domain;import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;import java.io.Serializable;
import java.util.Date;/*** 用户对象 sys_user** @author deka*/
@Data
public class SysUser implements Serializable {private static final long serialVersionUID = 1L;private String token;/*** 订单类型*/private String orderType;/*** 用户ID*/private Long userId;/*** 部门ID*/private Long deptId;/*** 客户名称*/private String customerName;private String customerUuid;/*** 所属区域*/private String userRegion;/*** 用户账号*/private String userName;/*** 用户昵称*/private String nickName;/*** 用户身份*/private String userIdentity;/*** 用户类别*/private String userType;/*** 用户邮箱*/private String email;/*** 手机号码*/private String phonenumber;/*** 用户性别*/private String sex;/*** 用户头像*/private String avatar;/*** 密码*/private String password;/*** 盐加密*/private String salt;/*** 帐号状态(0正常 1停用)*/private String status;/*** 删除标志(0代表存在 2代表删除)*/private String delFlag;/*** 最后登录IP*/private String loginIp;/*** 最后登录时间*/private Date loginDate;/*** 角色组*/private Long[] roleIds;/*** 岗位组*/private Long[] postIds;/*** 所属客户UUID*/private String[] customerUuids;/*** 所属区域*/private String[] userRegions;/*** 是否工厂人员标志,0:否,1:是*/private String isFactoryWorker;/*** 是否设备授权用户,0:否,1:是*/private String isDeviceAuthUser;/*** 部门名称*/private String deptName;/*** 审批名称*/private String examine;/*** 核准名称*/private String approval;/*** 机构层级*/private Integer organizationLevel;@JsonIgnoreprivate Integer parentOrganizationLevel;private String organizationId;
}

2,编辑 LoginUser 实现 UserDetails

package com.mydemo.springbootdocker.domain;import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;import java.util.Collection;
import java.util.List;/*** @Author wyt* @Date 2024/4/23 上午 10:34* @Version 1.0*/
@Data
public class LoginUser implements UserDetails {public SysUser user;private  List<GrantedAuthority> auth;public LoginUser(SysUser sysUser,List<GrantedAuthority> auth) {this.user = sysUser;this.auth=auth;}@Overridepublic Collection<? extends GrantedAuthority> getAuthorities() {return auth;}@Overridepublic String getPassword() {return user.getPassword();}@Overridepublic String getUsername() {return user.getUserName();}@Overridepublic boolean isAccountNonExpired() {return true;}@Overridepublic boolean isAccountNonLocked() {return true;}@Overridepublic boolean isCredentialsNonExpired() {return true;}@Overridepublic boolean isEnabled() {return true;}
}

3, 创建UserDetailsServiceImpl 类实现 接口UserDetailsService

package com.mydemo.springbootdocker.security;import com.mydemo.springbootdocker.domain.LoginUser;
import com.mydemo.springbootdocker.domain.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
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 java.util.List;/*** @Author wyt* @Date 2024/4/23 上午 10:29* @Version 1.0*/
@Slf4j
@Configuration
public class UserDetailsServiceImpl implements UserDetailsService {@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {log.info("username= {}", username);/*** 实际操作,是根据用户输入的用户名,从数据库中获取用户名,密码 权限相关  然后加入到内存中* 后续操作是 使用数据库中存的加密数据,与用户输入的密码加密比较,看是否一直,如果一致表示认证成功,否则失败** 本示例写死即可*/SysUser sysUser = new SysUser();sysUser.setUserId(Long.valueOf(123));sysUser.setUserName(username);sysUser.setNickName("系统管理员");BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();String encode = passwordEncoder.encode("123456");sysUser.setPassword(encode);//这里的角色信息没有从数据库里查询。实际开发中要从数据库里查询List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("admin");
//        return new User(username,encode,auths);return createLoginUser(sysUser, auths);}public UserDetails createLoginUser(SysUser sysUser, List<GrantedAuthority> auths) {return new LoginUser(sysUser, auths);}
}

4,编辑SecurityWebConfig 类继承 WebSecurityConfigurerAdapter 类

package com.mydemo.springbootdocker.security;import com.mydemo.springbootdocker.security.handler.LoginFailureHandler;
import com.mydemo.springbootdocker.security.handler.LoginSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;/*** @Author wyt* @Date 2024/4/23 下午 1:22* @Version 1.0*/
@Configuration
@EnableWebSecurity
public class SecurityWebConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate UserDetailsService userDetailsService;@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.formLogin()
//                .loginProcessingUrl("/loginDeal").usernameParameter("userName") // 提交表单中的用户名.passwordParameter("password") // 提交表单中的密码字段
//                .successHandler(new LoginSuccessHandler()) // 认证成功处理
//                .failureHandler(new LoginFailureHandler()) // 认证失败.permitAll().and().authorizeRequests().antMatchers("/test/**").permitAll() // 不需要登陆访问.anyRequest().authenticated().and().csrf().disable() // 关闭csrf认证;}}

完成如上工作就可以访问测试了
并且congroller 中/test/… 下面的接口是不需要登陆认证的


http://www.ppmy.cn/server/15934.html

相关文章

浏览器JavaScript兼容解决方案整理

1、addEventListener 与 attachEvent 区别 attachEvent ——兼容&#xff1a;IE7、IE8&#xff1b;不兼容firefox、chrome、IE9、IE10、IE11、safari、opera。 addEventListener——兼容&#xff1a;firefox、chrome、IE、safari、opera&#xff1b;不兼容IE7、IE8 解决方案&…

2024系统架构师---论软件系统架构风格

论软件系统架构风格 系统架构风格(System Architecture Style)是描述某一特定应用领域中系统组织方式的惯用模式架构风格定义了一个词汇表和一组约束&#xff0c;词汇表中包含一些构件和连接件类型&#xff0c;而这组约束指出系统是如何将这些构件和连接件组合起来的口软件系统…

Java | Leetcode Java题解之第44题通配符匹配

题目&#xff1a; 题解&#xff1a; class Solution {public boolean isMatch(String s, String p) {int sRight s.length(), pRight p.length();while (sRight > 0 && pRight > 0 && p.charAt(pRight - 1) ! *) {if (charMatch(s.charAt(sRight - 1)…

Clickhouse离线安装教程

https://blog.51cto.com/u_15060531/4174350 1. 前置 1.1 检查服务器架构 服务器&#xff1a;Centos7.X 需要确保是否x86_64处理器构架、Linux并且支持SSE 4.2指令集 grep -q sse4_2 /proc/cpuinfo && echo "SSE 4.2 supported" || echo "SSE 4.2 …

如何配置nginx的转发?

配置Nginx的转发可以通过修改Nginx的配置文件来实现。以下是配置Nginx转发的基本步骤&#xff1a; 打开Nginx的配置文件&#xff0c;通常位于/etc/nginx/nginx.conf或/usr/local/nginx/conf/nginx.conf。 在http块中添加一个新的server块&#xff0c;用于配置转发目标的基本信…

ABTest如何计算最小样本量-工具篇

如果是比例类指标&#xff0c;有一个可以快速计算最小样本量的工具&#xff1a; https://www.evanmiller.org/ab-testing/sample-size.html 计算样本量有4个要输入的参数&#xff1a;①一类错误概率&#xff0c;②二类错误概率 &#xff08;一般是取固定取值&#xff09;&…

详细分析mysqlslap的基本知识 | 压力测试(附Demo)

目录 前言1. 基本知识2. 参数解读2.1 auto-generate-sql2.2 only-print2.3 iterations2.4 并发处理参数 前言 对数据库进行压力测试&#xff0c;对此补充这方面的详细知识点 1. 基本知识 mysqlslap 是 MySQL 自带的用于模拟数据库负载的压力测试工具 可以模拟多个客户端并发…

docker环境搭建

项目环境搭建 1、安装 Linux 虚拟机 &#xff08;1&#xff09;下载安装&#xff1a; VM VirtualBox 下载安装&#xff1a;Downloads – Oracle VM VirtualBox&#xff0c;要先开启CPU虚拟化 &#xff08;2&#xff09;通过vagrant&#xff0c;在VirtualBox中安装虚拟机 下…