SpringBoot学习笔记(十五:OAuth2 )

@html


1、OAuth 简介


在这里插入图片描述

一、什么是OAuth

开放受权(Open Authorization,OAuth)是一种资源提供商用于受权第三方应用表明资源全部者获取有限访问权限的受权机制。因为在整个受权过程当中,第三方应用都无须触及用户的密码就能够取得部分资源的使用权限,因此OAuth是安全开放的。前端

例如,用户想经过 QQ 登陆csdn,这时csdn就是一个第三方应用,csdn要访问用户的一些基本信息就须要获得用户的受权,若是用户把本身的 QQ 用户名和密码告诉csdn,那么csdn就能访问用户的全部数据,井且只有用户修改密码才能收回受权,这种受权方式安全隐患很大,若是使用 OAuth ,就能很好地解决这一问题。java

在这里插入图片描述

OAuth第一个版本诞生于2007年12月,并于2010年4月正式被IETF做为标准发布(编号RFC 5849)。因为OAuth1.0复杂的签名逻辑以及单一的受权流程存在较大缺陷,随后标准工做组又推出了 OAuth2.0草案,并在2012年10月正式发布其标准(编号RFC 6749)。OAuth2.0放弃了OAuth1.0中让开发者感到痛苦的数字签名和加密方案,使用已经获得验证并普遍使用的HTTPS技术做为安全保障手 段。OAuth2.0与OAuth1.0互不兼容,因为OAuth1.0已经基本退出历史舞台,因此下面提到的OAuth都是指OAuth2.0。git


二、OAuth 角色

想要理解OAuth的运行流程,则必需要认识4个重要的角色。github

  • Resource Owner:资源全部者,一般指用户,例如每个QQ用户。
  • Resource Server:资源服务器,指存放用户受保护资源的服务器,一般须要经过Access Token(访问令牌)才能进行访问。例如,存储QQ用户基本信息的服务器,充当的即是资源服务器的 角色。
  • Client:客户端,指须要获取用户资源的第三方应用,如CSDN网站。
  • Authorization Server:受权服务器,用于验证资源全部者,并在验证成功以后向客户端发放相关访问令牌。

三、OAuth 受权流程

这是 个大体的流程,由于 OAuth2 中有 种不一样的受权模式,每种受权模式的受权流程又会有差别,基本流程以下:web

  • 客户端(第三方应用)向资源全部者请求受权。
  • 服务端返回一个受权许可凭证给客户端。
  • 客户端拿着受权许可凭证去受权服务器申请令牌。
  • 受权服务器验证信息无误后,发放令牌给客户端。
  • 客户端拿着令牌去资源服务器访问资源。
  • 资源服务器验证令牌无误后开放资源。

在这里插入图片描述


四、OAuth受权模式

OAuth 协议的受权模式共分为4种。面试


4.一、受权码

受权码(authorization code)方式,指的是第三方应用先申请一个受权码,而后再用该码获取令牌。spring

这种方式是最经常使用的流程,安全性也最高,它适用于那些有后端的 Web 应用。受权码经过前端传送,令牌则是储存在后端,并且全部与资源服务器的通讯都在后端完成。这样的先后端分离,能够避免令牌泄漏。数据库

  • 第一步,A 网站提供一个连接,用户点击后就会跳转到 B 网站,受权用户数据给 A 网站使用。下面就是 A 网站跳转 B 网站的一个示意连接。
https://b.com/oauth/authorize?
  response_type=code&
  client_id=CLIENT_ID&
  redirect_uri=CALLBACK_URL&
  scope=read

上面 URL 中,response_type参数表示要求返回受权码(code),client_id参数让 B 知道是谁在请求,redirect_uri参数是 B 接受或拒绝请求后的跳转网址,scope参数表示要求的受权范围(这里是只读)。json

在这里插入图片描述

  • 第二步,用户跳转后,B 网站会要求用户登陆,而后询问是否赞成给予 A 网站受权。用户表示赞成,这时 B 网站就会跳回redirect_uri参数指定的网址。跳转时,会传回一个受权码,就像下面这样。
