当前位置:网站首页>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";
}
边栏推荐
- FPGA - 7系列 FPGA内部结构之Clocking -02- 时钟布线资源
- Thesis learning record essay multi label lift
- Code shoe set - mt3114 · interesting balance - explain it with examples
- Brief description of activation function
- excel初级应用案例——杜邦分析仪
- Crossing sect · paipan + Siyuan notes = private notebook
- 表格中el-tooltip 实现换行展示
- excel高级绘图技巧100讲(一)-用甘特图来展示项目进度情况
- 【考研高数 武忠祥+880版 自用】高数第二章基础阶段思维导图
- First defined here occurs during QT compilation. Causes and Solutions
猜你喜欢

Through cooperation with the University of international trade, we can increase efficiency for college students

数据库问题,如何优化Oracle SQL查询语句更快,效率更高

Multi label lsml for essay learning records

3D printer threading: five simple solutions

Fixed height of the first column in El table dynamic header rendering

2022 年面向初学者的 10 大免费 3D 建模软件

Essay learning record essay multi label Global

Call us special providers of personal cloud services for College Students

3D打印机穿线:5种简单的解决方案

It's not that you have a bad mind, but that you haven't found the right tool
随机推荐
Qt编写自定义控件-自绘电池
MySQL数据迁移遇到的一些错误
2022 the 8th China International "Internet +" college student innovation and entrepreneurship competition industry proposition track is open for registration!
穿越派·派盘 + Mountain Duck = 数据本地管理
TIDB数据库特性总结
【考研高数 自用】高数第一章基础阶段思维导图
论文学习记录随笔 多标签之LSML
SystemVerilog学习-07-类的继承和包的使用
SQL必会题之留存率
Primary application case of Excel DuPont analyzer
我从技术到产品经理的几点体会
C语言初阶——实现扫雷游戏
Oracle create user + Role
bat操作ftp上传下载命令
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“
Advanced drawing skills of Excel lecture 100 (1) - use Gantt chart to show the progress of the project
3D printer threading: five simple solutions
码蹄集 - MT3114 · 有趣的平衡 - 用样例通俗地讲解
OneFlow源码解析:算子签名的自动推断
OpenGL ES: (5) OpenGL的基本概念、OpenGL ES 在屏幕产生图片的过程、OpenGL管线(pipeline)