#---------------------OAuth2---------------------
security:
oauth2:
client:
access-token-uri: http://localhost:
s
e
r
v
e
r
.
p
o
r
t
/
a
u
t
h
/
o
a
u
t
h
/
t
o
k
e
n
u
s
e
r
−
a
u
t
h
o
r
i
z
a
t
i
o
n
−
u
r
i
:
h
t
t
p
:
/
/
l
o
c
a
l
h
o
s
t
:
{server.port}/auth/oauth/token user-authorization-uri: http://localhost:
server.port/auth/oauth/tokenuser−authorization−uri:http://localhost:{server.port}/auth/oauth/authorize
client-id: web
resource:
user-info-uri: http://localhost:${server.port}/auth/javayh/member
prefer-token-info: false
#----------------------超时配置-------------------
ribbon:
ReadTimeout: 60000
ConnectTimeout: 60000
MaxAutoRetries: 2
MaxAutoRetriesNextServer: 2
eureka:
enabled: true
hystrix:
command:
default:
execution:
timeout:
enabled: true
isolation:
thread:
timeoutInMilliseconds: 60000
pom配置
<?xml version="1.0" encoding="UTF-8"?>
4.0.0
com.javayh
javayh-oauth2
0.0.1-SNAPSHOT
com.javayh
javayh-zuul
0.0.1-SNAPSHOT
javayh-zuul
javayh-zuul
Security配置
@Configuration
@EnableWebSecurity
@Order(99)//必加
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
- 禁止csrf
- @param http
- @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
}
认证服务器配置
yaml
摘取自某位大佬的,讲解很详细
server:
port: 8092
spring:
application:
name: javayh-oauth
redis:
database: 0
host: localhost
port: 6379
password:
jedis:
pool:
max-active: 8
max-idle: 8
min-idle: 0
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowMultiQueries=true
username: root
password: 1219320
druid:
initialSize: 5 #初始化连接大小
minIdle: 5 #最小连接池数量
maxActive: 20 #最大连接池数量
maxWait: 60000 #获取连接时最大等待时间,单位毫秒
timeBetweenEvictionRunsMillis: 60000 #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
minEvictableIdleTimeMillis: 300000 #配置一个连接在池中最小生存的时间,单位是毫秒
validationQuery: SELECT 1 from DUAL #测试连接
testWhileIdle: true #申请连接的时候检测,建议配置为true,不影响性能,并且保证安全性
testOnBorrow: false #获取连接时执行检测,建议关闭,影响性能
testOnReturn: false #归还连接时执行检测,建议关闭,影响性能
poolPreparedStatements: false #是否开启PSCache,PSCache对支持游标的数据库性能提升巨大,oracle建议开启,mysql下建议关闭
maxPoolPreparedStatementPerConnectionSize: 20 #开启poolPreparedStatements后生效
filters: stat,wall,log4j #配置扩展插件,常用的插件有=>stat:监控统计 log4j:日志 wall:防御sql注入
connectionProperties: ‘druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000’ #通过connectProperties属性来打开mergeSql功能;慢SQL记录
eureka:
instance:
prefer-ip-address: true
instance-id:
s
p
r
i
n
g
.
c
l
o
u
d
.
c
l
i
e
n
t
.
i
p
−
a
d
d
r
e
s
s
:
{spring.cloud.client.ip-address}:
spring.cloud.client.ip−address:{server.port}
client:
service-url:
defaultZone: http://localhost:8090/eureka/
mybatis:
type-aliases-package: com.javayh.entity
configuration:
map-underscore-to-camel-case: true #开启驼峰命名,l_name -> lName
jdbc-type-for-null: NULL
lazy-loading-enabled: true
aggressive-lazy-loading: true
cache-enabled: true #开启二级缓存
call-setters-on-nulls: true #map空列不显示问题
mapper-locations:
- classpath:mybatis/*.xml
pom配置
<?xml version="1.0" encoding="UTF-8"?>
4.0.0
com.javayh
javayh-oauth2
0.0.1-SNAPSHOT
com.javayh
javayh-oauth
0.0.1-SNAPSHOT
javayh-oauth
ojavayh-oauth
接下来是重点配置
DruidConfiguration
@Slf4j
@Configuration
public class DruidConfiguration {
@Value(“${spring.datasource.url}”)
private String url;
@Value(“${spring.datasource.username}”)
private String username;
@Value(“${spring.datasource.password}”)
private String password;
@Value(“${spring.datasource.driver-class-name}”)
private String driverClassName;
@Value(“${spring.druid.initialSize}”)
private int initialSize;
@Value(“${spring.druid.minIdle}”)
private int minIdle;
@Value(“${spring.druid.maxActive}”)
private int maxActive;
@Value(“${spring.druid.maxWait}”)
private int maxWait;
@Value(“${spring.druid.timeBetweenEvictionRunsMillis}”)
private int timeBetweenEvictionRunsMillis;
@Value(“${spring.druid.minEvictableIdleTimeMillis}”)
private int minEvictableIdleTimeMillis;
@Value(“${spring.druid.validationQuery}”)
private String validationQuery;
@Value(“${spring.druid.testWhileIdle}”)
private boolean testWhileIdle;
@Value(“${spring.druid.testOnBorrow}”)
private boolean testOnBorrow;
@Value(“${spring.druid.testOnReturn}”)
private boolean testOnReturn;
@Value(“${spring.druid.poolPreparedStatements}”)
private boolean poolPreparedStatements;
@Value(“${spring.druid.maxPoolPreparedStatementPerConnectionSize}”)
private int maxPoolPreparedStatementPerConnectionSize;
@Value(“${spring.druid.filters}”)
private String filters;
@Value(“{spring.druid.connectionProperties}”)
private String connectionProperties;
@Bean
@Primary
public DataSource dataSource() {
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(url);
datasource.setUsername(username);
//这里可以做加密处理
datasource.setPassword(password);
datasource.setDriverClassName(driverClassName);
//configuration
datasource.setInitialSize(initialSize);
datasource.setMinIdle(minIdle);
datasource.setMaxActive(maxActive);
datasource.setMaxWait(maxWait);
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setValidationQuery(validationQuery);
datasource.setTestWhileIdle(testWhileIdle);
datasource.setTestOnBorrow(testOnBorrow);
datasource.setTestOnReturn(testOnReturn);
datasource.setPoolPreparedStatements(poolPreparedStatements);
datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
try {
datasource.setFilters(filters);
} catch (SQLException e) {
log.info(“连接异常”+e.getMessage());
}
datasource.setConnectionProperties(connectionProperties);
return datasource;
}
@Bean
public FilterRegistrationBean statFilter() {
//创建过滤器
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
//设置过滤器过滤路径
filterRegistrationBean.addUrlPatterns(“/");
//忽略过滤的形式
filterRegistrationBean.addInitParameter(“exclusions”, ".js,.gif,.jpg,.png,.css,.ico,/druid/”);
return filterRegistrationBean;
}
}
AuthorizationServerConfig
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private DataSource dataSource;
@Autowired
private RedisConnectionFactory redisConnectionFactory;
@Autowired
private MyUserDetailService userDetailService;
@Bean
public TokenStore tokenStore() {
return new RedisTokenStore(redisConnectionFactory);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security
.allowFormAuthenticationForClients()
.tokenKeyAccess(“permitAll()”)
.checkTokenAccess(“isAuthenticated()”);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// clients.withClientDetails(clientDetails());
clients.inMemory()
.withClient(“android”)
.scopes(“read”)
.secret(“android”)
.authorizedGrantTypes(“password”, “authorization_code”, “refresh_token”)
.and()
.withClient(“webapp”)
.scopes(“read”)
.authorizedGrantTypes(“implicit”)
.and()
.withClient(“browser”)
.authorizedGrantTypes(“refresh_token”, “password”)
.scopes(“read”);
}
@Bean
public ClientDetailsService clientDetails() {
return new JdbcClientDetailsService(dataSource);
}
@Bean
public WebResponseExceptionTranslator webResponseExceptionTranslator(){
return new JavaYhWebException();
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore())
.userDetailsService(userDetailService)
.authenticationManager(authenticationManager);
endpoints.tokenServices(defaultTokenServices());
//认证异常翻译
endpoints.exceptionTranslator(webResponseExceptionTranslator());
}
/**
-
注意,自定义TokenServices的时候,需要设置@Primary,否则报错,
- @return
/
@Primary
@Bean
public DefaultTokenServices defaultTokenServices(){
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setTokenStore(tokenStore());
tokenServices.setSupportRefreshToken(true);
//tokenServices.setClientDetailsService(clientDetails());
// token有效期自定义设置,默认12小时
tokenServices.setAccessTokenValiditySeconds(6060*12);
// refresh_token默认30天
tokenServices.setRefreshTokenValiditySeconds(60 * 60 * 24 * 7);
return tokenServices;
}
}
ResourceServerConfig
最后
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数Java工程师,想要提升技能,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助。
因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,不论你是刚入门Android开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门!
如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。**
[外链图片转存中…(img-T03KBUOE-1715079822521)]
[外链图片转存中…(img-Ne5XA7RP-1715079822521)]
[外链图片转存中…(img-b4ng4eDC-1715079822521)]
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,不论你是刚入门Android开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门!
如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!