https://a.com/callback?code=AUTHORIZATION_CODE

上面 URL 中,code参数就是受权码。

在这里插入图片描述

  • 第三步,A 网站拿到受权码之后,就能够在后端,向 B 网站请求令牌。
https://b.com/oauth/token?
 client_id=CLIENT_ID&
 client_secret=CLIENT_SECRET&
 grant_type=authorization_code&
 code=AUTHORIZATION_CODE&
 redirect_uri=CALLBACK_URL

上面 URL 中,client_id 参数和 client_secret 参数用来让 B 确认 A 的身份(client_secret参数是保密的,所以只能在后端发请求),grant_type参数的值是 AUTHORIZATION_CODE,表示采用的受权方式是受权码,code参数是上一步拿到的受权码,redirect_uri 参数是令牌颁发后的回调网址。

在这里插入图片描述

  • 第四步,B 网站收到请求之后,就会颁发令牌。具体作法是向redirect_uri指定的网址,发送一段 JSON 数据。
{    
      "access_token":"ACCESS_TOKEN",
      "token_type":"bearer",
      "expires_in":2592000,
      "refresh_token":"REFRESH_TOKEN",
      "scope":"read",
      "uid":100101,
      "info":{...}
    }

上面 JSON 数据中,access_token字段就是令牌,A 网站在后端拿到了。

在这里插入图片描述

4.二、隐藏式

有些 Web 应用是纯前端应用,没有后端。这时就不能用上面的方式了,必须将令牌储存在前端。RFC 6749 就规定了第二种方式,容许直接向前端颁发令牌。这种方式没有受权码这个中间步骤,因此称为(受权码)"隐藏式"(implicit)。

  • 第一步,A 网站提供一个连接,要求用户跳转到 B 网站,受权用户数据给 A 网站使用。
https://b.com/oauth/authorize?
  response_type=token&
  client_id=CLIENT_ID&
  redirect_uri=CALLBACK_URL&
  scope=read

上面 URL 中,response_type参数为token,表示要求直接返回令牌。

  • 第二步,用户跳转到 B 网站,登陆后赞成给予 A 网站受权。这时,B 网站就会跳回redirect_uri参数指定的跳转网址,而且把令牌做为 URL 参数,传给 A 网站。
https://a.com/callback#token=ACCESS_TOKEN

上面 URL 中,token参数就是令牌,A 网站所以直接在前端拿到令牌。

注意,令牌的位置是 URL 锚点(fragment),而不是查询字符串(querystring),这是由于 OAuth 2.0 容许跳转网址是 HTTP 协议,所以存在"中间人攻击"的风险,而浏览器跳转时,锚点不会发到服务器,就减小了泄漏令牌的风险。

在这里插入图片描述
这种方式把令牌直接传给前端,是很不安全的。所以,只能用于一些安全要求不高的场景,而且令牌的有效期必须很是短,一般就是会话期间(session)有效,浏览器关掉,令牌就失效了。


4.三、密码式

若是你高度信任某个应用,RFC 6749 也容许用户把用户名和密码,直接告诉该应用。该应用就使用你的密码,申请令牌,这种方式称为"密码式"(password)。

  • 第一步,A 网站要求用户提供 B 网站的用户名和密码。拿到之后,A 就直接向 B 请求令牌。
https://oauth.b.com/token?
  grant_type=password&
  username=USERNAME&
  password=PASSWORD&
  client_id=CLIENT_ID

上面 URL 中,grant_type参数是受权方式,这里的password表示"密码式",username和password是 B 的用户名和密码。

  • 第二步,B 网站验证身份经过后,直接给出令牌。注意,这时不须要跳转,而是把令牌放在 JSON 数据里面,做为 HTTP 回应,A 所以拿到令牌。

4.四、凭证式

最后一种方式是凭证式(client credentials),适用于没有前端的命令行应用,即在命令行下请求令牌。

  • 第一步,A 应用在命令行向 B 发出请求。
