@RequestMapping("/oauth")
@Controller
public class OauthController { String clientId = "clientId";
String clientSecret = "clientSecret";
String response_type = "code";
String authorizationCode = "authorizationCode";
String redirectUrlPage = "redirectUrlPage"; /**
* 请求通过凭证地址
*/
String getAccessTokenURL = "http://localhost:8080/subaccountServer/oauth/getAccessToken";
/**
* 请求资源地址
*/
String userInfoUrl = "http://localhost:8080/subaccountServer/oauth/getResource"; /**
* 重定向到请求 授权码的url
* @return
* @throws Exception
*/
@RequestMapping("/redirectToRequestAuthorizationCodeURL")
public String redirectToRequestAuthorizationCodeURL() throws Exception {
String url = "getAuthorizationCode";
// accessTokenRequest 是用来描述请求对象的,描述了请求地址,和请求参数
OAuthClientRequest accessTokenRequest = OAuthClientRequest.authorizationLocation(url)
.setResponseType(response_type).setClientId(clientId).setRedirectURI( redirectUrlPage ).buildQueryMessage(); return "redirect:" + accessTokenRequest.getLocationUri();
} /**
* 返回授权码
* @param model
* @param request
* @return
* @throws Exception
*/
@RequestMapping("/getAuthorizationCode")
public Object getAuthorizationCode(Model model, HttpServletRequest request) throws Exception {
OAuthAuthzRequest oauthRequest = new OAuthAuthzRequest(request); String redirectURI = oauthRequest.getParam(OAuth.OAUTH_REDIRECT_URI);
String clientId = oauthRequest.getClientId();
String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);
//得到数据以后应该检查数据 //把 state 写到一个 重定向的响应
OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse.authorizationResponse(request, HttpServletResponse.SC_FOUND);
builder.setCode(authorizationCode);
OAuthResponse response = builder.location(redirectURI).buildQueryMessage(); return "redirect:" + response.getLocationUri(); } /**
* 请求通过凭证
* @param request
* @return
* @throws Exception
*/
@RequestMapping("/redirectUrlPage")
public Object redirectUrlPage(HttpServletRequest request) throws Exception {
String code = request.getParameter("code"); OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient()); OAuthClientRequest accessTokenRequest = OAuthClientRequest.tokenLocation(getAccessTokenURL)
.setGrantType(GrantType.AUTHORIZATION_CODE)
.setClientId(clientId)
.setClientSecret(clientSecret)
.setCode(code)
.setRedirectURI(redirectUrlPage)
.buildQueryMessage(); OAuthAccessTokenResponse oAuthResponse = oAuthClient.accessToken(accessTokenRequest, OAuth.HttpMethod.POST); //得到通过凭证和过期时间
String accessToken = oAuthResponse.getAccessToken();
Long expiresIn = oAuthResponse.getExpiresIn(); return "redirect:requestResourcePage?accessToken=" + accessToken; } /**
* 返回通过凭证
* @param request
* @return
* @throws Exception
*/
@RequestMapping(value = "/getAccessToken", method = RequestMethod.POST)
public HttpEntity<String> getAccessToken(HttpServletRequest request) throws Exception {
// 构建OAuth请求
OAuthTokenRequest oauthRequest = new OAuthTokenRequest(request); String authCode = oauthRequest.getParam(OAuth.OAUTH_CODE);
String clientSecret = oauthRequest.getClientSecret();
//应该验证授权码 // 生成Access Token
OAuthIssuer oauthIssuer = new OAuthIssuerImpl(new MD5Generator());
String accessToken = oauthIssuer.accessToken(); OAuthResponse response = OAuthASResponse.tokenResponse(HttpServletResponse.SC_OK).setAccessToken(accessToken).setExpiresIn("120").buildJSONMessage();
return new ResponseEntity<String>(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
} /**
* 请求资源
* @param accessToken
* @return
* @throws Exception
*/
@RequestMapping("/requestResourcePage")
@ResponseBody
public String requestResourcePage(String accessToken) throws Exception {
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient()); OAuthClientRequest userInfoRequest = new OAuthBearerClientRequest(userInfoUrl).setAccessToken(accessToken).buildQueryMessage(); OAuthResourceResponse resourceResponse = oAuthClient.resource(userInfoRequest, OAuth.HttpMethod.GET,OAuthResourceResponse.class);
String resource = resourceResponse.getBody(); return resource;
} /**
* 返回资源
* @param request
* @return
* @throws Exception
*/
@RequestMapping("/getResource")
public HttpEntity<String> getResource(HttpServletRequest request) throws Exception {
OAuthAccessResourceRequest oauthRequest = new OAuthAccessResourceRequest(request, ParameterStyle.QUERY);
String accessToken = oauthRequest.getAccessToken();
//这里应该验证accessToken return new ResponseEntity<String>("我就是资源", HttpStatus.OK);
} }

  

需要的oauth 依赖:

		<dependency>
<groupId>org.apache.oltu.oauth2</groupId>
<artifactId>org.apache.oltu.oauth2.client</artifactId>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.oltu.oauth2</groupId>
<artifactId>org.apache.oltu.oauth2.authzserver</artifactId>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.oltu.oauth2</groupId>
<artifactId>org.apache.oltu.oauth2.resourceserver</artifactId>
<version>1.0.1</version>
</dependency>

  

