当前位置: 首页 > news >正文

Security

初始化security

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId><version>2.5.15</version></dependency>
可以理解为db的用户信息
  • db的密码 放在父类
  • db的用户名 放在父类
@ToString
public class MyUser implements UserDetails {private String username;private String password;private Set<String> permissions;public MyUser(String username, String password, Set<String> permissions) {this.username = username;this.password = password;this.permissions = permissions;}@Overridepublic Collection<? extends GrantedAuthority> getAuthorities() {return null;}@Overridepublic String getPassword() {return this.password;}@Overridepublic String getUsername() {return this.username;}@Overridepublic boolean isAccountNonExpired() {return true;}@Overridepublic boolean isAccountNonLocked() {return true;}@Overridepublic boolean isCredentialsNonExpired() {return true;}@Overridepublic boolean isEnabled() {return true;}
}
用户信息
  • 这里的用户信息 放的是数据库存储的 dbPasword转化了一下
import com.google.common.collect.Sets;
import com.gouying.domain.MyUser;
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.stereotype.Service;@Service
public class MyUserDetailsService implements UserDetailsService {@Overridepublic UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {System.out.println("dao 查询用户");// 校验用户System.out.println("校验用户 是否存在  是否删除 是否合法");//String username, String password, Collection<? extends GrantedAuthority> authoritiesString password = "admin";String dbPasword = new BCryptPasswordEncoder().encode(password);UserDetails userDetails = new MyUser(userName,dbPasword, Sets.newHashSet("ROLE_USER"));return userDetails;}
}
security配置类
  • 除了登录 其他都拦截
@EnableWebSecurity(debug = true)
@Configuration
public class SecurityConfig {@Autowiredprivate MyUserDetailsService myUserDetailsService;@Beanpublic AuthenticationManager authenticationManager() {DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();daoAuthenticationProvider.setUserDetailsService(myUserDetailsService);daoAuthenticationProvider.setPasswordEncoder(bCryptPasswordEncoder());return new ProviderManager(Lists.newArrayList(daoAuthenticationProvider));}@Beanpublic PasswordEncoder bCryptPasswordEncoder() {return new BCryptPasswordEncoder();}@Beanprotected SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {return httpSecurity.authorizeRequests(authorize -> authorize.antMatchers("/login").permitAll()
//                        .antMatchers(HttpMethod.GET, "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**").permitAll().anyRequest().authenticated())// 默认用security的登录页.formLogin(Customizer.withDefaults()).build();}}
Controller

import com.gouying.domain.MyUser;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;import javax.annotation.Resource;@RestController
public class LoginController {@Resourceprivate AuthenticationManager authenticationManager;@PostMapping("/login")public String login(@RequestBody MyUser user){try{UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());Authentication authentication = authenticationManager.authenticate(authenticationToken);Object credentials = authentication.getCredentials();System.out.println(credentials.toString());MyUser user1 = (MyUser) authentication.getPrincipal();System.out.println(user1.toString());}catch (Exception e){e.printStackTrace();}return "success";}
}
http://www.xdnf.cn/news/716545.html

相关文章:

  • Coze Space的分享体验:基于Y模型分析法的深入剖析
  • 交通违法拍照数据集,可识别接打电话,不系安全带的行为,支持YOLO,COCO JSON,VOC XML格式的标注数据集 最高正确识别率可达88.6%
  • window安装nginx
  • PostgreSQL查询一个表的数据
  • AI预测3D新模型百十个定位预测+胆码预测+去和尾2025年5月29日第92弹
  • N2语法 逆接
  • Python应用while嵌套循环
  • 嵌入式学习笔记 - freeRTOS 阻塞延时的实现机制,同时避免在中断中扫描停留
  • 2025音频传输模块全球选购指南:高品质音频体验的品牌之选
  • 民锋视角下的资产配置策略优化与风险评估模型探索
  • 华为OD机试真题——字母组合过滤组合字符串(2025A卷:100分)Java/python/JavaScript/C/C++/GO最佳实现
  • LangChain【2】之专业术语
  • DTO、VO、DO、BO、PO 的概念与核心区别
  • Swagger 访问不到 报错:o.s.web.servlet.PageNotFound : No mapping for GET /doc.html
  • leetcode hot100刷题日记——28.环形链表2
  • 【论文精读】2024 ECCV--MGLD-VSR现实世界视频超分辨率(RealWorld VSR)
  • 第十三章:预处理
  • Dify+MCP+MySQL:智能问数本地实践
  • 品优购项目(HTML\CSS)
  • 缓存架构方案:Caffeine + Redis 双层缓存架构深度解析
  • 2025年05月29日Github流行趋势
  • 【SOLUTION】Java 生成 TOTP 验证码
  • 政策与数字双赋能驱动:ERP助力外贸企业高质量发展路径解析
  • Maven-生命周期
  • 信创采购热潮下的隐忧:单一技术路线的市场垄断之困
  • Oracle RMAN自动恢复测试脚本
  • mongodb的安装使用
  • 20250529-C#知识:分部类和分部方法
  • 小白畅通Linux之旅-----Linux日志管理
  • 【芯片设计中的交通网络革命:Crossbar与NoC架构的博弈C架构的博弈】