https://oauth.b.com/token?
  grant_type=client_credentials&
  client_id=CLIENT_ID&
  client_secret=CLIENT_SECRET

上面 URL 中,grant_type参数等于client_credentials表示采用凭证式,client_id和client_secret用来让 B 确认 A 的身份。

  • 第二步,B 网站验证经过之后,直接返回令牌。

这种方式给出的令牌,是针对第三方应用的,而不是针对用户的,即有可能多个用户共享同一个令牌。


2、实践

一、密码模式

若是是自建单点服务,通常都会使用密码模式。资源服务器和受权服务器
能够是同一台服务器,也能够分开。这里咱们学习分布式的状况。

受权服务器和资源服务器分开,项目结构以下:

在这里插入图片描述


1.一、受权服务器

受权服务器的职责:

  • 管理客户端及其受权信息
    * 管理用户及其受权信息
    * 管理Token的生成及其存储
    * 管理Token的校验及校验Key

1.1.一、依赖

<!--security-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <!--oauth2-->
        <dependency>
            <groupId>org.springframework.security.oauth</groupId>
            <artifactId>spring-security-oauth2</artifactId>
            <version>2.3.6.RELEASE</version>
        </dependency>

1.1.二、受权服务器配置

受权服务器配置经过继承AuthorizationServerConfigurerAdapter的配置类实现:

/**
 * @Author 三分恶
 * @Date 2020/5/20
 * @Description  受权服务器配置
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;//密码模式须要注入认证管理器

    @Autowired
    public PasswordEncoder passwordEncoder;

    //配置客户端
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("client-demo")
                .secret(passwordEncoder.encode("123"))
                .authorizedGrantTypes("password") //这里配置为密码模式
                .scopes("read_scope");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager);//密码模式必须添加authenticationManager
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.allowFormAuthenticationForClients()
                .checkTokenAccess("isAuthenticated()");
    }
}
  • 客户端的注册:这里经过inMemory的方式在内存中注册客户端相关信息;实际项目中能够经过一些管理接口及界面动态实现客户端的注册
  • 校验Token权限控制:资源服务器若是须要调用受权服务器的/oauth/check_token接口校验token有效性,那么须要配置checkTokenAccess("isAuthenticated()")
  • authenticationManager配置:须要经过endpoints.authenticationManager(authenticationManager)将Security中的authenticationManager配置到Endpoints中,不然,在Spring Security中配置的权限控制将不会在进行OAuth2相关权限控制的校验时生效。

1.1.三、Spring Security配置

经过Spring Security来完成用户及密码加解密等配置:

/**
 * @Author 三分恶
 * @Date 2020/5/20
 * @Description SpringSecurity 配置
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

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

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

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("fighter")
                .password(passwordEncoder().encode("123"))
                .authorities(new ArrayList<>(0));
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //全部请求必须认证
        http.authorizeRequests().anyRequest().authenticated();
    }
}

1.二、资源服务器

资源服务器的职责:

  • token的校验
  • 给与资源

1.2.一、资源服务器配置

资源服务器依赖同样,而配置则经过继承自ResourceServerConfigurerAdapter的配置类来实现:

/**
 * @Author 三分恶
 * @Date 2020/5/20
 * @Description
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Bean
    public RemoteTokenServices remoteTokenServices() {
        final RemoteTokenServices tokenServices = new RemoteTokenServices();
        tokenServices.setClientId("client-demo");
        tokenServices.setClientSecret("123");
        tokenServices.setCheckTokenEndpointUrl("http://localhost:8090/oauth/check_token");
        return tokenServices;
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.stateless(true);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        //session建立策略
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
        //全部请求须要认证
        http.authorizeRequests().anyRequest().authenticated();
    }
}

主要进行了以下配置:

  • TokenService配置:在不采用JWT的状况下,须要配置RemoteTokenServices来充当tokenServices,它主要完成Token的校验等工做。所以须要指定校验Token的受权服务器接口地址
  • 同时,因为在受权服务器中配置了/oauth/check_token须要客户端登陆后才能访问,所以也须要配置客户端编号及Secret;在校验以前先进行登陆
  • 经过ResourceServerSecurityConfigurer来配置须要访问的资源编号及使用的TokenServices

1.2.二、资源服务接口

接口比较简单:

/**
 * @Author 三分恶
 * @Date 2020/5/20
 * @Description
 */
