要解决的问题:不暴露客户密码的情况下授权三方服务访问客户资源

    角色:资源拥有者,客户端应用(三方服务),授权服务器,资源服务器

    模式:授权码模式:需要客户授权得到授权码后再次通过三方服务的密码取得token,双重校验,最安全,最复杂

               简易模式:无需授权码对用户暴露返回的Token,不安全

               密码模式:客户端应用需要资源拥有者密码。全链路可信情况下使用

               客户端模式:无需资源拥有者密码,只需要客户端应用密码进行校验,服务器对服务器使用

       本试验主要演示注册码模式,分为授权服务器和资源服务器俩个应用,后续会持续扩展为单个授权服务器和多个资源服务器。

试验步骤

按照以下截图创建授权服务器,授权服务器包结构如下

使用SpringSecurity 实现 OAuth2 资源服务器认证服务器分离( 注册码模式)_SpringSecurity

1 使用pom文件导入相应依赖,主要导入了以下依赖包

1)SpringBoot的security和web,

2)SpringSecurity的OAuth2

pom文件如下

 

4.0.0io.spring2goauthcode-server0.0.1-SNAPSHOTjarauthcode-serverDemo project for Spring Bootorg.springframework.bootspring-boot-starter-parent1.5.10.RELEASEUTF-8UTF-81.8org.springframework.bootspring-boot-starter-securityorg.springframework.bootspring-boot-starter-web        org.springframework.security.oauthspring-security-oauth2org.springframework.bootspring-boot-starter-testtestorg.springframework.securityspring-security-testtestorg.springframework.bootspring-boot-maven-plugin

2 修改application.properties设置用户登录密码

 

# Spring Security =bobo
security.user.password=xyz

3 制作SpringBoot的启动文件

 

package com.test.authcodeserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

4 设置授权服务代码

 


package com.test.authcodeserver.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
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.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;

@Configuration
@EnableAuthorizationServer
public class AuthCodeServerConfig extends AuthorizationServerConfigurerAdapter {
@Override
    public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
    }
    @Override
    public void configure(ClientDetailsServiceConfigurer clients)
            throws Exception {        //JdbcClientDetailsService可以动态管理数据库中客户端数据        //http://localhost:8080/oauth/authorize?client_id=testclientid&redirect_uri=http://localhost:9001/authCodeCallback&response_type=code&scope=read_userinfoclients.inMemory()
                .withClient("testclientid")//clientId:(必须的)用来标识客户的Id。.secret("1234")//secret:(需要值得信任的客户端)客户端安全码,如果有的话。.redirectUris("http://localhost:9001/authCodeCallback")//客户端应用负责获取授权码的endpoint.authorizedGrantTypes("authorization_code")// 授权码模式.scopes("read_userinfo", "read_contacts");//scope:用来限制客户端的访问范围,如果为空(默认)的话,那么客户端拥有全部的访问范围。}

}

5 启动SpringBoot服务

6 客户端服务访问授权服务器,铜鼓访问如下url取得授权码

http://localhost:8080/oauth/authorize?client_id=testclientid&redirect_uri=http://localhost:9001/authCodeCallback&response_type=code&scope=read_userinfo

使用SpringSecurity 实现 OAuth2 资源服务器认证服务器分离( 注册码模式)_SpringSecurity_02

访问完成后会redirect回客户端服务器并将授权码作为参数传回,其中localhost:9001即为客户端应用

使用SpringSecurity 实现 OAuth2 资源服务器认证服务器分离( 注册码模式)_SpringSecurity_03

7 客户端使用返回的授权码获取访问令牌

使用SpringSecurity 实现 OAuth2 资源服务器认证服务器分离( 注册码模式)_SpringSecurity_04

使用SpringSecurity 实现 OAuth2 资源服务器认证服务器分离( 注册码模式)_SpringSecurity_05

发送请求参数如下

url:http://localhost:8080/oauth/token

code=ifz2BV&grant_type=authorization_code&redirect_uri=http%3A%2F%2Flocalhost%3A9001%2FauthCodeCallback&scope=read_userinfo

得到的令牌数据

 

{

access_token: "554338cd-cab0-4ba0-b5bf-3ebd55db3196"

token_type: "bearer"

expires_in: 43199

scope: "read_userinfo"

}

以上授权服务器就简单完成了,下面将制作资源服务器

 

--------------------------------------------------------------------------------------------------

 

资源服务器

0 资源服务器的包结构

使用SpringSecurity 实现 OAuth2 资源服务器认证服务器分离( 注册码模式)_SpringSecurity_06

1 资源服务器配置,使用RemoteTokenServices调取认证服务器的认证方法来对Token进行认证

 

package com.test.resourceserver.config;

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.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;//资源服务配置@Configuration
@EnableResourceServer
public class OAuth2ResourceConfig extends ResourceServerConfigurerAdapter {

    @Primary
    @Bean
    public RemoteTokenServices tokenServices() {
        final RemoteTokenServices tokenService = new RemoteTokenServices();
        tokenService.setCheckTokenEndpointUrl("http://localhost:8080/oauth/check_token");
        tokenService.setClientId("testclientid");
        tokenService.setClientSecret("1234");
        return tokenService;
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {//        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)//                .and()//                .authorizeRequests()//                .anyRequest()//                .authenticated()//                .and()//                .requestMatchers()//                .antMatchers("/api/**");http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                .and()
                .authorizeRequests().anyRequest().permitAll();
    }
}


2 提供对外的API接口

 

package com.test.resourceserver.api;

import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class UserController {   // 资源API@RequestMapping("/api/userinfo")
    public ResponseEntitygetUserInfo() {

        String  user  = (String) SecurityContextHolder.getContext()
                .getAuthentication().getPrincipal();
        String email = user+ "@";
        UserInfo userInfo = new UserInfo();
        userInfo.setName(user);
        userInfo.setEmail(email);
        return ResponseEntity.ok(userInfo);
    }

}

调用getUserInfo

http://localhost:8004/api/userinfo 

authorization: Bearer 638aa01c-4ccd-4873-ab86-d46f22aea091

使用SpringSecurity 实现 OAuth2 资源服务器认证服务器分离( 注册码模式)_SpringSecurity_07

调用后返回资源服务器的结果

使用SpringSecurity 实现 OAuth2 资源服务器认证服务器分离( 注册码模式)_SpringSecurity_08

至此一个资源服务器和认证服务器分离的资源调用就结束了。