diff --git a/SpringBoot-MyBatis-Advances/pom.xml b/SpringBoot-MyBatis-Advances/pom.xml
index fbd2556..6a46376 100644
--- a/SpringBoot-MyBatis-Advances/pom.xml
+++ b/SpringBoot-MyBatis-Advances/pom.xml
@@ -37,6 +37,20 @@
mysql
mysql-connector-java
+
+ org.apache.maven.doxia
+ doxia-site-renderer
+ 1.11.1
+
+
+ org.springframework.boot
+ spring-boot-starter-cache
+
+
+ org.springframework.boot
+ spring-boot-starter-data-redis
+ 2.3.9.RELEASE
+
@@ -51,6 +65,16 @@
true
+
+ org.apache.maven.plugins
+ maven-site-plugin
+ 3.7.1
+
+
+ org.apache.maven.plugins
+ maven-project-info-reports-plugin
+ 3.0.0
+
diff --git a/SpringBoot-MyBatis-Advances/src/main/java/com/fancv/Application_Mybatis.java b/SpringBoot-MyBatis-Advances/src/main/java/com/fancv/Application_Mybatis.java
index 1b8c859..9c2724b 100644
--- a/SpringBoot-MyBatis-Advances/src/main/java/com/fancv/Application_Mybatis.java
+++ b/SpringBoot-MyBatis-Advances/src/main/java/com/fancv/Application_Mybatis.java
@@ -2,6 +2,7 @@
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.cache.annotation.EnableCaching;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
//TODO
@@ -14,6 +15,7 @@
*/
@SpringBootApplication
@EnableSwagger2
+@EnableCaching
public class Application_Mybatis {
public static void main(String[] args) {
diff --git a/SpringBoot-MyBatis-Advances/src/main/java/com/fancv/config/RedisCacheConfig.java b/SpringBoot-MyBatis-Advances/src/main/java/com/fancv/config/RedisCacheConfig.java
new file mode 100644
index 0000000..0aab800
--- /dev/null
+++ b/SpringBoot-MyBatis-Advances/src/main/java/com/fancv/config/RedisCacheConfig.java
@@ -0,0 +1,127 @@
+package com.fancv.config;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.cache.CacheManager;
+import org.springframework.cache.annotation.EnableCaching;
+import org.springframework.cache.interceptor.KeyGenerator;
+import org.springframework.cache.interceptor.SimpleKeyGenerator;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.data.redis.cache.RedisCacheConfiguration;
+import org.springframework.data.redis.cache.RedisCacheManager;
+import org.springframework.data.redis.connection.RedisConnectionFactory;
+import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
+import org.springframework.data.redis.serializer.RedisSerializationContext;
+import org.springframework.data.redis.serializer.StringRedisSerializer;
+
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+@Configuration
+@EnableCaching
+public class RedisCacheConfig {
+
+ @Value("${cache.default.expire-time:2000}")
+ private int defaultExpireTime;
+ @Value("${cache.user.expire-time:1000}")
+ private int userCacheExpireTime;
+ @Value("${cache.user.name:cache}")
+ private String userCacheName;
+
+ /* *//**
+ * Redis缓存管理器
+ *
+ * @param lettuceConnectionFactory
+ * @return
+ *//*
+ @Bean
+ public CacheManager cacheManager(RedisConnectionFactory lettuceConnectionFactory) {
+ RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig();
+ // 设置缓存管理器管理的缓存的默认过期时间
+ defaultCacheConfig = defaultCacheConfig.entryTtl(Duration.ofSeconds(defaultExpireTime))
+ // 设置 key为string序列化
+ .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
+ // 设置value为json序列化
+ .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
+ // 不缓存空值
+ .disableCachingNullValues();
+
+ Set cacheNames = new HashSet<>();
+ cacheNames.add(userCacheName);
+
+ // 对每个缓存空间应用不同的配置
+ Map configMap = new HashMap<>();
+ configMap.put(userCacheName, defaultCacheConfig.entryTtl(Duration.ofSeconds(userCacheExpireTime)));
+ configMap.put("users", defaultCacheConfig.entryTtl(Duration.ofSeconds(400)));
+
+ RedisCacheManager cacheManager = RedisCacheManager.builder(lettuceConnectionFactory)
+ .cacheDefaults(defaultCacheConfig)
+ .initialCacheNames(cacheNames)
+ .withInitialCacheConfigurations(configMap)
+ .build();
+ return cacheManager;
+ }*/
+
+
+ /* *
+ * 缓存管理器
+ *
+ * @param lettuceConnectionFactory
+ * @return*/
+
+ @Bean
+ public CacheManager cacheManager(RedisConnectionFactory lettuceConnectionFactory) {
+ RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig();
+ // 设置缓存管理器管理的缓存的默认过期时间
+ defaultCacheConfig = defaultCacheConfig.entryTtl(Duration.ofSeconds(defaultExpireTime))
+ // 设置 key为string序列化
+ .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
+ // 设置value为json序列化
+ .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
+ // 不缓存空值
+ .disableCachingNullValues();
+
+ Set cacheNames = new HashSet<>();
+ cacheNames.add(userCacheName);
+
+ // 对每个缓存空间应用不同的配置
+ Map configMap = new HashMap<>();
+ configMap.put(userCacheName, defaultCacheConfig.entryTtl(Duration.ofSeconds(userCacheExpireTime)));
+ configMap.put("users", defaultCacheConfig.entryTtl(Duration.ofSeconds(400)));
+
+ RedisCacheManager cacheManager = RedisCacheManager.builder(lettuceConnectionFactory)
+ .cacheDefaults(defaultCacheConfig)
+ .initialCacheNames(cacheNames)
+ .withInitialCacheConfigurations(configMap)
+ .build();
+ return cacheManager;
+ }
+ /**
+ * 自定义缓存的redis的KeyGenerator【key生成策略】
+ * 注意: 该方法只是声明了key的生成策略,需在@Cacheable注解中通过keyGenerator属性指定具体的key生成策略
+ * 可以根据业务情况,配置多个生成策略
+ * 如: @Cacheable(value = "key", keyGenerator = "cacheKeyGenerator")
+ */
+ @Bean
+ public KeyGenerator keyGenerator() {
+ /**
+ * target: 类
+ * method: 方法
+ * params: 方法参数
+ */
+ return (target, method, params) -> {
+ //获取代理对象的最终目标对象
+ StringBuilder sb = new StringBuilder();
+ sb.append(target.getClass().getSimpleName()).append(":");
+ sb.append(method.getName()).append(":");
+ //调用SimpleKey的key生成器
+ Object key = SimpleKeyGenerator.generateKey(params);
+ return sb.append(key);
+ };
+ }
+
+
+}
diff --git a/SpringBoot-MyBatis-Advances/src/main/java/com/fancv/controller/DemoController.java b/SpringBoot-MyBatis-Advances/src/main/java/com/fancv/controller/DemoController.java
index 1a8122a..bdaf868 100644
--- a/SpringBoot-MyBatis-Advances/src/main/java/com/fancv/controller/DemoController.java
+++ b/SpringBoot-MyBatis-Advances/src/main/java/com/fancv/controller/DemoController.java
@@ -2,7 +2,10 @@
import com.fancv.dao.User;
import com.fancv.mapper.MyUserMapper;
+import com.fancv.service.UserService;
+import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.accept.MappingMediaTypeFileExtensionResolver;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@@ -13,14 +16,22 @@
@RestController
@RequestMapping("mybatis")
+@Api(value = "User")
public class DemoController {
+
@Autowired
MyUserMapper userMapper;
- @GetMapping("insert")
- public String batchInster(){
- User user = userMapper.selectByPrimaryKey(1);
- return user.getName();
+ @Autowired
+ UserService userService;
+
+
+ @GetMapping("user_info")
+ public User getUserInfo(Integer id){
+
+ User user = userService.getUerInfo(id);
+ User user1 = userService.getUerInfoWithoutKey();
+ return user;
}
@GetMapping("replace")
@@ -48,6 +59,6 @@ public int merge(){
a.setCreateTime(new Date());
a.setName("dfa");
a.setPassword("124321");
- return userMapper.mergeinfo(a);
+ return 1;
}
}
diff --git a/SpringBoot-MyBatis-Advances/src/main/java/com/fancv/dao/User.java b/SpringBoot-MyBatis-Advances/src/main/java/com/fancv/dao/User.java
index 3818498..d172df0 100644
--- a/SpringBoot-MyBatis-Advances/src/main/java/com/fancv/dao/User.java
+++ b/SpringBoot-MyBatis-Advances/src/main/java/com/fancv/dao/User.java
@@ -1,10 +1,9 @@
package com.fancv.dao;
-import org.springframework.stereotype.Component;
-
+import java.io.Serializable;
import java.util.Date;
-public class User {
+public class User implements Serializable {
private Integer id;
private String name;
diff --git a/SpringBoot-MyBatis-Advances/src/main/java/com/fancv/service/UserService.java b/SpringBoot-MyBatis-Advances/src/main/java/com/fancv/service/UserService.java
new file mode 100644
index 0000000..6fc0f57
--- /dev/null
+++ b/SpringBoot-MyBatis-Advances/src/main/java/com/fancv/service/UserService.java
@@ -0,0 +1,36 @@
+package com.fancv.service;
+
+import com.fancv.dao.User;
+import com.fancv.mapper.MyUserMapper;
+import lombok.extern.log4j.Log4j2;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.cache.annotation.CacheConfig;
+import org.springframework.cache.annotation.Cacheable;
+import org.springframework.cache.annotation.EnableCaching;
+import org.springframework.stereotype.Service;
+
+@Service
+@Log4j2
+@EnableCaching
+@CacheConfig(cacheNames = "users")
+public class UserService {
+
+ @Autowired
+ MyUserMapper userMapper;
+
+ /**
+ * @Cacheable(cacheNames = "users", condition = "#id > 0", sync = true, keyGenerator = "keyGenerator",key = "'user-' + #id")
+ * Both 'key' and 'keyGenerator' attributes have been set. 不能同时使用
+ * @param id
+ * @return
+ */
+ @Cacheable(cacheNames = "users", condition = "#id > 0", sync = true, keyGenerator = "keyGenerator")
+ public User getUerInfo(Integer id) {
+ return userMapper.selectByPrimaryKey(id);
+ }
+
+ @Cacheable(cacheNames = "ca", sync = true, keyGenerator = "keyGenerator")
+ public User getUerInfoWithoutKey() {
+ return userMapper.selectByPrimaryKey(2);
+ }
+}
diff --git a/SpringBoot-MyBatis-Advances/src/main/resources/application.yaml b/SpringBoot-MyBatis-Advances/src/main/resources/application.yaml
index 2788663..9c0dcb4 100644
--- a/SpringBoot-MyBatis-Advances/src/main/resources/application.yaml
+++ b/SpringBoot-MyBatis-Advances/src/main/resources/application.yaml
@@ -1,4 +1,13 @@
spring:
+ cache:
+ redis:
+ key-prefix: "sp:"
+ time-to-live: 800
+ type: redis
+ redis:
+ port: 6379
+ host: 127.0.0.1
+ database: 10
datasource:
username: admin
password: hta@123
@@ -35,3 +44,8 @@ mybatis:
mapper-locations: classpath:mappers/*Mapper.xml
type-aliases-package: com.fancv.dao
+logging:
+ level:
+ com.fancv.mapper: debug
+
+
diff --git a/SpringBoot-Security/pom.xml b/SpringBoot-Security/pom.xml
new file mode 100644
index 0000000..1f184bd
--- /dev/null
+++ b/SpringBoot-Security/pom.xml
@@ -0,0 +1,132 @@
+
+
+
+
+ SpringBootCodeBase
+ com.fancv
+ 1.0-SNAPSHOT
+
+ 4.0.0
+
+ SpringBoot-Security
+
+ SpringBoot-Security
+
+ http://www.example.com
+
+
+ UTF-8
+ 11
+ 11
+
+
+
+
+ junit
+ junit
+ 4.11
+ test
+
+
+ org.springframework.boot
+ spring-boot-starter-jdbc
+ 2.3.9.RELEASE
+
+
+ com.alibaba
+ druid-spring-boot-starter
+ 1.1.17
+
+
+ org.springframework.boot
+ spring-boot-configuration-processor
+ 2.5.7
+
+
+
+ com.baomidou
+ mybatis-plus
+ 3.5.1
+
+
+ mysql
+ mysql-connector-java
+ 8.0.19
+
+
+ org.slf4j
+ log4j-over-slf4j
+ 1.7.25
+
+
+
+ org.springframework.boot
+ spring-boot-starter-security
+
+
+ org.springframework.cloud
+ spring-cloud-starter-oauth2
+ 2.2.5.RELEASE
+
+
+ com.nimbusds
+ nimbus-jose-jwt
+ 8.16
+
+
+ org.springframework.boot
+ spring-boot-starter-data-redis
+
+
+ org.springframework.boot
+ spring-boot-starter-thymeleaf
+
+
+
+
+
+
+
+
+ maven-clean-plugin
+ 3.1.0
+
+
+
+ maven-resources-plugin
+ 3.0.2
+
+
+ maven-compiler-plugin
+ 3.8.0
+
+
+ maven-surefire-plugin
+ 2.22.1
+
+
+ maven-jar-plugin
+ 3.0.2
+
+
+ maven-install-plugin
+ 2.5.2
+
+
+ maven-deploy-plugin
+ 2.8.2
+
+
+
+ maven-site-plugin
+ 3.7.1
+
+
+ maven-project-info-reports-plugin
+ 3.0.0
+
+
+
+
+
diff --git a/SpringBoot-Security/src/main/java/com/fancv/SpringSecurityApplicationStart.java b/SpringBoot-Security/src/main/java/com/fancv/SpringSecurityApplicationStart.java
new file mode 100644
index 0000000..8940b00
--- /dev/null
+++ b/SpringBoot-Security/src/main/java/com/fancv/SpringSecurityApplicationStart.java
@@ -0,0 +1,19 @@
+package com.fancv;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
+
+/**
+ * Hello world!
+ *
+ */
+@SpringBootApplication
+@EnableResourceServer
+public class SpringSecurityApplicationStart
+{
+ public static void main( String[] args )
+ {
+ SpringApplication.run(SpringSecurityApplicationStart.class,args);
+ }
+}
diff --git a/SpringBoot-Security/src/main/java/com/fancv/config/CustomTokenEnhancer.java b/SpringBoot-Security/src/main/java/com/fancv/config/CustomTokenEnhancer.java
new file mode 100644
index 0000000..8833aa7
--- /dev/null
+++ b/SpringBoot-Security/src/main/java/com/fancv/config/CustomTokenEnhancer.java
@@ -0,0 +1,27 @@
+package com.fancv.config;
+
+
+import org.springframework.security.core.Authentication;
+import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
+import org.springframework.security.oauth2.common.OAuth2AccessToken;
+import org.springframework.security.oauth2.provider.OAuth2Authentication;
+import org.springframework.security.oauth2.provider.token.TokenEnhancer;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class CustomTokenEnhancer implements TokenEnhancer {
+
+ @Override
+ public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
+ Authentication userAuthentication = authentication.getUserAuthentication();
+ if (userAuthentication != null) {
+ Object principal = authentication.getUserAuthentication().getPrincipal();
+ //把用户标识嵌入JWT Token中去(Key是userDetails)
+ Map additionalInfo = new HashMap<>();
+ additionalInfo.put("userDetails", principal);
+ ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
+ }
+ return accessToken;
+ }
+}
\ No newline at end of file
diff --git a/SpringBoot-Security/src/main/java/com/fancv/config/OAuth2ServerConfiguration.java b/SpringBoot-Security/src/main/java/com/fancv/config/OAuth2ServerConfiguration.java
new file mode 100644
index 0000000..d63bcf6
--- /dev/null
+++ b/SpringBoot-Security/src/main/java/com/fancv/config/OAuth2ServerConfiguration.java
@@ -0,0 +1,154 @@
+package com.fancv.config;
+
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.core.io.ClassPathResource;
+import org.springframework.data.redis.connection.RedisConnectionFactory;
+import org.springframework.security.authentication.AuthenticationManager;
+import org.springframework.security.crypto.password.NoOpPasswordEncoder;
+import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
+import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
+import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
+import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
+import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
+import org.springframework.security.oauth2.provider.approval.JdbcApprovalStore;
+import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
+import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
+import org.springframework.security.oauth2.provider.token.TokenEnhancer;
+import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
+import org.springframework.security.oauth2.provider.token.TokenStore;
+import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
+import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
+import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
+import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
+import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
+
+import javax.sql.DataSource;
+import java.util.Arrays;
+
+@Configuration
+@EnableAuthorizationServer //开启授权服务器
+public class OAuth2ServerConfiguration extends AuthorizationServerConfigurerAdapter {
+ @Autowired
+ private DataSource dataSource;
+
+ @Autowired
+ private AuthenticationManager authenticationManager;
+
+ @Autowired
+ private RedisConnectionFactory redisConnectionFactory;
+
+
+
+
+ /**
+ * 我们配置了使用数据库来维护客户端信息。虽然在各种Demo中我们经常看到的是在内存中维护客户端信息,通过配置直接写死在这里。
+ * 但是,对于实际的应用我们一般都会用数据库来维护这个信息,甚至还会建立一套工作流来允许客户端自己申请ClientID,实现OAuth客户端接入的审批。
+ * @param clients
+ * @throws Exception
+ */
+ @Override
+ public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
+ clients.jdbc(dataSource);
+ }
+
+ /**
+ * 这里干了两件事儿。首先,打开了验证Token的访问权限(以便之后我们演示)。
+ * 然后,允许ClientSecret明文方式保存,并且可以通过表单提交(而不仅仅是Basic Auth方式提交),之后会演示到这个。
+ * @param security
+ * @throws Exception
+ */
+ @Override
+ public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
+ security.checkTokenAccess("permitAll()")
+ .allowFormAuthenticationForClients().passwordEncoder(NoOpPasswordEncoder.getInstance());
+ }
+
+ /**
+ * 干了以下4件事儿:
+ * 1. 配置我们的令牌存放方式为JWT方式,而不是内存、数据库或Redis方式。
+ * JWT是Json Web Token的缩写,也就是使用JSON数据格式包装的令牌,由.号把整个JWT分隔为头、数据体、签名三部分。
+ * JWT保存Token虽然易于使用但是不是那么安全,一般用于内部,且需要走HTTPS并配置比较短的失效时间。
+ * 2. 配置JWT Token的非对称加密来进行签名
+ * 3. 配置一个自定义的Token增强器,把更多信息放入Token中
+ * 4. 配置使用JDBC数据库方式来保存用户的授权批准记录
+ * @param endpoints
+ * @throws Exception
+ */
+ @Override
+ public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
+ TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
+ tokenEnhancerChain.setTokenEnhancers(
+ Arrays.asList(tokenEnhancer()));
+
+ endpoints.approvalStore(approvalStore())
+ .authorizationCodeServices(authorizationCodeServices())
+ .tokenStore(tokenStore())
+ .tokenEnhancer(tokenEnhancerChain)
+ .authenticationManager(authenticationManager);
+ }
+
+ /**
+ * 使用JDBC数据库方式来保存授权码
+ * @return
+ */
+ @Bean
+ public AuthorizationCodeServices authorizationCodeServices() {
+ return new JdbcAuthorizationCodeServices(dataSource);
+ }
+
+ /**
+ * 使用Redis存储
+ * @return
+ */
+ @Bean
+ public TokenStore tokenStore() {
+ RedisTokenStore redisTokenStore = new RedisTokenStore(redisConnectionFactory);
+ redisTokenStore.setPrefix("auth-token:");
+ return redisTokenStore;
+ }
+
+ /**
+ * 使用JDBC数据库方式来保存用户的授权批准记录
+ * @return
+ */
+ @Bean
+ public JdbcApprovalStore approvalStore() {
+ return new JdbcApprovalStore(dataSource);
+ }
+
+ /**
+ * 自定义的Token增强器,把更多信息放入Token中
+ * @return
+ */
+ @Bean
+ public TokenEnhancer tokenEnhancer() {
+ return new CustomTokenEnhancer();
+ }
+
+ /**
+ * 配置JWT使用非对称加密方式来验证
+ * @return
+ */
+ /* @Bean
+ protected JwtAccessTokenConverter jwtTokenEnhancer() {
+ KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("jwt.jks"), "2022qw".toCharArray());
+ JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
+ converter.setKeyPair(keyStoreKeyFactory.getKeyPair("jwt"));
+ return converter;
+ }*/
+
+ /**
+ * 配置登录页面的视图信息(其实可以独立一个配置类,这样会更规范)
+ */
+ @Configuration
+ static class MvcConfig implements WebMvcConfigurer {
+ @Override
+ public void addViewControllers(ViewControllerRegistry registry) {
+ registry.addViewController("login").setViewName("login");
+ }
+ }
+}
diff --git a/SpringBoot-Security/src/main/java/com/fancv/config/WebSecurityConfig.java b/SpringBoot-Security/src/main/java/com/fancv/config/WebSecurityConfig.java
new file mode 100644
index 0000000..be4e852
--- /dev/null
+++ b/SpringBoot-Security/src/main/java/com/fancv/config/WebSecurityConfig.java
@@ -0,0 +1,71 @@
+package com.fancv.config;
+
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.security.authentication.AuthenticationManager;
+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.builders.WebSecurity;
+import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
+import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
+import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
+
+import javax.sql.DataSource;
+
+@Configuration
+@EnableWebSecurity
+public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
+ @Autowired
+ private DataSource dataSource;
+
+ @Override
+ @Bean
+ public AuthenticationManager authenticationManagerBean() throws Exception {
+ return super.authenticationManagerBean();
+ }
+
+ /**
+ * 配置用户账户的认证方式。显然,我们把用户存在了数据库中希望配置JDBC的方式。
+ * 此外,我们还配置了使用BCryptPasswordEncoder哈希来保存用户的密码(生产环境中,用户密码肯定不能是明文保存的)
+ * @param auth
+ * @throws Exception
+ */
+ @Override
+ protected void configure(AuthenticationManagerBuilder auth) throws Exception {
+ auth.jdbcAuthentication()
+ .dataSource(dataSource)
+ .passwordEncoder(new BCryptPasswordEncoder());
+ }
+
+ /**
+ * 开放/login和/oauth/authorize两个路径的匿名访问。前者用于登录,后者用于换授权码,这两个端点访问的时机都在登录之前。
+ * 设置/login使用表单验证进行登录。
+ * @param http
+ * @throws Exception
+ */
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+
+ http.authorizeRequests()
+ .antMatchers("/login/**").permitAll()// 配置拦截规则
+ .anyRequest().authenticated();
+
+// http.authorizeRequests()
+// .antMatchers("/login")
+// .permitAll()
+// .anyRequest().authenticated()
+// .and()
+// .formLogin().loginPage("/login");
+ }
+ /***
+ * 核心过滤器配置方法
+ * @param web
+ * @throws Exception
+ */
+ @Override
+ public void configure(WebSecurity web) throws Exception {
+ super.configure(web);
+ }
+}
\ No newline at end of file
diff --git a/SpringBoot-Security/src/main/java/com/fancv/controller/UserInfoController.java b/SpringBoot-Security/src/main/java/com/fancv/controller/UserInfoController.java
new file mode 100644
index 0000000..7fb06c9
--- /dev/null
+++ b/SpringBoot-Security/src/main/java/com/fancv/controller/UserInfoController.java
@@ -0,0 +1,15 @@
+package com.fancv.controller;
+
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@RequestMapping("user/")
+public class UserInfoController {
+
+ @GetMapping("list")
+ public String userList(){
+ return "ok";
+ }
+}
diff --git a/SpringBoot-Security/src/main/resources/application.yaml b/SpringBoot-Security/src/main/resources/application.yaml
new file mode 100644
index 0000000..b9281ae
--- /dev/null
+++ b/SpringBoot-Security/src/main/resources/application.yaml
@@ -0,0 +1,40 @@
+spring:
+ redis:
+ host: 127.0.0.1
+ database: 1
+ port: 6379
+ datasource:
+ username: 'admin'
+ password: 'hta@123'
+ url: jdbc:mysql://127.0.0.1:3306/spring_security?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&zeroDateTimeBehavior=convertToNull
+ driver-class-name: com.mysql.cj.jdbc.Driver
+ type: com.alibaba.druid.pool.DruidDataSource
+ initialSize: 5
+ minIdle: 5
+ maxActive: 20
+ maxWait: 60000
+ timeBetweenEvictionRunsMillis: 60000
+ minEvictableIdleTimeMillis: 300000
+ validationQuery: SELECT 1 FROM DUAL
+ testWhileIdle: true
+ testOnBorrow: false
+ testOnReturn: false
+ poolPreparedStatements: true
+ #配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
+ filters: stat,wall,log4j
+ maxPoolPreparedStatementPerConnectionSize: 20
+ useGlobalDataSourceStat: true
+ connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
+ db2:
+ username: admin
+ password: hta@123
+ url: jdbc:mysql://localhost:3306/spring_security?useUnicode=true&characterEncoding=utf-8&useSSL=false
+ driver-class-name: com.mysql.cj.jdbc.Driver
+
+server:
+ port: 9011
+
+
+logging:
+ level:
+ root: debug
\ No newline at end of file
diff --git a/SpringBoot-Security/src/main/resources/jwt.jks b/SpringBoot-Security/src/main/resources/jwt.jks
new file mode 100644
index 0000000..9bfeb9c
Binary files /dev/null and b/SpringBoot-Security/src/main/resources/jwt.jks differ
diff --git a/SpringBoot-Security/src/main/resources/templates/login.html b/SpringBoot-Security/src/main/resources/templates/login.html
new file mode 100644
index 0000000..b1183c4
--- /dev/null
+++ b/SpringBoot-Security/src/main/resources/templates/login.html
@@ -0,0 +1,37 @@
+
+
+
+
+ OAuth2 Demo
+
+
+
+
+
+
+
+
Login Form
+
+
+ 用户名或密码错误...
+
+
+
+
+
+
+
+
+
diff --git a/SpringBoot-Security/src/test/java/com/fancv/SpringSecurityApplicationStartTest.java b/SpringBoot-Security/src/test/java/com/fancv/SpringSecurityApplicationStartTest.java
new file mode 100644
index 0000000..2100f4a
--- /dev/null
+++ b/SpringBoot-Security/src/test/java/com/fancv/SpringSecurityApplicationStartTest.java
@@ -0,0 +1,20 @@
+package com.fancv;
+
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+/**
+ * Unit test for simple App.
+ */
+public class SpringSecurityApplicationStartTest
+{
+ /**
+ * Rigorous Test :-)
+ */
+ @Test
+ public void shouldAnswerWithTrue()
+ {
+ assertTrue( true );
+ }
+}