@RestController
public class ResourceController {

    @GetMapping("/user/{username}")
    public String user(@PathVariable String username){
        return "Hello !"+username;
    }
}

1.三、测试

受权服务器使用8090端口启动,资源服务器使用默认端口。


1.3.一、获取token

访问/oauth/token端点,获取token:

在这里插入图片描述

  • 请求头:

在这里插入图片描述

  • 返回的token
    在这里插入图片描述

1.3.二、使用获取到的token访问资源接口

  • 使用token调用资源,访问http://localhost:8080/user/fighter,注意使用token添加Bearer请求头

在这里插入图片描述
至关于在Headers中添加 Authorization:Bearer 4a3c351d-770d-42aa-af39-3f54b50152e9。

OK,能够看到资源正确返回。

这里仅仅是密码模式的精简化配置,在实际项目中,某些部分如:

  • 资源服务访问受权服务去校验token这部分可能会换成Jwt、Redis等tokenStore实现,
  • 受权服务器中的用户信息与客户端信息生产环境从数据库中读取,对应Spring Security的UserDetailsService实现类或用户信息的Provider

二、受权码模式

不少网站登陆时,容许使用第三方网站的身份,这称为"第三方登陆"。所谓第三方登陆,实质就是 OAuth 受权。

例如用户想要登陆 A 网站,A 网站让用户提供第三方网站的数据,证实本身的身份。获取第三方网站的身份数据,就须要 OAuth 受权。

以A网站使用GitHub第三方登陆为例,流程示意以下:

在这里插入图片描述

接下来,简单地实现GitHub登陆流程。


2.一、应用注册

在使用以前须要先注册一个应用,让GitHub能够识别。

在这里插入图片描述

应用的名称随便填,主页 URL 填写http://localhost:8080,回调地址填写 http://localhost:8080/oauth/redirect。

  • 提交表单之后,GitHub 应该会返回客户端 ID(client ID)和客户端密钥(client secret),这就是应用的身份识别码
    在这里插入图片描述

2.二、具体代码

  • 只须要引入web依赖:
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
  • GitHub相关配置
github.client.clientId=29d127aa0753c12263d7
github.client.clientSecret=f3cb9222961efe4c2adccd6d3e0df706972fa5eb
github.client.authorizeUrl=https://github.com/login/oauth/authorize
github.client.accessTokenUrl=https://github.com/login/oauth/access_token
github.client.redirectUrl=http://localhost:8080/oauth/redirect
github.client.userInfoUrl=https://api.github.com/user
  • 对应的配置类
@Component
@ConfigurationProperties(prefix = "github.client")
public class GithubProperties {
    private String clientId;
    private String clientSecret;
    private String authorizeUrl;
    private String redirectUrl;
    private String accessTokenUrl;
    private String userInfoUrl;
    //省略getter、setter
}
  • index.html:首页比较简单,一个连接向后端发起登陆请求
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>网站首页</title>
</head>
<body>
    <div style="text-align: center">
        <a href="http://localhost:8080/authorize">Login in with GitHub</a>
    </div>
</body>
</html>
  • GithubLoginController.java:
     * 使用RestTemplate发送http请求
     * 使用Jackson解析返回的json,不用引入更多依赖
     * 快捷起见,发送http请求的方法直接写在控制器中,实际上应该将工具方法分离出去
     * 一样是快捷起见,返回的用户信息没有作任何解析
@Controller
public class GithubLoginController {
    @Autowired
    GithubProperties githubProperties;


