当前位置:网站首页>srpingboot security demo
srpingboot security demo
2022-07-01 05:57:00 【Meta39】
pom.xml
<!--security-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Based on the configuration file yaml Certification of ( Don't suggest )
spring:
# Profile based authentication ( Don't suggest )
security:
user:
name: test
password: test
Configuration class based authentication ( Don't suggest )
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.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/** * Realize authentication through configuration class ( Don't suggest ) */
@Configuration
public class MyWebSecurity extends WebSecurityConfigurerAdapter {
// Configure the user name and password in the method , Data logged in as a user
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
auth.inMemoryAuthentication().withUser("lucy").password(bCryptPasswordEncoder.encode("123")).roles();
}
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
Custom authentication class ( Suggest )
notes MyWebSecurity
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.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import javax.annotation.Resource;
import javax.sql.DataSource;
/** * Custom implementation authentication ( Suggest ) */
@Configuration
public class MyWebSecurity2 extends WebSecurityConfigurerAdapter {
@Resource
private UserDetailsService userDetailsService;
// Inject data source
@Resource
private DataSource dataSource;
@Bean
public PersistentTokenRepository persistentTokenRepository(){
JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
jdbcTokenRepository.setDataSource(dataSource);
// jdbcTokenRepository.setCreateTableOnStartup(true);
return jdbcTokenRepository;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// Log out
// http.logout().logoutUrl("/logout").logoutSuccessUrl("/login").permitAll();
// Sign in
http.formLogin()
// .loginPage("/login.html") // Login page setup
// .loginProcessingUrl("/user/login")// Login access path
// .defaultSuccessUrl("/hello").permitAll()// The path to jump after successful login
.and()
.authorizeRequests()
.antMatchers("/", "/user/login").permitAll()// Visit the white list
// 1. hasAuthority Method
// .antMatchers("/admin").hasAuthority("admin")// have admin Permission to access this path
// 2. hasAnyAuthority Method
// .antMatchers("/admin").hasAnyAuthority("admin,manager")
// 3. hasRole Method
// .antMatchers("/admin").hasRole("admin")// When configuring roles, add ROLE_ Such as ROLE_admin
// 4. hasAnyRole Method
.antMatchers("/admin").hasAnyRole("admin,test")
.anyRequest().authenticated()
// automatic logon
.and()
.rememberMe().tokenRepository(persistentTokenRepository())
.tokenValiditySeconds(60)//token Expiration time seconds
.userDetailsService(userDetailsService)
.and()
.csrf().disable();// close csrf Cross Site Request Forgery Attack interception
}
}
RedisConfig
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
/** * Prevent data from being stored in redis The statement */
@Bean(name="redisTemplate")
public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
// Set serialization
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);// Has expired
om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance , ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
jackson2JsonRedisSerializer.setObjectMapper(om);
// To configure redisTemplate
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(lettuceConnectionFactory);
RedisSerializer<?> stringSerializer = new StringRedisSerializer();
// key serialize
redisTemplate.setKeySerializer(stringSerializer);
// value serialize , Serializable objects
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
// Hash key serialize
redisTemplate.setHashKeySerializer(stringSerializer);
// Hash value serialize , Serializable objects
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
Users Entity class
import lombok.Data;
@Data
public class Users {
private Integer id;
private String username;
private String password;
}
UsersMapper
import com.fu.springsecuritydemo.entity.Users;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/** * use redis Simulation query database */
@Component
public class UsersMapper {
@Resource
private RedisTemplate redisTemplate;
public void insert(Users users){
redisTemplate.opsForValue().set(users.getId(),users);
}
public Users select(String username){
return (Users) redisTemplate.opsForValue().get(username);
}
public void delete(Integer userId){
redisTemplate.delete(userId);
}
}
MyUserDetailsService
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 org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
@Resource
private UsersMapper usersMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// call usersMapper Query database according to user name
Users users = usersMapper.select(username);
// Judge
if (users == null){
// The database doesn't have a user name , Authentication failed
throw new UsernameNotFoundException(" The username does not exist !");
}
List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("admin,ROLE_admin");//admin It's authority ,ROLE_admin It's the role
// Return from query database users object , Get the user name and password , return
return new User(users.getUsername(),new BCryptPasswordEncoder().encode(users.getPassword()),auths);
}
}
TestController
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
public class TestController {
@Resource
private RedisTemplate<String,Object> redisTemplate;
@GetMapping("hello")
public String hello(){
if (!redisTemplate.hasKey("lucy")){
Users users = new Users();
users.setId(1);
users.setUsername("lucy");
users.setPassword("123");
redisTemplate.opsForValue().set(users.getUsername(),users);
}
return "hello";
}
}
Authorization by annotation ( Suggest )
Start class plus @EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true) annotation
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
@SpringBootApplication
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
public class SpringSecurityDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringSecurityDemoApplication.class, args);
}
}
TestController
@GetMapping("hello2")
@Secured({
"ROLE_admin"})// If you need multiple roles to access, configure with English commas, such as ROLE_admin,ROLE_test
public String hello2(){
return "hello2";
}
边栏推荐
- Qt编写自定义控件-自绘电池
- FPGA - 7系列 FPGA内部结构之Clocking -01- 时钟架构概述
- OpenGL es: (3) EGL, basic steps of EGL drawing, eglsurface, anativewindow
- MinIO纠错码、分布式MinIO集群搭建及启动
- Bat operation FTP upload and download command
- Advanced drawing skills of Excel lecture 100 (1) - use Gantt chart to show the progress of the project
- Geoffrey Hinton: my 50 years of in-depth study and Research on mental skills
- POL8901 LVDS转MIPI DSI 支持旋转图像处理芯片
- 论文学习记录随笔 多标签之GLOCAL
- Codeforces Round #803 (Div. 2)vp
猜你喜欢

Preliminary level of C language -- selected good questions on niuke.com

Advanced drawing skills of Excel lecture 100 (1) - use Gantt chart to show the progress of the project

Build 2022 上开发者最应关注的七大方向主要技术更新

Know the future of "edge computing" from the Nobel prize!

Leetcode Max rectangle, Max square series 84 85. 221. 1277. 1725. (monotonic stack, dynamic programming)

Qt编写自定义控件-自绘电池

论文学习记录随笔 多标签之GLOCAL

HCM 初学 ( 四 ) - 时间

健康照明中应用的LED照明灯

穿越派 你的数据云行
随机推荐
In win10 and win11, the scroll direction of Elan touch panel is reversed, and "double finger click to open the right-click menu" and "double finger scroll" are started“
CJC8988带2个立体声耳机驱动器的低功率立体声编解码器
论文学习记录随笔 多标签之LIFT
SystemVerilog学习-10-验证量化和覆盖率
FPGA - 7系列 FPGA内部结构之Clocking -02- 时钟布线资源
Geoffrey Hinton:我的五十年深度学习生涯与研究心法
2022 the 8th China International "Internet +" college student innovation and entrepreneurship competition industry proposition track is open for registration!
为了保护自己的数据,他奋斗了一天一夜
srpingboot security demo
Qt编写自定义控件-自绘电池
Preliminary level of C language -- selected good questions on niuke.com
Continuous breakthrough and steady progress -- Review and Prospect of cross platform development technology of mobile terminal
Some errors encountered in MySQL data migration
如何添加葫芦儿派盘
π盘,让您电脑变成个人的私有云
Fragment upload and breakpoint resume
skywalking集成nacos动态配置
Geoffrey Hinton: my 50 years of in-depth study and Research on mental skills
OpenGL es: (1) origin of OpenGL es (transfer)
PLA不粘貼在床上:6個簡單的解决方案