用于安全微服务环境的最小设置

时间:2018-07-05 19:51:51

标签: spring-boot jwt single-sign-on api-gateway

我想使用Gradle,Spring Boot2,Zuul,JWT,带有REST-Api的微服务和自制的身份验证服务器来设置SSO微服务环境。 当身份验证服务器,网关和微服务充当OAuth客户端和资源服务器时,它们的注释是什么?什么是最小设置?

2 个答案:

答案 0 :(得分:5)

对于gradle配置,我建议使用网站http://start.spring.io/和授权服务器。配置如下:

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() {
        ....
    }
}

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

通过这种方式,您可以使用身份验证服务器在sso中配置客户端应用程序,@ EnableOAuth2Sso会为您执行任何操作,就像客户端应用程序一样,如果您的应用程序未通过身份验证,则sso将在的登录页面上重定向您您的身份验证服务器,并会为您刷新zuul令牌中继的令牌。在本使用案例中,它也可用作功能部件,我使用eureka作为发现服务注册表。配置OAuth2RestTemplate非常重要,因为spring将使用此Bean为您自动刷新令牌,否则,一旦令牌过期,您将无法自动刷新令牌。

您所有的资源服务器将如下所示:

@EnableResourceServer
@SpringBootApplication
public class AccountServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(AccountServiceApplication.class, args);
    }
}

在您的application.yml中:

 security:
  oauth2:
    resource:
      jwt:
        key-value: -----BEGIN PUBLIC KEY-----
   .....
                   -----END PUBLIC KEY----

-

当然,这是一个非常小的配置,但对于启动来说它的ID足够

更新:

不要忘记网关,sso和任何其他资源服务器上的yml应用程序中的资源配置,因为否则将无法针对您的身份验证服务器验证令牌。

如果使用普通的oauth2令牌,则可以使用

security.oauth2.resource.token-info-uri: your/auth/server:yourport/oauth/check_token 

security.oauth2.resource.user-info-uri: yourAccountDEtailsRndpoint/userInfo.json
security.oauth2.resource.preferTokenInfo: false

在您偏好的令牌信息为false的情况下,您在身份验证服务器上的典型帐户数据入口点。

@RestController
@RequestMapping("/account")
class UserRestFullEndPoint {

    @GetMapping("/userInfo")
    public Principal userInfo(Principal principal){
        return principal;
    }
}

在春季将自动提供token-info-uri配置的情况下的UserInfoRestTemplateFactory,唯一要记住的是配置Oauth2RestTemplate,因为否则您的令牌将不再刷新

更新2

如果是非JWT令牌,则缺少配置 身份验证服务器上的@EnableResourceServer。

通过这种方式,您的用户信息uri将返回主体对象,例如json。听到的问题是,无论如何您的端点都将返回null,因此您的服务收到401。这是因为您的身份验证服务器只能返回令牌,而无法公开不是框架端点的其他服务来提供令牌。由于您需要返回用户信息,因此需要一种公开资源的方法,因此,即使像资源服务器一样,也需要公开身份验证服务器。在jwt的情况下,它是没有用的,因为令牌验证和用户信息将由令牌本身提供。用户信息将由jwt提供,并由jwt密钥提供验证。

恢复您的身份验证服务器如下:

@SpringBootApplication
public class AuthserverApplication {

    public static void main(String[] args) {
        SpringApplication.run(AuthserverApplication.class, args);
    }
}

@RestController
class UserInfo {

    @GetMapping("/account/user-info")
    public Principal principal(Principal principal){
        System.out.println(principal);
        return principal;
    }

}

@Controller
class Login{

    @GetMapping(value = "/login", produces = "application/json")
    public String login(){
        return "login";
    }
}

@Configuration
@EnableAuthorizationServer
@EnableResourceServer
class SecurityOAuth2AutorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.authenticationManager(authenticationManager)
                .approvalStoreDisabled()
                .reuseRefreshTokens(false)
                .userDetailsService(accountUserDetailsService());
    }

    @Bean
    public UserDetailsService accountUserDetailsService() {
        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
        inMemoryUserDetailsManager.createUser(new User("user", passwordEncoder.encode("secret"),
                Collections.singleton(new SimpleGrantedAuthority("USER"))));

        return inMemoryUserDetailsManager;
    }

    @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("client_credentials", "password", "authorization_code", "refresh_token", "implicit")
                .authorities("ROLE_USER", "ROLE_EMPLOYEE")
                .scopes("read", "write", "trust", "openid")
                .autoApprove(true)
                .refreshTokenValiditySeconds(20000000)
                .accessTokenValiditySeconds(20000000);
    }

}

