OAthe2 Login use OkHttpClient and OAuth2RestTemplate

http://samchu.logdown.com/posts/1437422-oathe2-login-use-okhttpclient-and-oauth2resttemplate?utm_source=tuicool&utm_medium=referral

如果要取得 OAuth 授權的話,可以直接使用 OkHttpClient 或是 OAuth2RestTemplate 來實作

在依賴中增加 OkHttpClient

build.gradle

dependencies {
    compile ‘com.squareup.okhttp3:okhttp:3.6.0‘
}

實際登入的程式

public void Okhttp() throws IOException {
    OkHttpClient client = new OkHttpClient();
    String credential = Credentials.basic("clientkpi", "123456");
    FormBody body = new FormBody.Builder()
            .add("username", "sam.chu=")
            .add("password", "12345678")
            .add("grant_type", "password")
            .add("scope", "account role").build();
    Request request = new Request.Builder()
            .header("Authorization", credential)
            .url("http://localhost:8081/oauth/token")
            .post(body)
            .build();
    try (Response response = client.newCall(request).execute()) {
        if (!response.isSuccessful()) {
            throw new IOException("Unexpected code " + response);
        }
        ObjectMapper mapper = new ObjectMapper();
        OauthToken oauthToken = mapper.readValue(response.body().string(), OauthToken.class);
        System.out.println(oauthToken);
    }
}

或是你可以選 org.springframework.security.oauth:spring-security-oauth2 提供的 OAuth2RestTemplate

在依賴中增加 org.springframework.security.oauth:spring-security-oauth2

build.gradle

dependencies {
    compile(‘org.springframework.boot:spring-boot-starter-security‘)
    compile ‘org.springframework.security.oauth:spring-security-oauth2:2.0.12.RELEASE‘
}
public void testOAuth() {
    AccessTokenRequest atr = new DefaultAccessTokenRequest();
    OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(atr));
    try {
        System.out.println(oAuth2RestTemplate.getAccessToken());
        System.out.println(oAuth2RestTemplate.getAccessToken().getRefreshToken());
    } catch (OAuth2AccessDeniedException e) {
        System.out.println("登入失敗" + e.getHttpErrorCode()); // 403

        System.out.println("登入失敗" + e.getOAuth2ErrorCode()); // access_denied

        System.out.println("登入失敗" + e.getMessage()); //Access token denied.

        System.out.println("登入失敗" + e.getLocalizedMessage()); // Access token denied.

        System.out.println("登入失敗" + e.getSummary()); // error="access_denied", error_description="Access token denied."

    }
}

protected OAuth2ProtectedResourceDetails resource() {
    ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
    List scopes = new ArrayList<String>(2);
    scopes.add("account");
    scopes.add("role");
    resource.setAccessTokenUri("http://localhost:8081/oauth/token");
    resource.setClientId("clientkpi");
    resource.setClientSecret("123456");
    resource.setGrantType("password");
    resource.setScope(scopes);
    resource.setUsername("sam.chu=");
    resource.setPassword("12345678");
    return resource;
}

不過基於 Spring Boot 的自動配置會亂數產生帳密 來做 Http basic 認證,剛開發的時候會有點煩

可以在 SpringBootApplication 暫時把它關閉

順便把 EnableOAuth2Client 加上

@EnableOAuth2Client
@SpringBootApplication(exclude = {SecurityAutoConfiguration.class})
public class KpiApplication {

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

其他兩個範例是使用 RestTemplate 來新增跟取得的範例

public void restPost() throws IOException {
        String url = "http://localhost:8082/api/v1/role";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON_UTF8));
        headers.add("Authorization", String.format("%s %s", "bearer", "eyJhbGciOiJIUzI1.NiIsInR5cCI6I.kpXVCJ9"));
        RoleDto roleDto = new RoleDto();
        roleDto.setCode("ROLE_GINTAMA");
        roleDto.setLabel("銀魂銀魂銀魂");
        HttpEntity<RoleDto> entity = new HttpEntity<RoleDto>(roleDto, headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class, new HashMap<String, String>());
        if (response.getStatusCode().equals(HttpStatus.CREATED)) {
            System.out.println(response.getBody());
        }
    }

取得資源

