简介
spring Security 是针对spring项目的安全框架,也是springBoot底层安全模块默认的技术选型,他可以实现强大的web安全控制,我们仅需要引入spring-boot-starter-security模块,进行少量的配置,即可实现强大的安全管理
记住几个类:
- WebSecurityConfigurerAdapter:自定义Security策略
- AuthenticationManagerBuilder: 自定义认证策略
- @EnableWebSecurity: 开启WebSecurity模式
导入security
| <!--导入security--> |
| <dependency> |
| <groupId>org.springframework.boot</groupId> |
| <artifactId>spring-boot-starter-security</artifactId> |
| </dependency> |
controller层
| package com.google.controller; |
| |
| import org.springframework.stereotype.Controller; |
| import org.springframework.web.bind.annotation.CrossOrigin; |
| import org.springframework.web.bind.annotation.PathVariable; |
| import org.springframework.web.bind.annotation.RequestMapping; |
| import org.springframework.web.bind.annotation.ResponseBody; |
| |
| @CrossOrigin(origins = "http://localhost:8081",maxAge = 3600) |
| @Controller |
| public class SecurityController { |
| @RequestMapping("/") |
| public String usertext() { |
| String username = "罗"; |
| return "redirect:http://localhost:8081/"; |
| } |
| @RequestMapping("/{level}/{id}") |
| @ResponseBody |
| public String level(@PathVariable String level , @PathVariable int id) { |
| String username = level+"/"+id+"页面"; |
| return username; |
| } |
| } |
| |
认证
| |
| @Override |
| protected void configure(HttpSecurity http) throws Exception { |
| http.authorizeRequests() |
| |
| .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("root").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2","vip3") |
| .and() |
| .withUser("xiao").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2"); |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?