    /**
     * 登陆接口,重定向至github
     *
     * @return 跳转url
     */
    @GetMapping("/authorize")
    public String authorize() {
        String url =githubProperties.getAuthorizeUrl() +
                "?client_id=" + githubProperties.getClientId() +
                "&redirect_uri=" + githubProperties.getRedirectUrl();
        return "redirect:" + url;
    }

    /**
     * 回调接口,用户赞成受权后,GitHub会将受权码传递给此接口
     * @param code GitHub重定向时附加的受权码,只能用一次
     * @return
     */
    @GetMapping("/oauth/redirect")
    @ResponseBody
    public String redirect(@RequestParam("code") String code) throws JsonProcessingException {
        System.out.println("code:"+code);
        // 使用code获取token
        String accessToken = this.getAccessToken(code);
        // 使用token获取userInfo
        String userInfo = this.getUserInfo(accessToken);
        return userInfo;
    }


    /**
     * 使用受权码获取token
     * @param code
     * @return
     */
    private String getAccessToken(String code) throws JsonProcessingException {
        String url = githubProperties.getAccessTokenUrl() +
                "?client_id=" + githubProperties.getClientId() +
                "&client_secret=" + githubProperties.getClientSecret() +
                "&code=" + code +
                "&grant_type=authorization_code";
        // 构建请求头
        HttpHeaders requestHeaders = new HttpHeaders();
        // 指定响应返回json格式
        requestHeaders.add("accept", "application/json");
        // 构建请求实体
        HttpEntity<String> requestEntity = new HttpEntity<>(requestHeaders);
        RestTemplate restTemplate = new RestTemplate();
        // post 请求方式
        ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);
        String responseStr = response.getBody();
        // 解析响应json字符串
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(responseStr);
        String accessToken = jsonNode.get("access_token").asText();
        System.out.println("accessToken:"+accessToken);
        return accessToken;
    }

    /**
     *
     * @param accessToken 使用token获取userInfo
     * @return
     */
    private String getUserInfo(String accessToken) {
        String url = githubProperties.getUserInfoUrl();
        // 构建请求头
        HttpHeaders requestHeaders = new HttpHeaders();
        // 指定响应返回json格式
        requestHeaders.add("accept", "application/json");
        // AccessToken放在请求头中
        requestHeaders.add("Authorization", "token " + accessToken);
        // 构建请求实体
        HttpEntity<String> requestEntity = new HttpEntity<>(requestHeaders);
        RestTemplate restTemplate = new RestTemplate();
        // get请求方式
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
        String userInfo = response.getBody();
        System.out.println("userInfo:"+userInfo);
        return userInfo;
    }

}

2.三、测试

  • 访问localhost:8080,点击连接,重定向至GitHub

在这里插入图片描述

  • 在GitHub中输入帐号密码,登陆

在这里插入图片描述

  • 登陆成功后,GitHub 就会跳转到redirect_uri指定的跳转网址,而且带上受权码
http://localhost:8080/oauth/redirect?code=d45683eded3ac7d4e6ed

OK,用户信息也一并返回了。

在这里插入图片描述


本文为学习笔记类博客,学习资料见参考!



参考:

【1】:《SpringSecurity 实战》
【2】:《SpringBoot Vue全栈开发实战》
【3】:理解OAuth 2.0
【4】:OAuth 2.0 的一个简单解释
【5】:OAuth 2.0 的四种方式
【6】:这个案例写出来,还怕跟面试官扯不明白 OAuth2 登陆流程?
【7】:作微服务绕不过的 OAuth2,松哥也来和你们扯一扯
【8】:GitHub OAuth 第三方登陆示例教程
【9】:OAuth 2.0 认证的原理与实践
【10】:Spring Security OAuth2 Demo —— 密码模式(Password)
【11】:Spring Security OAuth专题学习-密码模式及客户端模式实例
【12】:Spring Boot and OAuth2
【13】:Spring Boot+OAuth2使用GitHub登陆本身的服务

相关文章
相关标签/搜索