public void restGet() throws IOException {
    String url = "http://localhost:8082/api/v1/role";
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON_UTF8));
    headers.add("Authorization", String.format("%s %s", "bearer", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsia3BpIiwiYWNjb3VudCJdLCJ1c2VyX25hbWUiOiJzYW0uY2h1PSIsInNjb3BlIjpbImFjY291bnQiLCJyb2xlIl0sImV4cCI6MTQ4NzU3NDUzNywiYXV0aG9yaXRpZXMiOlsiUk9MRV9VU0VSIl0sImp0aSI6ImNiMzc0OGFmLTc2NGUtNDNiNy1iNTVjLTU4ZjQzZWQwOTU0MCIsImNsaWVudF9pZCI6ImNsaWVudGtwaSJ9.9Wwk5-GrJ_xdVOcOexoDhIXEznHqm3ssBfob0FeSFgA"));
    HttpEntity<String> entity = new HttpEntity<String>(headers);
    ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
    if (response.getStatusCode().equals(HttpStatus.OK)) {
        System.out.println(response.getBody());
    }
}

← use JWT OAuth2 and spring-security Create AuthorizationServer

http://samchu.logdown.com/posts/1433379

http://www.tuicool.com/articles/eeQvy2j

时间: 2024-08-24 11:36:35

OAthe2 Login use OkHttpClient and OAuth2RestTemplate的相关文章

linux 本地账号密码无法登陆,一直返回 登陆的login界面

登陆redhat一直是返回login,账号和密码没错 通过ssh crt类的软件远程连接系统 然后更改文件   vi /etc/pam.d/login 把 :session required /lib/security/pam_limits.so 更改为:session required /lib64/security/pam_limits.so wq保存

摆脱Login控件,自己定义登录操作

protected void ImageButton1_Click(object sender, ImageClickEventArgs e) { //在登录过程中,程序自动使用login.aspx进行拦截 //验证用户通过后,自动返回拦截的位置 if (Membership.ValidateUser(this.TextBox1.Text, this.TextBox2.Text)) { this.Session["xh"] = this.TextBox1.Text; FormsAuth

/etc/login.defs 的说明

/etc/login.defs 配合/etc/passwd和/etc/shadow来对用户进行一些限制  但是优先级低于/etc/passwd和/etc/shadow. 如果有冲突的地方,系统会以/etc/passwd和/etc/shadow为准. 这个文件的内容如下 [[email protected] ~]# egrep -v '^[ ]*$|^#' /etc/login.defs      过滤/etc/login.defs中的空行/只有空格的行/被注释的行 MAIL_DIR    /va

Java小项目之Login界面理解MVC(MySQL数据库基本操作)

说真的,第一次看到MVC时候的感觉就和看到面向对象编程一样,感觉很方.之后慢慢的写了一些代码,在理解面向对象编程的同时也看到了MVC,虽然现在还是用不到,但是我觉得还是有些了解的好. 先谈谈MVC:模型(model):程序员编写程序应有的功能(实现算法等等).数据库专家进行数据管理和数据库设计(可以实现具体的功能).  视图(view):设计界面. 控制(Controller):处理事务. 很多地方可能我理解的不是很到位.只是能写出来一个大概,后续我还会更新.又重新查了一遍资料,感觉又开始有一种

private OkHttpClient client

前面的内容介绍了OkHttp,本章就来教大家okhttp的基本使用,学了这些基本东西之后,大家有其他的需求可以自行扩展.以下的所有请求都是异步请求服务器,在真实的企业开发中,基本都是异步. get请求 post请求 文件上传 依赖 Android Studio可以在线依赖,在app/build.gradle文件中加上下面这句话就行 compile 'com.squareup.okhttp3:okhttp:3.8.0' 1 1 get请求 首先需要创建一个全局的OkHttpClient对象,所有的

linux-裁剪Linux功能,编译/bin/login, busybox编译linux

linux功能:终端提示信息 [[email protected] ~]# cat /etc/issueRed Hat Enterprise Linux Server release 5.8 (Tikanga)Kernel \r on an \m [[email protected] ~]# uname -r2.6.18-308.el5[[email protected] ~]# uname -mx86_64[[email protected] ~]# linux功能:用户 nsswitch:

execute as login 切换上下文

作为DBA,可能经常需要帮助Developer排除有关权限的问题.要确认某个账号是不是已经拥有了某权限,DBA并不需要使用该账号的登录名和密码进行验证,只需使用execute as语句,将当前会话的上下文切换到指定的login(登录)或者user(用户),就可以验证该账号是否拥有某权限. execute as user='user_name' 该语句模拟的上下文是当前数据库中的user,模拟范围仅限于当前数据库,任何对该数据库以外的资源的访问尝试都会导致失败,不管该user是否拥有相应权限. e

【幻化万千戏红尘】qianfengDay27-HttpURLConnection,OkHttpClient,,多线程下载且断点续传基础学习:

课程回顾: Servlet:java语言开发的运行在服务器上的开发步骤:1.创建Servlet类2.重写doGet或doPost方法3.运行在服务器 生命周期:1.初始化2.服务3.销毁 URL:统一资源定位符,网址openConnection 今日内容:Http协议:超文本传输协议常用方式:1.HttpURLConnection2.okHttp HttpURLConnection的使用步骤:1.创建URL对象---URL url=new URL("网址");2.获取连接对象--Htt

Error page: /dede/login.php Error infos: No database

登陆dede后台这样提示Error page: /dede/login.php Error infos: No database selected Error sql: Select admin.*,atype.purviews From `dede_admin` admin left join `dede_admintype` atype on atype.rank=admin.usertype where admin.userid like 'admin' limit 0,1登陆dede后台