问答社区项目学习——引入第三方登录(四)

建立学习的第一站吧,从头开始。欢迎大家跟我一起学习~ 这里也是为了记录自己的学习之路!——by  xln

 1. 实现网站的登录功能,这里使用github的登录功能,在github首页下滑进入API

2. 选择github授权app,进入文档中,粗略浏览大概后,在右侧栏中找到Building OAuth App

右边侧栏底部

3. 开始创建一个App,阅读以下步骤,接下来按步骤进行

4. 对创建一个OAuth app步骤创建一个时序图,说明系统之间是如何交互的

5. 首先开始第一步进入首页头像,进入Settings,并选择Develop Setting

                                        

6. 选择OAuth Apps 进行创建

7. 在Index.html页面的下拉页面的登录框写获取github登录权限的几个参数

<li><a href="https://github.com/login/oauth/authorize?client_id=3f87d2525e1f0d7ccae5&redirect_url=http://localhost:8887/callback&scope=user&state=1">登录</a></li>

8. 然后运行项目,打开项目页面,点击登录,就会跳转到以下页面

9. 进行授权后,浏览器显示成功,由于回调页面没有设置,所以只看浏览器地址

 

10. 为了创建回调页面,先创建一个Controller

package study.xln.community.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class AuthorizeController {
    @GetMapping("/callback")
    public String callback(@RequestParam(name = "code")  String code,
                           @RequestParam(name = "state") String state){
        //登录成功之后返回首页
        return "index";
    }
}

 看okhttp页面得到POST如何请求

11. 创建一个对第三方支持的package,一个github 的provider,在里面写一个POST传递github登录授权的几个参数的方法,在pom文件中引入okhttp的jar包,以及fastjson的jar包(用Alt+insert键,快捷引出Dependency,查找所需Jar包,如果没有,在https://mvnrepository.com/中查找所需的包),然后在AuthorizeController去调用这个Provider的方法。

package study.xln.community.provider;

import com.alibaba.fastjson.JSON;
import okhttp3.*;
import org.springframework.stereotype.Component;
import study.xln.community.dto.AccessTokenDTO;
import study.xln.community.dto.GithubUser;

import java.io.IOException;
/**
*  拿到accesstoken
**/
//注解@Controller是把类作为路由API的一个承载者
//注解@Component仅仅把当前类初始化到Spring的容器的上下文,使用这个注解就不需要再去实例化这个对象了
@Component
public class GithubProvider {
    //如果参数超过两个,就要把它封装成对象去做

    public String getAccessToken(AccessTokenDTO accessTokenDTO){
        //已经封装好方法了,把它定义成局部变量
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();

//        String json = "";
        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(accessTokenDTO));
        Request request = new Request.Builder()
                .url("https://github.com/login/oauth/access_token")
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
//            return response.body().string();
            String string = response.body().string();
            System.out.println(string);
            return string;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public GithubUser getUser(String accessToken){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://api.github.com/user?access_token="+accessToken)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            //把string的json对象自动转化解析成java的类对象
            GithubUser githubUser = JSON.parseObject(string, GithubUser.class);
            return githubUser;
        } catch (IOException e) {
        }
        return null;
    }
}

 

package study.xln.community.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import study.xln.community.dto.AccessTokenDTO;
import study.xln.community.provider.GithubProvider;

@Controller
public class AuthorizeController {

    @Autowired  //自动的去把String容器里面写好的实例化的一个实例加载到当前使用的上下文
    private GithubProvider githubProvider;

    @GetMapping("/callback")
    public String callback(@RequestParam(name = "code")  String code,
                           @RequestParam(name = "state") String state){

        AccessTokenDTO accessTokenDTO = new AccessTokenDTO();
        //在github的OAuth application settings里面对应Client ID和Cilent Secret
        accessTokenDTO.setClient_id("3f87d2525e1f0d7ccae5");
        accessTokenDTO.setClient_secret("e580934afb9c20a54ceaaa1fb2ce9b3d590f35ae");
        accessTokenDTO.setCode(code);
        accessTokenDTO.setRedirect_uri("http://localhost:8887/callback");
        accessTokenDTO.setState(state);
        //在括号里new一个对象时,选中并使用Ctrl+Alt+V 自动创建对象
        githubProvider.getAccessToken(accessTokenDTO);
        //登录成功之后返回首页
        return "index";
    }
}

12. 创建一个dto的package,表示数据传输的一个模型(dto详细说明 https://www.cnblogs.com/loveis715/p/4379656.html

13. 创建一个新的access_token来测试,

 

下面进行验证是否拿到access token能得到想要的信息

在浏览器输入https://api.github.com/user?access_token=拿到的新的access token,然后得到一系列的json数据

14. 创建新的DTO,设置从json页面拿到需要的字段

15. 启动项目,点击登录,能够回到首页面,且拿到access_token,下图为成功返回页面

 16. 测试能否拿到登录数据,在GithubProvider里面将之前拿到的accesstoken分解,在AuthorizeController里面得到用户信息

 

17. 为了在不同环境读取不同的配置文件,可以把所需变量封装在application.properties里面

18. 启动项目,打开首页,登录之后,state为1显示跳转成功,并在控制台得到用户名称

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值