@Configuration
@Order(SecurityProperties.DEFAULT_FILTER_ORDER)
class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().httpBasic().disable()
                .formLogin().loginPage("/login").loginProcessingUrl("/login")
                .permitAll()
                .and()
                .requestMatchers().antMatchers("/account/userInfo", "/login", "/oauth/authorize", "/oauth/confirm_access")
                .and()
                .authorizeRequests().anyRequest().authenticated();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}

登录页面:

<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>

application.yml:

server:
  use-forward-headers: true
  port: 9090
  servlet:
    context-path: /auth


management.endpoints.web.exposure.include: "*"

spring:
  application:
    name: authentication-server

您的sso服务器将如下所示:

@EnableZuulProxy
@SpringBootApplication
public class SsoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SsoApplication.class, args);
    }

    @Bean
    public OAuth2RestTemplate oAuth2RestTemplate(OAuth2ClientContext context,
                                                 OAuth2ProtectedResourceDetails authorizationCodeResourceDetails) {
        return new OAuth2RestTemplate(authorizationCodeResourceDetails, context);
    }
}



@Configuration
@EnableOAuth2Sso
class OAuth2SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().cors().and().httpBasic().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                .and()
                .authorizeRequests().anyRequest().authenticated();
    }
}

http://localhost:8080/index.html上的简单页面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

It Works by an SSO

<script src="https://code.jquery.com/jquery-3.3.1.min.js"
        integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
        crossorigin="anonymous"></script>

<script>
    $.ajax({
        url: "/hello-service/hello",
        success: function (data, status) {
            window.alert("The returned data" + data);
        }
    })

</script>
</body>
</html>

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/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

您好的服务(资源服务器)将是:

@SpringBootApplication
public class ResourceServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ResourceServerApplication.class, args);
    }

}

@RestController
class HelloService {

    @GetMapping("/hello")
    public ResponseEntity hello(){
        return ResponseEntity.ok("Hello World!!!");
    }
}



@Configuration
@EnableResourceServer
class SecurityOAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().anyRequest().authenticated()
                .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
    }

}

我希望它对您有用

答案 1 :(得分:0)

感谢您的快速答复。我在使其工作时遇到问题。也许您有另一个好主意。 我无权访问“ http://localhost:9977/service/home”上的资源。 我的服务器和Zuul代码:

@EnableOAuth2Sso
@EnableZuulProxy
@SpringBootApplication
@RestController
public class StackServerApplication {

    @GetMapping("/oauth/check_token")
    public java.security.Principal userInfo(Principal principal){
        return principal;
    }

    @Autowired
    private OAuth2RestTemplate userInfoRestTemplate;

    public static void main(String[] args) {
        SpringApplication.run(StackServerApplication.class, args);
    }

    @Bean
    @Primary
    public OAuth2RestTemplate oAuth2RestTemplate(OAuth2ClientContext context,
            OAuth2ProtectedResourceDetails authorizationCodeResourceDetails) {
        return new OAuth2RestTemplate(authorizationCodeResourceDetails, context);
    }

    @Bean
    public UserInfoRestTemplateFactory userInfoRestTemplateFactory() {
        return new UserInfoRestTemplateFactory() {

            @Override
            public OAuth2RestTemplate getUserInfoRestTemplate() {
                return userInfoRestTemplate;
            }
        };
    }
}

application.yml:

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

资源服务器:

@EnableResourceServer
@SpringBootApplication
public class StackResourceApplication {

    public static void main(String[] args) {
        SpringApplication.run(StackResourceApplication.class, args);
    }

    @RestController
    public class ServiceController {

        @GetMapping("/home")
        public String home() {
            return "Hermie";
        }            
    }
}

application.yml:

spring:
  application:
    name: service
security:
  oauth2:
    resource:
      token-info-uri: http://localhost:9977/oauth/check_token  
      preferTokenInfo: false

当我呼叫“ http://localhost:9977/service/home”时,服务器告诉我我未被授权。