Spring boot 安全微服务环境的最低设置
我想用Gradle、Spring Boot2、Zuul、JWT、带REST Api的微服务和自制的身份验证服务器来设置SSO微服务环境。Spring boot 安全微服务环境的最低设置,spring-boot,jwt,single-sign-on,api-gateway,Spring Boot,Jwt,Single Sign On,Api Gateway,我想用Gradle、Spring Boot2、Zuul、JWT、带REST Api的微服务和自制的身份验证服务器来设置SSO微服务环境。 当身份验证服务器、网关和微服务充当OAuth客户端和资源服务器时,它们的注释是什么?什么是最小设置?对于gradle配置,我建议使用网站和授权服务器。配置如下所示: buildscript { ext { springBootVersion = '2.0.3.RELEASE' } repositories {
当身份验证服务器、网关和微服务充当OAuth客户端和资源服务器时,它们的注释是什么?什么是最小设置?对于gradle配置,我建议使用网站和授权服务器。配置如下所示:
buildscript {
ext {
springBootVersion = '2.0.3.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
ext {
springCloudVersion = 'Finchley.RELEASE'
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.cloud:spring-cloud-starter-oauth2')
compile('org.springframework.cloud:spring-cloud-starter-security')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
@Configuration
@EnableAuthorizationServer
public class SecurityOAuth2AutorizationServerConfig extends AuthorizationServerConfigurerAdapter {
private final AccountUserDetailsService accountUserDetailsService;
private final UserDetailsService authenticationManager;
private final PasswordEncoder passwordEncoder;
public SecurityOAuth2AutorizationServerConfig(UserDetailsService accountUserDetailsService,
AuthenticationManager authenticationManager,
PasswordEncoder passwordEncoder) {
this.accountUserDetailsService = accountUserDetailsService;
this.authenticationManager = authenticationManager;
this.passwordEncoder = passwordEncoder;
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.approvalStoreDisabled()
.authenticationManager(authenticationManager)
.tokenStore(tokenStore())
.accessTokenConverter(accessTokenConverter())
.userDetailsService(accountUserDetailsService)
.reuseRefreshTokens(false);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
oauthServer.tokenKeyAccess("permitAll()")
.passwordEncoder(passwordEncoder)
.checkTokenAccess("isAuthenticated()")
.allowFormAuthenticationForClients();
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("client")
.secret(passwordEncoder.encode("secret"))
.authorizedGrantTypes("authorization_code", "refresh_token", "password").scopes("openid")
.authorities("ROLE_USER", "ROLE_EMPLOYEE")
.scopes("read", "write", "trust", "openid")
.resourceIds("oauth2-resource")
.autoApprove(true)
.accessTokenValiditySeconds(5)
.refreshTokenValiditySeconds(60*60*8);
}
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
....
}
}
@EnableResourceServer
@SpringBootApplication
public class AccountServiceApplication {
public static void main(String[] args) {
SpringApplication.run(AccountServiceApplication.class, args);
}
}
然后,身份验证服务器将如下所示:
buildscript {
ext {
springBootVersion = '2.0.3.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
ext {
springCloudVersion = 'Finchley.RELEASE'
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.cloud:spring-cloud-starter-oauth2')
compile('org.springframework.cloud:spring-cloud-starter-security')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
@Configuration
@EnableAuthorizationServer
public class SecurityOAuth2AutorizationServerConfig extends AuthorizationServerConfigurerAdapter {
private final AccountUserDetailsService accountUserDetailsService;
private final UserDetailsService authenticationManager;
private final PasswordEncoder passwordEncoder;
public SecurityOAuth2AutorizationServerConfig(UserDetailsService accountUserDetailsService,
AuthenticationManager authenticationManager,
PasswordEncoder passwordEncoder) {
this.accountUserDetailsService = accountUserDetailsService;
this.authenticationManager = authenticationManager;
this.passwordEncoder = passwordEncoder;
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.approvalStoreDisabled()
.authenticationManager(authenticationManager)
.tokenStore(tokenStore())
.accessTokenConverter(accessTokenConverter())
.userDetailsService(accountUserDetailsService)
.reuseRefreshTokens(false);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
oauthServer.tokenKeyAccess("permitAll()")
.passwordEncoder(passwordEncoder)
.checkTokenAccess("isAuthenticated()")
.allowFormAuthenticationForClients();
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("client")
.secret(passwordEncoder.encode("secret"))
.authorizedGrantTypes("authorization_code", "refresh_token", "password").scopes("openid")
.authorities("ROLE_USER", "ROLE_EMPLOYEE")
.scopes("read", "write", "trust", "openid")
.resourceIds("oauth2-resource")
.autoApprove(true)
.accessTokenValiditySeconds(5)
.refreshTokenValiditySeconds(60*60*8);
}
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
....
}
}
@EnableResourceServer
@SpringBootApplication
public class AccountServiceApplication {
public static void main(String[] args) {
SpringApplication.run(AccountServiceApplication.class, args);
}
}
sso登录页面的配置如下所示:
@Configuration
@Order(SecurityProperties.DEFAULT_FILTER_ORDER)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.formLogin()
.permitAll()
.and()
.authorizeRequests().anyRequest().authenticated();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public UserDetailsService accountUserDetailsService() {
InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
inMemoryUserDetailsManager.createUser(new User("user", "secret",
Collections.singleton(new SimpleGrantedAuthority("USER"))));
return inMemoryUserDetailsManager;
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
在sso应用程序中,您可以进行如下配置:
@EnableOAuth2Sso
@EnableZuulProxy
@SpringBootApplication
public class SsoDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SsoDemoApplication.class, args);
}
@Bean
@Primary
public OAuth2RestTemplate oAuth2RestTemplate(OAuth2ClientContext context,
OAuth2ProtectedResourceDetails authorizationCodeResourceDetails) {
return new OAuth2RestTemplate(authorizationCodeResourceDetails, context);
}
}
在application.yml中:
security:
oauth2:
client:
clientId: client
clientSecret: secret
accessTokenUri: http://localhost:9090/auth/oauth/token
userAuthorizationUri: http://localhost:9090/auth/oauth/authorize
auto-approve-scopes: '.*'
registered-redirect-uri: http://localhost:9090/auth/singin
clientAuthenticationScheme: form
resource:
jwt:
key-value: -----BEGIN PUBLIC KEY-----
......
-----END PUBLIC KEY-----
server:
use-forward-headers: true
zuul:
sensitiveHeaders:
ignoredServices: '*'
ignoreSecurityHeaders: false
addHostHeader: true
routes:
your-service: /your-service/**
proxy:
auth:
routes:
spent-budget-service: oauth2
security:
oauth2:
resource:
jwt:
key-value: -----BEGIN PUBLIC KEY-----
.....
-----END PUBLIC KEY----
server:
use-forward-headers: true
port: 9090
servlet:
context-path: /auth
management.endpoints.web.exposure.include: "*"
spring:
application:
name: authentication-server
security:
oauth2:
client:
clientId: client
clientSecret: secret
accessTokenUri: http://localhost:9090/auth/oauth/token
userAuthorizationUri: http://localhost:9090/auth/oauth/authorize
auto-approve-scopes: '.*'
registered-redirect-uri: http://localhost:9090/auth/login
clientAuthenticationScheme: form
resource:
user-info-uri: http://localhost:9090/auth/account/user-info
prefer-token-info: false
management.endpoints.web.exposure.include: "*"
server:
use-forward-headers: true
port: 8080
zuul:
sensitiveHeaders:
ignoredServices: '*'
ignoreSecurityHeaders: false
addHostHeader: true
routes:
hello-service:
serviceId: hello-service
path: /hello-service/**
url: http://localhost:4040/
proxy:
auth:
routes:
hello-service: oauth2
security:
oauth2:
client:
clientId: client
clientSecret: secret
accessTokenUri: http://localhost:9977/auth/oauth/token
userAuthorizationUri: http://localhost:9977/auth/oauth/authorize
auto-approve-scopes: '.*'
registered-redirect-uri: http://localhost:9977/auth/singin
clientAuthenticationScheme: form
resource:
token-info-uri: http://localhost:9977/oauth/check_token
preferTokenInfo: false
server:
use-forward-headers: true
port: 9977
zuul:
sensitiveHeaders:
ignoredServices: '*'
ignoreSecurityHeaders: false
addHostHeader: true
routes:
service:
url: http://localhost:8080
proxy:
auth:
routes:
service: oauth2
spring:
application:
name: service
security:
oauth2:
resource:
token-info-uri: http://localhost:9977/oauth/check_token
preferTokenInfo: false
通过这种方式,您可以使用身份验证服务器在sso中配置您的客户端应用程序@EnableOAuth2Sso将为您做任何事情它也类似于客户端应用程序,如果您的应用程序未经身份验证,您的sso将在您的身份验证服务器的登录页面上重定向您,并为您刷新您的令牌zuul令牌中继也可用在这个用例中,我使用eureka作为发现服务注册中心。配置OAuth2RestTemplate非常重要,因为spring将使用此bean为您自动刷新令牌,否则一旦令牌过期,您将无法自动刷新令牌
您的所有resourceserver将如下所示:
buildscript {
ext {
springBootVersion = '2.0.3.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
ext {
springCloudVersion = 'Finchley.RELEASE'
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.cloud:spring-cloud-starter-oauth2')
compile('org.springframework.cloud:spring-cloud-starter-security')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
@Configuration
@EnableAuthorizationServer
public class SecurityOAuth2AutorizationServerConfig extends AuthorizationServerConfigurerAdapter {
private final AccountUserDetailsService accountUserDetailsService;
private final UserDetailsService authenticationManager;
private final PasswordEncoder passwordEncoder;
public SecurityOAuth2AutorizationServerConfig(UserDetailsService accountUserDetailsService,
AuthenticationManager authenticationManager,
PasswordEncoder passwordEncoder) {
this.accountUserDetailsService = accountUserDetailsService;
this.authenticationManager = authenticationManager;
this.passwordEncoder = passwordEncoder;
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.approvalStoreDisabled()
.authenticationManager(authenticationManager)
.tokenStore(tokenStore())
.accessTokenConverter(accessTokenConverter())
.userDetailsService(accountUserDetailsService)
.reuseRefreshTokens(false);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
oauthServer.tokenKeyAccess("permitAll()")
.passwordEncoder(passwordEncoder)
.checkTokenAccess("isAuthenticated()")
.allowFormAuthenticationForClients();
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("client")
.secret(passwordEncoder.encode("secret"))
.authorizedGrantTypes("authorization_code", "refresh_token", "password").scopes("openid")
.authorities("ROLE_USER", "ROLE_EMPLOYEE")
.scopes("read", "write", "trust", "openid")
.resourceIds("oauth2-resource")
.autoApprove(true)
.accessTokenValiditySeconds(5)
.refreshTokenValiditySeconds(60*60*8);
}
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
....
}
}
@EnableResourceServer
@SpringBootApplication
public class AccountServiceApplication {
public static void main(String[] args) {
SpringApplication.run(AccountServiceApplication.class, args);
}
}
在application.yml中:
security:
oauth2:
client:
clientId: client
clientSecret: secret
accessTokenUri: http://localhost:9090/auth/oauth/token
userAuthorizationUri: http://localhost:9090/auth/oauth/authorize
auto-approve-scopes: '.*'
registered-redirect-uri: http://localhost:9090/auth/singin
clientAuthenticationScheme: form
resource:
jwt:
key-value: -----BEGIN PUBLIC KEY-----
......
-----END PUBLIC KEY-----
server:
use-forward-headers: true
zuul:
sensitiveHeaders:
ignoredServices: '*'
ignoreSecurityHeaders: false
addHostHeader: true
routes:
your-service: /your-service/**
proxy:
auth:
routes:
spent-budget-service: oauth2
security:
oauth2:
resource:
jwt:
key-value: -----BEGIN PUBLIC KEY-----
.....
-----END PUBLIC KEY----
server:
use-forward-headers: true
port: 9090
servlet:
context-path: /auth
management.endpoints.web.exposure.include: "*"
spring:
application:
name: authentication-server
security:
oauth2:
client:
clientId: client
clientSecret: secret
accessTokenUri: http://localhost:9090/auth/oauth/token
userAuthorizationUri: http://localhost:9090/auth/oauth/authorize
auto-approve-scopes: '.*'
registered-redirect-uri: http://localhost:9090/auth/login
clientAuthenticationScheme: form
resource:
user-info-uri: http://localhost:9090/auth/account/user-info
prefer-token-info: false
management.endpoints.web.exposure.include: "*"
server:
use-forward-headers: true
port: 8080
zuul:
sensitiveHeaders:
ignoredServices: '*'
ignoreSecurityHeaders: false
addHostHeader: true
routes:
hello-service:
serviceId: hello-service
path: /hello-service/**
url: http://localhost:4040/
proxy:
auth:
routes:
hello-service: oauth2
security:
oauth2:
client:
clientId: client
clientSecret: secret
accessTokenUri: http://localhost:9977/auth/oauth/token
userAuthorizationUri: http://localhost:9977/auth/oauth/authorize
auto-approve-scopes: '.*'
registered-redirect-uri: http://localhost:9977/auth/singin
clientAuthenticationScheme: form
resource:
token-info-uri: http://localhost:9977/oauth/check_token
preferTokenInfo: false
server:
use-forward-headers: true
port: 9977
zuul:
sensitiveHeaders:
ignoredServices: '*'
ignoreSecurityHeaders: false
addHostHeader: true
routes:
service:
url: http://localhost:8080
proxy:
auth:
routes:
service: oauth2
spring:
application:
name: service
security:
oauth2:
resource:
token-info-uri: http://localhost:9977/oauth/check_token
preferTokenInfo: false
-
当然,这是一个非常简单的配置,但id足够用于启动
更新:
不要忘记网关、sso和任何其他资源服务器上的应用程序yml中的资源配置,否则将无法针对身份验证服务器验证令牌
对于普通oauth2令牌,您可以使用
security.oauth2.resource.token-info-uri: your/auth/server:yourport/oauth/check_token
或
如果preferTokenInfo:false,则验证服务器上的典型帐户数据入口点
@RestController
@RequestMapping("/account")
class UserRestFullEndPoint {
@GetMapping("/userInfo")
public Principal userInfo(Principal principal){
return principal;
}
}
UserInfoRestTemplateFactory在令牌信息uri配置的情况下,将由spring自动提供。唯一要记住的是配置Oauth2RestTemplate,否则您的令牌将不再刷新
更新2
对于非JWT令牌,缺少的配置是添加
身份验证服务器上的@EnableResourceServer
这样,用户信息uri将返回主体对象,例如json。问题是您的端点在任何情况下都将返回null,因此您的服务收到了401。之所以会发生这种情况,是因为您的身份验证服务器只能返回令牌,而不能为了提供令牌而公开非框架端点的其他服务。因为您需要返回用户信息,所以您需要一种公开资源的方法,因此您需要公开auth服务器,甚至像资源服务器一样。在jwt的情况下,它是无用的,因为令牌验证和用户信息将由令牌本身提供。用户信息将由jwt提供,并通过jwt密钥进行验证
恢复身份验证服务器将如下所示:
登录页面:
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" th:href="@{/webjars/bootstrap/3.3.7-1/css/bootstrap.css}"/>
<link rel="stylesheet" th:href="@{/webjars/bootstrap/3.3.7-1/css/bootstrap-theme.css}"/>
<title>Log In</title>
</head>
<body>
<div class="container">
<form role="form" action="login" method="post">
<div class="row">
<div class="form-group">
<div class="col-md-6 col-lg-6 col-md-offset-2 col-lg-offset-">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username"/>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-6 col-lg-6 col-md-offset-2 col-lg-offset-2">
<label for="password">Password:</label>
<input type="password" class="form-control" id="password" name="password"/>
</div>
</div>
</div>
<div class="row">
<div class="col-md-offset-2 col-lg-offset-2 col-lg-12">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
</div>
<script th:src="@{/webjars/jquery/3.2.0/jquery.min.js}"></script>
<script th:src="@{/webjars/bootstrap/3.3.7-1/js/bootstrap.js}" ></script>
</body>
</html>
您的sso服务器将如下所示:
@EnableOAuth2Sso
@EnableZuulProxy
@SpringBootApplication
public class SsoDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SsoDemoApplication.class, args);
}
@Bean
@Primary
public OAuth2RestTemplate oAuth2RestTemplate(OAuth2ClientContext context,
OAuth2ProtectedResourceDetails authorizationCodeResourceDetails) {
return new OAuth2RestTemplate(authorizationCodeResourceDetails, context);
}
}
关于以下内容的简单页面:
您的hello服务资源服务器将是:
我希望它能对您有用我建议您使用该网站的gradle配置和授权服务器。配置如下所示:
buildscript {
ext {
springBootVersion = '2.0.3.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
ext {
springCloudVersion = 'Finchley.RELEASE'
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.cloud:spring-cloud-starter-oauth2')
compile('org.springframework.cloud:spring-cloud-starter-security')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
@Configuration
@EnableAuthorizationServer
public class SecurityOAuth2AutorizationServerConfig extends AuthorizationServerConfigurerAdapter {
private final AccountUserDetailsService accountUserDetailsService;
private final UserDetailsService authenticationManager;
private final PasswordEncoder passwordEncoder;
public SecurityOAuth2AutorizationServerConfig(UserDetailsService accountUserDetailsService,
AuthenticationManager authenticationManager,
PasswordEncoder passwordEncoder) {
this.accountUserDetailsService = accountUserDetailsService;
this.authenticationManager = authenticationManager;
this.passwordEncoder = passwordEncoder;
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.approvalStoreDisabled()
.authenticationManager(authenticationManager)
.tokenStore(tokenStore())
.accessTokenConverter(accessTokenConverter())
.userDetailsService(accountUserDetailsService)
.reuseRefreshTokens(false);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
oauthServer.tokenKeyAccess("permitAll()")
.passwordEncoder(passwordEncoder)
.checkTokenAccess("isAuthenticated()")
.allowFormAuthenticationForClients();
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("client")
.secret(passwordEncoder.encode("secret"))
.authorizedGrantTypes("authorization_code", "refresh_token", "password").scopes("openid")
.authorities("ROLE_USER", "ROLE_EMPLOYEE")
.scopes("read", "write", "trust", "openid")
.resourceIds("oauth2-resource")
.autoApprove(true)
.accessTokenValiditySeconds(5)
.refreshTokenValiditySeconds(60*60*8);
}
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
....
}
}
@EnableResourceServer
@SpringBootApplication
public class AccountServiceApplication {
public static void main(String[] args) {
SpringApplication.run(AccountServiceApplication.class, args);
}
}
然后,身份验证服务器将如下所示:
buildscript {
ext {
springBootVersion = '2.0.3.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
ext {
springCloudVersion = 'Finchley.RELEASE'
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.cloud:spring-cloud-starter-oauth2')
compile('org.springframework.cloud:spring-cloud-starter-security')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
@Configuration
@EnableAuthorizationServer
public class SecurityOAuth2AutorizationServerConfig extends AuthorizationServerConfigurerAdapter {
private final AccountUserDetailsService accountUserDetailsService;
private final UserDetailsService authenticationManager;
private final PasswordEncoder passwordEncoder;
public SecurityOAuth2AutorizationServerConfig(UserDetailsService accountUserDetailsService,
AuthenticationManager authenticationManager,
PasswordEncoder passwordEncoder) {
this.accountUserDetailsService = accountUserDetailsService;
this.authenticationManager = authenticationManager;
this.passwordEncoder = passwordEncoder;
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.approvalStoreDisabled()
.authenticationManager(authenticationManager)
.tokenStore(tokenStore())
.accessTokenConverter(accessTokenConverter())
.userDetailsService(accountUserDetailsService)
.reuseRefreshTokens(false);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
oauthServer.tokenKeyAccess("permitAll()")
.passwordEncoder(passwordEncoder)
.checkTokenAccess("isAuthenticated()")
.allowFormAuthenticationForClients();
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("client")
.secret(passwordEncoder.encode("secret"))
.authorizedGrantTypes("authorization_code", "refresh_token", "password").scopes("openid")
.authorities("ROLE_USER", "ROLE_EMPLOYEE")
.scopes("read", "write", "trust", "openid")
.resourceIds("oauth2-resource")
.autoApprove(true)
.accessTokenValiditySeconds(5)
.refreshTokenValiditySeconds(60*60*8);
}
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
....
}
}
@EnableResourceServer
@SpringBootApplication
public class AccountServiceApplication {
public static void main(String[] args) {
SpringApplication.run(AccountServiceApplication.class, args);
}
}
sso登录页面的配置如下所示:
@Configuration
@Order(SecurityProperties.DEFAULT_FILTER_ORDER)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.formLogin()
.permitAll()
.and()
.authorizeRequests().anyRequest().authenticated();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public UserDetailsService accountUserDetailsService() {
InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
inMemoryUserDetailsManager.createUser(new User("user", "secret",
Collections.singleton(new SimpleGrantedAuthority("USER"))));
return inMemoryUserDetailsManager;
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
在sso应用程序中,您可以进行如下配置:
@EnableOAuth2Sso
@EnableZuulProxy
@SpringBootApplication
public class SsoDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SsoDemoApplication.class, args);
}
@Bean
@Primary
public OAuth2RestTemplate oAuth2RestTemplate(OAuth2ClientContext context,
OAuth2ProtectedResourceDetails authorizationCodeResourceDetails) {
return new OAuth2RestTemplate(authorizationCodeResourceDetails, context);
}
}
在application.yml中:
security:
oauth2:
client:
clientId: client
clientSecret: secret
accessTokenUri: http://localhost:9090/auth/oauth/token
userAuthorizationUri: http://localhost:9090/auth/oauth/authorize
auto-approve-scopes: '.*'
registered-redirect-uri: http://localhost:9090/auth/singin
clientAuthenticationScheme: form
resource:
jwt:
key-value: -----BEGIN PUBLIC KEY-----
......
-----END PUBLIC KEY-----
server:
use-forward-headers: true
zuul:
sensitiveHeaders:
ignoredServices: '*'
ignoreSecurityHeaders: false
addHostHeader: true
routes:
your-service: /your-service/**
proxy:
auth:
routes:
spent-budget-service: oauth2
security:
oauth2:
resource:
jwt:
key-value: -----BEGIN PUBLIC KEY-----
.....
-----END PUBLIC KEY----
server:
use-forward-headers: true
port: 9090
servlet:
context-path: /auth
management.endpoints.web.exposure.include: "*"
spring:
application:
name: authentication-server
security:
oauth2:
client:
clientId: client
clientSecret: secret
accessTokenUri: http://localhost:9090/auth/oauth/token
userAuthorizationUri: http://localhost:9090/auth/oauth/authorize
auto-approve-scopes: '.*'
registered-redirect-uri: http://localhost:9090/auth/login
clientAuthenticationScheme: form
resource:
user-info-uri: http://localhost:9090/auth/account/user-info
prefer-token-info: false
management.endpoints.web.exposure.include: "*"
server:
use-forward-headers: true
port: 8080
zuul:
sensitiveHeaders:
ignoredServices: '*'
ignoreSecurityHeaders: false
addHostHeader: true
routes:
hello-service:
serviceId: hello-service
path: /hello-service/**
url: http://localhost:4040/
proxy:
auth:
routes:
hello-service: oauth2
security:
oauth2:
client:
clientId: client
clientSecret: secret
accessTokenUri: http://localhost:9977/auth/oauth/token
userAuthorizationUri: http://localhost:9977/auth/oauth/authorize
auto-approve-scopes: '.*'
registered-redirect-uri: http://localhost:9977/auth/singin
clientAuthenticationScheme: form
resource:
token-info-uri: http://localhost:9977/oauth/check_token
preferTokenInfo: false
server:
use-forward-headers: true
port: 9977
zuul:
sensitiveHeaders:
ignoredServices: '*'
ignoreSecurityHeaders: false
addHostHeader: true
routes:
service:
url: http://localhost:8080
proxy:
auth:
routes:
service: oauth2
spring:
application:
name: service
security:
oauth2:
resource:
token-info-uri: http://localhost:9977/oauth/check_token
preferTokenInfo: false
通过这种方式,您可以使用身份验证服务器在sso中配置您的客户端应用程序@EnableOAuth2Sso将为您做任何事情它也类似于客户端应用程序,如果您的应用程序未经身份验证,您的sso将在您的身份验证服务器的登录页面上重定向您,并为您刷新您的令牌zuul令牌中继也可用在这个用例中,我使用eureka作为发现服务注册中心。配置OAuth2RestTemplate非常重要,因为spring将使用此bean为您自动刷新令牌,否则一旦令牌过期,您将无法自动刷新令牌
您的所有resourceserver将如下所示:
buildscript {
ext {
springBootVersion = '2.0.3.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
ext {
springCloudVersion = 'Finchley.RELEASE'
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.cloud:spring-cloud-starter-oauth2')
compile('org.springframework.cloud:spring-cloud-starter-security')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
@Configuration
@EnableAuthorizationServer
public class SecurityOAuth2AutorizationServerConfig extends AuthorizationServerConfigurerAdapter {
private final AccountUserDetailsService accountUserDetailsService;
private final UserDetailsService authenticationManager;
private final PasswordEncoder passwordEncoder;
public SecurityOAuth2AutorizationServerConfig(UserDetailsService accountUserDetailsService,
AuthenticationManager authenticationManager,
PasswordEncoder passwordEncoder) {
this.accountUserDetailsService = accountUserDetailsService;
this.authenticationManager = authenticationManager;
this.passwordEncoder = passwordEncoder;
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.approvalStoreDisabled()
.authenticationManager(authenticationManager)
.tokenStore(tokenStore())
.accessTokenConverter(accessTokenConverter())
.userDetailsService(accountUserDetailsService)
.reuseRefreshTokens(false);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
oauthServer.tokenKeyAccess("permitAll()")
.passwordEncoder(passwordEncoder)
.checkTokenAccess("isAuthenticated()")
.allowFormAuthenticationForClients();
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("client")
.secret(passwordEncoder.encode("secret"))
.authorizedGrantTypes("authorization_code", "refresh_token", "password").scopes("openid")
.authorities("ROLE_USER", "ROLE_EMPLOYEE")
.scopes("read", "write", "trust", "openid")
.resourceIds("oauth2-resource")
.autoApprove(true)
.accessTokenValiditySeconds(5)
.refreshTokenValiditySeconds(60*60*8);
}
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
....
}
}
@EnableResourceServer
@SpringBootApplication
public class AccountServiceApplication {
public static void main(String[] args) {
SpringApplication.run(AccountServiceApplication.class, args);
}
}
在application.yml中:
security:
oauth2:
client:
clientId: client
clientSecret: secret
accessTokenUri: http://localhost:9090/auth/oauth/token
userAuthorizationUri: http://localhost:9090/auth/oauth/authorize
auto-approve-scopes: '.*'
registered-redirect-uri: http://localhost:9090/auth/singin
clientAuthenticationScheme: form
resource:
jwt:
key-value: -----BEGIN PUBLIC KEY-----
......
-----END PUBLIC KEY-----
server:
use-forward-headers: true
zuul:
sensitiveHeaders:
ignoredServices: '*'
ignoreSecurityHeaders: false
addHostHeader: true
routes:
your-service: /your-service/**
proxy:
auth:
routes:
spent-budget-service: oauth2
security:
oauth2:
resource:
jwt:
key-value: -----BEGIN PUBLIC KEY-----
.....
-----END PUBLIC KEY----
server:
use-forward-headers: true
port: 9090
servlet:
context-path: /auth
management.endpoints.web.exposure.include: "*"
spring:
application:
name: authentication-server
security:
oauth2:
client:
clientId: client
clientSecret: secret
accessTokenUri: http://localhost:9090/auth/oauth/token
userAuthorizationUri: http://localhost:9090/auth/oauth/authorize
auto-approve-scopes: '.*'
registered-redirect-uri: http://localhost:9090/auth/login
clientAuthenticationScheme: form
resource:
user-info-uri: http://localhost:9090/auth/account/user-info
prefer-token-info: false
management.endpoints.web.exposure.include: "*"
server:
use-forward-headers: true
port: 8080
zuul:
sensitiveHeaders:
ignoredServices: '*'
ignoreSecurityHeaders: false
addHostHeader: true
routes:
hello-service:
serviceId: hello-service
path: /hello-service/**
url: http://localhost:4040/
proxy:
auth:
routes:
hello-service: oauth2
security:
oauth2:
client:
clientId: client
clientSecret: secret
accessTokenUri: http://localhost:9977/auth/oauth/token
userAuthorizationUri: http://localhost:9977/auth/oauth/authorize
auto-approve-scopes: '.*'
registered-redirect-uri: http://localhost:9977/auth/singin
clientAuthenticationScheme: form
resource:
token-info-uri: http://localhost:9977/oauth/check_token
preferTokenInfo: false
server:
use-forward-headers: true
port: 9977
zuul:
sensitiveHeaders:
ignoredServices: '*'
ignoreSecurityHeaders: false
addHostHeader: true
routes:
service:
url: http://localhost:8080
proxy:
auth:
routes:
service: oauth2
spring:
application:
name: service
security:
oauth2:
resource:
token-info-uri: http://localhost:9977/oauth/check_token
preferTokenInfo: false
-
当然,这是一个非常简单的配置,但id足够用于启动
更新:
不要忘记网关、sso和任何其他资源服务器上的应用程序yml中的资源配置,否则将无法针对身份验证服务器验证令牌
对于普通oauth2令牌,您可以使用
security.oauth2.resource.token-info-uri: your/auth/server:yourport/oauth/check_token
或
如果preferTokenInfo:false,则验证服务器上的典型帐户数据入口点
@RestController
@RequestMapping("/account")
class UserRestFullEndPoint {
@GetMapping("/userInfo")
public Principal userInfo(Principal principal){
return principal;
}
}
如果是令牌信息uri配置,那么UserInfoRestTemplateFactory将由spring自动提供。唯一要记住的是配置Oauth2RestTemplate,否则您的
oken将不再刷新
更新2
对于非JWT令牌,缺少的配置是添加
身份验证服务器上的@EnableResourceServer
这样,用户信息uri将返回主体对象,例如json。问题是您的端点在任何情况下都将返回null,因此您的服务收到了401。之所以会发生这种情况,是因为您的身份验证服务器只能返回令牌,而不能为了提供令牌而公开非框架端点的其他服务。因为您需要返回用户信息,所以您需要一种公开资源的方法,因此您需要公开auth服务器,甚至像资源服务器一样。在jwt的情况下,它是无用的,因为令牌验证和用户信息将由令牌本身提供。用户信息将由jwt提供,并通过jwt密钥进行验证
恢复身份验证服务器将如下所示:
登录页面:
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" th:href="@{/webjars/bootstrap/3.3.7-1/css/bootstrap.css}"/>
<link rel="stylesheet" th:href="@{/webjars/bootstrap/3.3.7-1/css/bootstrap-theme.css}"/>
<title>Log In</title>
</head>
<body>
<div class="container">
<form role="form" action="login" method="post">
<div class="row">
<div class="form-group">
<div class="col-md-6 col-lg-6 col-md-offset-2 col-lg-offset-">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username"/>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-6 col-lg-6 col-md-offset-2 col-lg-offset-2">
<label for="password">Password:</label>
<input type="password" class="form-control" id="password" name="password"/>
</div>
</div>
</div>
<div class="row">
<div class="col-md-offset-2 col-lg-offset-2 col-lg-12">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
</div>
<script th:src="@{/webjars/jquery/3.2.0/jquery.min.js}"></script>
<script th:src="@{/webjars/bootstrap/3.3.7-1/js/bootstrap.js}" ></script>
</body>
</html>
您的sso服务器将如下所示:
@EnableOAuth2Sso
@EnableZuulProxy
@SpringBootApplication
public class SsoDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SsoDemoApplication.class, args);
}
@Bean
@Primary
public OAuth2RestTemplate oAuth2RestTemplate(OAuth2ClientContext context,
OAuth2ProtectedResourceDetails authorizationCodeResourceDetails) {
return new OAuth2RestTemplate(authorizationCodeResourceDetails, context);
}
}
关于以下内容的简单页面:
您的hello服务资源服务器将是:
我希望它能对你有用谢谢你的快速回答。我很难让它工作。也许你还有一个好主意。 我无权在上访问我的资源。 我的服务器和Zuul代码: application.yml:
security:
oauth2:
client:
clientId: client
clientSecret: secret
accessTokenUri: http://localhost:9090/auth/oauth/token
userAuthorizationUri: http://localhost:9090/auth/oauth/authorize
auto-approve-scopes: '.*'
registered-redirect-uri: http://localhost:9090/auth/singin
clientAuthenticationScheme: form
resource:
jwt:
key-value: -----BEGIN PUBLIC KEY-----
......
-----END PUBLIC KEY-----
server:
use-forward-headers: true
zuul:
sensitiveHeaders:
ignoredServices: '*'
ignoreSecurityHeaders: false
addHostHeader: true
routes:
your-service: /your-service/**
proxy:
auth:
routes:
spent-budget-service: oauth2
security:
oauth2:
resource:
jwt:
key-value: -----BEGIN PUBLIC KEY-----
.....
-----END PUBLIC KEY----
server:
use-forward-headers: true
port: 9090
servlet:
context-path: /auth
management.endpoints.web.exposure.include: "*"
spring:
application:
name: authentication-server
security:
oauth2:
client:
clientId: client
clientSecret: secret
accessTokenUri: http://localhost:9090/auth/oauth/token
userAuthorizationUri: http://localhost:9090/auth/oauth/authorize
auto-approve-scopes: '.*'
registered-redirect-uri: http://localhost:9090/auth/login
clientAuthenticationScheme: form
resource:
user-info-uri: http://localhost:9090/auth/account/user-info
prefer-token-info: false
management.endpoints.web.exposure.include: "*"
server:
use-forward-headers: true
port: 8080
zuul:
sensitiveHeaders:
ignoredServices: '*'
ignoreSecurityHeaders: false
addHostHeader: true
routes:
hello-service:
serviceId: hello-service
path: /hello-service/**
url: http://localhost:4040/
proxy:
auth:
routes:
hello-service: oauth2
security:
oauth2:
client:
clientId: client
clientSecret: secret
accessTokenUri: http://localhost:9977/auth/oauth/token
userAuthorizationUri: http://localhost:9977/auth/oauth/authorize
auto-approve-scopes: '.*'
registered-redirect-uri: http://localhost:9977/auth/singin
clientAuthenticationScheme: form
resource:
token-info-uri: http://localhost:9977/oauth/check_token
preferTokenInfo: false
server:
use-forward-headers: true
port: 9977
zuul:
sensitiveHeaders:
ignoredServices: '*'
ignoreSecurityHeaders: false
addHostHeader: true
routes:
service:
url: http://localhost:8080
proxy:
auth:
routes:
service: oauth2
spring:
application:
name: service
security:
oauth2:
resource:
token-info-uri: http://localhost:9977/oauth/check_token
preferTokenInfo: false
资源服务器:
application.yml:
security:
oauth2:
client:
clientId: client
clientSecret: secret
accessTokenUri: http://localhost:9090/auth/oauth/token
userAuthorizationUri: http://localhost:9090/auth/oauth/authorize
auto-approve-scopes: '.*'
registered-redirect-uri: http://localhost:9090/auth/singin
clientAuthenticationScheme: form
resource:
jwt:
key-value: -----BEGIN PUBLIC KEY-----
......
-----END PUBLIC KEY-----
server:
use-forward-headers: true
zuul:
sensitiveHeaders:
ignoredServices: '*'
ignoreSecurityHeaders: false
addHostHeader: true
routes:
your-service: /your-service/**
proxy:
auth:
routes:
spent-budget-service: oauth2
security:
oauth2:
resource:
jwt:
key-value: -----BEGIN PUBLIC KEY-----
.....
-----END PUBLIC KEY----
server:
use-forward-headers: true
port: 9090
servlet:
context-path: /auth
management.endpoints.web.exposure.include: "*"
spring:
application:
name: authentication-server
security:
oauth2:
client:
clientId: client
clientSecret: secret
accessTokenUri: http://localhost:9090/auth/oauth/token
userAuthorizationUri: http://localhost:9090/auth/oauth/authorize
auto-approve-scopes: '.*'
registered-redirect-uri: http://localhost:9090/auth/login
clientAuthenticationScheme: form
resource:
user-info-uri: http://localhost:9090/auth/account/user-info
prefer-token-info: false
management.endpoints.web.exposure.include: "*"
server:
use-forward-headers: true
port: 8080
zuul:
sensitiveHeaders:
ignoredServices: '*'
ignoreSecurityHeaders: false
addHostHeader: true
routes:
hello-service:
serviceId: hello-service
path: /hello-service/**
url: http://localhost:4040/
proxy:
auth:
routes:
hello-service: oauth2
security:
oauth2:
client:
clientId: client
clientSecret: secret
accessTokenUri: http://localhost:9977/auth/oauth/token
userAuthorizationUri: http://localhost:9977/auth/oauth/authorize
auto-approve-scopes: '.*'
registered-redirect-uri: http://localhost:9977/auth/singin
clientAuthenticationScheme: form
resource:
token-info-uri: http://localhost:9977/oauth/check_token
preferTokenInfo: false
server:
use-forward-headers: true
port: 9977
zuul:
sensitiveHeaders:
ignoredServices: '*'
ignoreSecurityHeaders: false
addHostHeader: true
routes:
service:
url: http://localhost:8080
proxy:
auth:
routes:
service: oauth2
spring:
application:
name: service
security:
oauth2:
resource:
token-info-uri: http://localhost:9977/oauth/check_token
preferTokenInfo: false
当我打电话时,服务器告诉我我未被授权。谢谢您的快速回复。我很难让它工作。也许你还有一个好主意。 我无权在上访问我的资源。 我的服务器和Zuul代码: application.yml:
security:
oauth2:
client:
clientId: client
clientSecret: secret
accessTokenUri: http://localhost:9090/auth/oauth/token
userAuthorizationUri: http://localhost:9090/auth/oauth/authorize
auto-approve-scopes: '.*'
registered-redirect-uri: http://localhost:9090/auth/singin
clientAuthenticationScheme: form
resource:
jwt:
key-value: -----BEGIN PUBLIC KEY-----
......
-----END PUBLIC KEY-----
server:
use-forward-headers: true
zuul:
sensitiveHeaders:
ignoredServices: '*'
ignoreSecurityHeaders: false
addHostHeader: true
routes:
your-service: /your-service/**
proxy:
auth:
routes:
spent-budget-service: oauth2
security:
oauth2:
resource:
jwt:
key-value: -----BEGIN PUBLIC KEY-----
.....
-----END PUBLIC KEY----
server:
use-forward-headers: true
port: 9090
servlet:
context-path: /auth
management.endpoints.web.exposure.include: "*"
spring:
application:
name: authentication-server
security:
oauth2:
client:
clientId: client
clientSecret: secret
accessTokenUri: http://localhost:9090/auth/oauth/token
userAuthorizationUri: http://localhost:9090/auth/oauth/authorize
auto-approve-scopes: '.*'
registered-redirect-uri: http://localhost:9090/auth/login
clientAuthenticationScheme: form
resource:
user-info-uri: http://localhost:9090/auth/account/user-info
prefer-token-info: false
management.endpoints.web.exposure.include: "*"
server:
use-forward-headers: true
port: 8080
zuul:
sensitiveHeaders:
ignoredServices: '*'
ignoreSecurityHeaders: false
addHostHeader: true
routes:
hello-service:
serviceId: hello-service
path: /hello-service/**
url: http://localhost:4040/
proxy:
auth:
routes:
hello-service: oauth2
security:
oauth2:
client:
clientId: client
clientSecret: secret
accessTokenUri: http://localhost:9977/auth/oauth/token
userAuthorizationUri: http://localhost:9977/auth/oauth/authorize
auto-approve-scopes: '.*'
registered-redirect-uri: http://localhost:9977/auth/singin
clientAuthenticationScheme: form
resource:
token-info-uri: http://localhost:9977/oauth/check_token
preferTokenInfo: false
server:
use-forward-headers: true
port: 9977
zuul:
sensitiveHeaders:
ignoredServices: '*'
ignoreSecurityHeaders: false
addHostHeader: true
routes:
service:
url: http://localhost:8080
proxy:
auth:
routes:
service: oauth2
spring:
application:
name: service
security:
oauth2:
resource:
token-info-uri: http://localhost:9977/oauth/check_token
preferTokenInfo: false
资源服务器:
application.yml:
security:
oauth2:
client:
clientId: client
clientSecret: secret
accessTokenUri: http://localhost:9090/auth/oauth/token
userAuthorizationUri: http://localhost:9090/auth/oauth/authorize
auto-approve-scopes: '.*'
registered-redirect-uri: http://localhost:9090/auth/singin
clientAuthenticationScheme: form
resource:
jwt:
key-value: -----BEGIN PUBLIC KEY-----
......
-----END PUBLIC KEY-----
server:
use-forward-headers: true
zuul:
sensitiveHeaders:
ignoredServices: '*'
ignoreSecurityHeaders: false
addHostHeader: true
routes:
your-service: /your-service/**
proxy:
auth:
routes:
spent-budget-service: oauth2
security:
oauth2:
resource:
jwt:
key-value: -----BEGIN PUBLIC KEY-----
.....
-----END PUBLIC KEY----
server:
use-forward-headers: true
port: 9090
servlet:
context-path: /auth
management.endpoints.web.exposure.include: "*"
spring:
application:
name: authentication-server
security:
oauth2:
client:
clientId: client
clientSecret: secret
accessTokenUri: http://localhost:9090/auth/oauth/token
userAuthorizationUri: http://localhost:9090/auth/oauth/authorize
auto-approve-scopes: '.*'
registered-redirect-uri: http://localhost:9090/auth/login
clientAuthenticationScheme: form
resource:
user-info-uri: http://localhost:9090/auth/account/user-info
prefer-token-info: false
management.endpoints.web.exposure.include: "*"
server:
use-forward-headers: true
port: 8080
zuul:
sensitiveHeaders:
ignoredServices: '*'
ignoreSecurityHeaders: false
addHostHeader: true
routes:
hello-service:
serviceId: hello-service
path: /hello-service/**
url: http://localhost:4040/
proxy:
auth:
routes:
hello-service: oauth2
security:
oauth2:
client:
clientId: client
clientSecret: secret
accessTokenUri: http://localhost:9977/auth/oauth/token
userAuthorizationUri: http://localhost:9977/auth/oauth/authorize
auto-approve-scopes: '.*'
registered-redirect-uri: http://localhost:9977/auth/singin
clientAuthenticationScheme: form
resource:
token-info-uri: http://localhost:9977/oauth/check_token
preferTokenInfo: false
server:
use-forward-headers: true
port: 9977
zuul:
sensitiveHeaders:
ignoredServices: '*'
ignoreSecurityHeaders: false
addHostHeader: true
routes:
service:
url: http://localhost:8080
proxy:
auth:
routes:
service: oauth2
spring:
application:
name: service
security:
oauth2:
resource:
token-info-uri: http://localhost:9977/oauth/check_token
preferTokenInfo: false
当我打电话时,服务器告诉我我未被授权。看到您的代码,我发现您不使用jwt令牌,否则我希望使用security.oauth2.resource.jwt.key-value valorized标记。在任何情况下,即使是在普通的oauth2令牌中,也必须在网关和任何资源服务器中配置security.oauth2.resource.token-info-uri:your/auth/server:yourport/oauth/check_令牌,因为否则sso和资源服务器无法验证您的令牌。无论如何,我已经更新了我的答案,以尝试解释如何克服您的令牌问题是,我删除了jwt令牌,以使其更简单。在我的“StackServerApplication”中,我添加了oauth/check_令牌Rest端点,并在yml文件中添加了“resource”标记,但是我在访问时仍然未经授权。您已经删除了UserInfoRestTemplateFactory,身份验证服务器上的@GetMapping/oauth/check_令牌应该映射到另一个路径上,因为此路径已由@FrameworkEndpoint实现。最好不要接触内部spring组件。这是我的解决方案的链接查看我看到的代码请不要使用jwt令牌,否则我希望使用security.oauth2.resource.jwt.key-value valorized标记。在任何情况下,即使是在普通的oauth2令牌中,也必须在网关和任何资源服务器中配置security.oauth2.resource.token-info-uri:your/auth/server:yourport/oauth/check_令牌,因为否则sso和资源服务器无法验证您的令牌。无论如何,我已经更新了我的答案,以尝试解释如何克服您的令牌问题是,我删除了jwt令牌,以使其更简单。在我的“StackServerApplication”中,我添加了oauth/check_令牌Rest端点,并在yml文件中添加了“resource”标记,但是我在访问时仍然未经授权。您已经删除了UserInfoRestTemplateFactory,身份验证服务器上的@GetMapping/oauth/check_令牌应该映射到另一个路径,因为此路径已由@FrameworkEndpoint实现。最好不要接触内部spring组件。这是我的解决方案的链接