备注1:一个程序模拟了 三个服务器端 ,一个 客户端。   可能比较难懂

备注2: 省略了验证用户信息,授权码,通过凭证的  逻辑。

oauth 请求逻辑图  https://www.cnblogs.com/cxygg/p/9503032.html

oauth2 java 代码示例的更多相关文章

  1. MapReduce序列化及分区的java代码示例

    概述 序列化(Serialization)是指把结构化对象转化为字节流. 反序列化(Deserialization)是序列化的逆过程.把字节流转为结构化对象. 当要在进程间传递对象或持久化对象的时候, ...

  2. kafka集群和zookeeper集群的部署,kafka的java代码示例

    来自:http://doc.okbase.net/QING____/archive/19447.html 也可参考: http://blog.csdn.net/21aspnet/article/det ...

  3. 消费者、生产者Java代码示例,wait

    箱子中的苹果代表资源,现在有消费者从箱子中拿走苹果,生产者往箱子中放苹果.代码如下: 资源--箱子中的苹果: public class Box { int size; int num; public ...

  4. 将MySQL一张表的数据迁移到MongoDB数据库的Java代码示例

    Java代码: package com.zifeiy.snowflake.handle.etl.mongodb; import java.sql.Connection; import java.sql ...

  5. 阿里云直播鉴权java代码示例

    段时间公司需要做直播服务,所以就研究了一下阿里云的直播,在直播里面,最重要的就是url的鉴权操作(验证推流或者拉流的有效性),在网上找了很多代码,都没有发现java的demo,所以就写篇播客记录一下, ...

  6. java代码示例(3)

    /** * 需求分析:根据输入的天数是否是周六或是周日, * 并且天气的温度大于28摄氏度,则外出游泳,否则钓鱼 * @author chenyanlong * 日期:2017/10/14 */ pa ...

  7. spark使用KryoRegistrator java代码示例

    转载引用自:http://www.cnblogs.com/tovin/p/3833985.html 最近在使用spark开发过程中发现当数据量很大时,如果cache数据将消耗很多的内存.为了减少内存的 ...

  8. android webView开发之js调用java代码示例

    1.webView设置 webView.getSettings().setJavaScriptEnabled(true);//设置支持js webView.addJavascriptInterface ...

  9. 服务端发送xml请求java代码示例

    /** * */ package com.autoyol.pay.cmb.core; import java.io.ByteArrayOutputStream; import java.io.IOEx ...

随机推荐

  1. oracle概要文件profile详解

    一.目的: Oracle系统中的profile可以用来对用户所能使用的数据库资源进行限制,使用Create Profile命令创建一个Profile,用它来实现对数据库资源的限制使用,如果把该prof ...

  2. [Spring]初识Spring-Spring是什么?如何实例化一个Spring容器?

    关于Spring入门的基础知识点 Spring简介 Spring是由Rod Johnson创建的轻量型容器,目的在于简化企业级开发.是一种容器框架 a.降低侵入性 b.提供了IOC(控制反转)和AOP ...

  3. Delphi 10.3.1 TNetHttpClient在多线程中存在的问题及解决方法。

    Delphi 10.3.1发布了,对10.3.0存在的各种问题,做了大量的修正.但听高勇说TNetHttpClient在多线程中存在问题,今天做了一下测试,确实如此,看来,还需要官方进一步修正! 具体 ...

  4. 运行和管理Rabbit

    节点描述的是一个Erlang节点运行着一个Erlang应用程序.Erlang虚拟机的每个实例我们称之为节点.多个Erlang应用程序可以运行在同一个节点之上.节点之间可以进行本地通信.在RabbitM ...

  5. wewqe

    script.cscript_runreason(const struct interface *ifp, const char *reason)elen = (size_t)make_env(ifp ...

  6. 如何通过创建切片器窗格节省PowerBI报告空间

    许多用户在使用Power BI的过程中,都会有这么一个困扰:在Power BI 开发中,切片器一旦过多就会占用非常多的空间.发生这种情况时,您显示数据的页面也会更加小.但另一方面,如果您没有切片器,报 ...

  7. poj 1236 强联通分量

    大致题意给你有一个点数为n<=100的有向图. 求解两个子任务: 1:最少给多少个点信息,这些点的信息可以顺着有向边传遍全图. 2:最少要加多少条边,使得整个图强联通. 求强联通分量再缩点后得到 ...

  8. mxnet自定义dataloader加载自己的数据

    实际上关于pytorch加载自己的数据之前有写过一篇博客,但是最近接触了mxnet,发现关于这方面的教程很少 如果要加载自己定义的数据的话,看mxnet关于mnist基本上能够推测12 看pytorc ...

  9. Oracle使用笔记(一)

    目录 一.创建表: 二.编辑表数据: 三.Oracle基本数据类型: (一) 字符串类型 1.1:CHAR类型 CHAR(size [BYTE | CHAR]) 1.2: NCHAR类型 1.3 VA ...

  10. Arcgis API本地化

    ①将API文件夹复制到该目录下C:\Program Files\ArcGIS\Server\framework\runtime\tomcat\webapps ②打开API文件夹中的init.js文件( ...