SpringSecurity 笔记
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
配置
com/binx/security/config/ApplicationConfig.java
查看代码
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
public class ApplicationConfig {
@Bean
PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
}
com/binx/security/config/SecurityConfig.java
查看代码
package com.binx.security.config;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import javax.sql.DataSource;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private DataSource dataSource;
@Bean
public PersistentTokenRepository persistentTokenRepository(){
JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
jdbcTokenRepository.setDataSource(dataSource);
return jdbcTokenRepository;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.logout().logoutUrl("/logout").logoutSuccessUrl("/site/hello").permitAll();
http.exceptionHandling().accessDeniedPage("/403.html");
http.formLogin().loginPage("/login.html")// 登录页面
.loginProcessingUrl("/login.do")//登录请求页面
.defaultSuccessUrl("/site/index").permitAll()//登录后跳转页面
.and().authorizeRequests()//权限控制
.antMatchers("/","/site/hello","/user/pre").permitAll()//不需要登录的页面
// .antMatchers("/site/auth").hasAuthority("admin")//拥有对应的角色才可以访问
// .antMatchers("site/auth").hasAnyAuthority("admin","user")
// .antMatchers("/site/auth").hasRole("admin")
.anyRequest().authenticated()//其他页面登录后即可访问
.and().rememberMe().tokenRepository(persistentTokenRepository())
.tokenValiditySeconds(60)
.userDetailsService(userDetailsService)
.and().csrf().disable();//关闭csrf
}
}
Controller
com/binx/security/controller/SiteController.java
查看代码
package com.binx.security.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("site")
public class SiteController {
@Autowired
private PasswordEncoder passwordEncoder;
@GetMapping("index")
public String index(){
return passwordEncoder.encode("123456");
}
@GetMapping("hello")
public String hello(){
return "hello";
}
@GetMapping("auth")
// @Secured("ROLE_admin")
@PreAuthorize("hasAuthority('admin')")
public String auth(){
return "auth";
}
}
com/binx/security/controller/UserController.java
查看代码
package com.binx.security.controller;
import com.binx.security.entity.User;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("user")
public class UserController {
@GetMapping("list")
@PostFilter("filterObject.username=='XuBin'")
public List<User> getAll() {
ArrayList<User> list = new ArrayList<>();
list.add(new User(1L, "XuBin", "666666"));
list.add(new User(2L, "Sxy", "123456"));
System.out.println(list);
return list;//返回结果经过过滤
}
@PostMapping("pre")
@PreFilter("filterObject.id%2==0")
public List<User> getTestPreFilter(@RequestBody List<User> list) {
System.out.println(list);//方法内的参数已经经过了过滤
return list;
}
}
实体类
查看代码
package com.binx.security.controller;
import com.binx.security.entity.User;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("user")
public class UserController {
@GetMapping("list")
@PostFilter("filterObject.username=='Jack'")
public List<User> getAll() {
ArrayList<User> list = new ArrayList<>();
list.add(new User(1L, "Jack", "666666"));
list.add(new User(2L, "Rose", "123456"));
System.out.println(list);
return list;//返回结果经过过滤
}
@PostMapping("pre")
@PreFilter("filterObject.id%2==0")
public List<User> getTestPreFilter(@RequestBody List<User> list) {
System.out.println(list);//方法内的参数已经经过了过滤
return list;
}
}
UserDetailsService
com/binx/security/service/SystemUserService.java
查看代码
package com.binx.security.service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.binx.security.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import com.binx.security.entity.User;
@Service
public class SystemUserService implements org.springframework.security.core.userdetails.UserDetailsService {
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
QueryWrapper<User> wrapper=new QueryWrapper<>();
wrapper.eq("username",username);
User user = userMapper.selectOne(wrapper);
if(user == null){
throw new UsernameNotFoundException("用户不存在");
}
return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),
AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_admin,admin"));
}
}
本文来自博客园,作者:Bin_x,转载请注明原文链接:https://www.cnblogs.com/Bin-x/p/15734579.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)