首先推薦看這篇:https://blog.csdn.net/u014730165/article/details/83181754
另外一個博客的源碼傳送:https://github.com/babylikebird/Micro-Service-Skeleton
環境:
大部分和推薦的這邊文章的pom依賴相同,不過用了nacos作爲配置中心和註冊中心,這裏面的版本比較重要,兼容性不用調。
兼容性問題:
問題1:這個版本可以解決redis兼容問題 【RedisConnection.set([B[B)V-】
參見文章:https://www.cnblogs.com/nicori/p/10001759.html
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.3.RELEASE</version>
</dependency>
springcloud:Finchley.RELEASE
springboot:2.0.0.RELEASE
JDK:1.8
nacos:0.2.1.RELEASE(暫時不講)
springcloud版本和springboot版本要注意,
大版本對應:
Spring Boot | Spring Cloud |
---|---|
1.2.x | Angel版本 |
1.3.x | Brixton版本 |
1.4.x stripes | Camden版本 |
1.5.x | Dalston版本、Edgware版本 |
2.0.x | Finchley版本 |
代碼:
application.yml
spring:
application:
name: member
redis:
password: 12345678
database: 0
port: 6379
host: 10.105.17.xxx
timeout: 2000
datasource:
url: jdbc:mysql://10.100.248.3:3306/oauth2?useUnicode=true&characterEncoding=utf8
username: root
password: root
druid:
driver-class-name: com.mysql.jdbc.Driver
server:
port: 8080
servlet:
context-path: /
OAuth2ServerConfig.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
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.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import javax.sql.DataSource;
@Order(2)
@Configuration
@EnableAuthorizationServer
public class OAuth2ServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
UserDetailsService userDetailsService;
@Autowired
RedisTemplate redisTemplate;
@Autowired
private DataSource dataSource;
@Autowired
PasswordEncoder passwordEncoder;
@Bean
RedisTokenStore redisTokenStore() {
return new RedisTokenStore(redisTemplate.getConnectionFactory());
}
@Bean
public ClientDetailsService clientDetails() {
return new JdbcClientDetailsService(dataSource);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer
.realm("xxxx-service")
//url:/oauth/token_key,exposes public key for token verification if using JWT tokens
.tokenKeyAccess("permitAll()")
//url:/oauth/check_token allow check token
.checkTokenAccess("isAuthenticated()")
.allowFormAuthenticationForClients();
}
/**
* jdbc token 配置
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService)
.tokenStore(redisTokenStore());
endpoints.tokenServices(defaultTokenServices());
}
@Primary
@Bean
public DefaultTokenServices defaultTokenServices() {
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setTokenStore(redisTokenStore());
tokenServices.setSupportRefreshToken(true);
tokenServices.setClientDetailsService(clientDetails());
// token有效期自定義設置,默認12小時
tokenServices.setAccessTokenValiditySeconds(60 * 60 * 12);
//默認30天,這裏修改
tokenServices.setRefreshTokenValiditySeconds(60 * 60 * 24 * 7);
return tokenServices;
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.withClientDetails(clientDetails());
// clients.inMemory()
// .withClient("dev")
// .secret(passwordEncoder.encode("dev"))
// .redirectUris("http://example.com")
// .authorizedGrantTypes("authorization_code", "client_credentials", "refresh_token",
// "password", "implicit")
// .scopes("all")
// .resourceIds("oauth2-resource")
// .accessTokenValiditySeconds(7200)
// .refreshTokenValiditySeconds(9200);
}
}
ResourceServerConfiguration.java
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
/**
* OAuth 資源服務器配置
*
* @author
* @date 2018-05-29
*/
@Order(6)
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf()
.disable()
.authorizeRequests()
.antMatchers("/oauth/**")
.permitAll()
.anyRequest()
.authenticated();
}
}
WebSecurityConfig.java
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.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
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.provisioning.InMemoryUserDetailsManager;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
PasswordEncoder passwordEncoder;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().and().authorizeRequests()
.antMatchers("/oauth/**","/login")
.permitAll()
.anyRequest()
.authenticated()
.and().csrf().disable();
}
@Bean
@Override
protected UserDetailsService userDetailsService(){
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(User.withUsername("hello1").password(passwordEncoder.encode("123456")).authorities("USER").build());
manager.createUser(User.withUsername("hello2").password(passwordEncoder.encode("123456")).authorities("USER").build());
return manager;
}
}
postMan驗證:
授權碼模式
1、獲取授權碼:
http://localhost:8080/oauth/authorize?response_type=code&client_id=dev&redirect_uri=http://example.com&scop=all
瀏覽器中回車,輸入WebSecurityConfig類中的userDetailsService方法裏添加username和password,後期從數據庫讀取
回調的地址欄有code
postman獲取access_token
使用token訪問自己的接口,Authorization選Oauth2填寫剛纔的access_token;或者Header裏面直接添加bearer+空格+access_token
acess_token刷新
客戶端模式(client)
密碼模式(password)