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

OAthe2 Login use OkHttpClient and OAuth2RestTemplate的更多相关文章

  1. 「2020 新手必备 」极速入门 Retrofit + OkHttp 网络框架到实战,这一篇就够了!

    老生常谈 什么是 Retrofit ? Retrofit 早已不是什么新技术了,想必看到这篇博客的大家都早已熟知,这里就不啰嗦了,简单介绍下: Retrofit 是一个针对 Java 和 Androi ...

  2. Android封装OkHttpClient的类库

    由于android6.0的SDK没有HttpClient,只有HttpURLConnection和OkHttpClient,特记下OkHttpClient的使用方法 1.Ui测试界面布局 <?x ...

  3. 浅谈SQL注入风险 - 一个Login拿下Server

    前两天,带着学生们学习了简单的ASP.NET MVC,通过ADO.NET方式连接数据库,实现增删改查. 可能有一部分学生提前预习过,在我写登录SQL的时候,他们鄙视我说:“老师你这SQL有注入,随便都 ...

  4. 打开程序总是会提示“Enter password to unlock your login keyring” ,如何成功关掉?

    p { margin-bottom: 0.1in; line-height: 120% } 一.一开始我是按照网友所说的 : rm -f ~/.gnome2/keyrings/login.keyrin ...

  5. Day01 login module

    知识点:模块导入  变量赋值的两种形式  格式化输出  for循环  if...else 嵌套 #!C:\Program Files\Python35/bin # -*- conding:utf-8 ...

  6. Login控件尝试

    新建web项目,添加default.aspx.Register.aspx.Login.aspx. default.aspx中添加LoginName.LoginStatus,LoginName的Form ...

  7. okhttp封装时,提示 cannot resolve method OkHttpClient setConnectTimeout() 函数

    如标题所示,okhttp封装时,提示 cannot resolve method  OkHttpClient setConnectTimeout() 函数,有遇到这样现象的朋友吗? 原因:因使用的是 ...

  8. [转载] 构造linux 系统下免密码ssh登陆  _How to establish password-less login with SSH

    In present (post production) IT infrastructure many different workstations, servers etc. have to be ...

  9. Security9:查询Login被授予的权限

    在给一个Login授予权限时,发现该Login已经存在,其对应的User也存在于指定的DB中,查看该Login在指定DB中已被授予的权限. 1,查看Login的Server PrincipalID s ...

随机推荐

  1. 图像边缘检测--OpenCV之cvCanny函数

    图像边缘检测--OpenCV之cvCanny函数 分类: C/C++ void cvCanny( const CvArr* image, CvArr* edges, double threshold1 ...

  2. Oracle UTL_HTTP(收集汇总有用资料)

    From Oracle The UTL_HTTP package makes Hypertext Transfer Protocol (HTTP) callouts from SQL and PL/S ...

  3. 初涉IPC,了解AIDL的工作原理及使用方法

    初涉IPC,了解AIDL的工作原理及使用方法 今天来讲讲AIDL,这个神秘的AIDL,也是最近在学习的,看了某课大神的讲解写下的blog,希望结合自己的看法给各位同价通俗易懂的讲解 官方文档:http ...

  4. PS 图像调整算法— —渐变映射

    这个调整简单来说就是先建立一张lookup table, 然后以图像的灰度值作为索引,映射得到相应的颜色值.图像的灰度值是由图像本身决定的,但是lookup table 却可以各种各样,所以不同的lo ...

  5. 图像分割之(四)OpenCV的GrabCut函数使用和源码解读

    图像分割之(四)OpenCV的GrabCut函数使用和源码解读         分类:            图像处理            计算机视觉             2013-01-23 ...

  6. GEFGWT的HelloWorld

    发现一个好玩的东西,gef-gwt,使用它可以轻松的在web上建立gef程序,原文在这里http://gefgwt.org/getting-started/(文章虽然是英文,但是很容易懂,我是按部就班 ...

  7. wait和notify的理解与使用

    1.对于wait()和notify()的理解 对于wait()和notify()的理解,还是要从jdk官方文档中开始,在Object类方法中有: void notify() Wakes up a si ...

  8. 理解java值传递与引用传递

    1.基本类型和引用类型在内存中的保存 Java中数据类型分为两大类,基本类型和对象类型.相应的,变量也有两种类型:基本类型和引用类型.基本类型的变量保存原始值,即它代表的值就是数值本身:而引用类型的变 ...

  9. 80端口被NT kernel & System 占用

    新年后正常上班的第一天,客户报告,虚拟机上的网站起不来了. 登录虚拟机的远程桌面,闪几下连接信息,后面就没了,不显示远程桌面.联系虚拟机管理,重启,远程桌面是连上了,网站还是起不来. 查看window ...

  10. IBATIS的优缺点

    ibatis优缺点总结 .优点 简单: 易于学习,易于使用,通过文档和源代码,可以比较完全的掌握它的设计思路和实现. 实用: 提供了数据映射功能,提供了对底层数据访问的封装(例如ado.net),提供 ...