@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. Chrome插件-网页版BusHound

    Chrome插件-网页版BusHound

  2. The databse returned no natively generated identity value问题

    com.cqupt.dayday.model 代码 package com.cqupt.dayday.model; import java.util.Date; /** * Created by I ...

  3. python 时间戳算法

    根据当前时间戳获得整小时时间戳 unit = 3600 start_time = int(time.time())/3600 * 3600 根据当前时间戳获得整天时间戳 unit = 3600*24 ...

  4. Collection集合复习方法回顾

    Collection集合方法: add()  //添加元素 remove()    //移除元素 size()                                     //返回集合长度 ...

  5. HDU 6050 17多校2 Funny Function(数学+乘法逆元)

    Problem Description Function Fx,ysatisfies:For given integers N and M,calculate Fm,1 modulo 1e9+7.   ...

  6. 性能测试-10.数据分析Analysis

    Analysis Summary 平均响应时间(Average TransactionResponse Time) 每秒响应数(Transactions per Second) 1.Vuser  Ru ...

  7. 【Python】练习题

    练习1:有两个磁盘文件A和B,各存放一行字母,要求把这两个文件中的信息合并(按字母顺序排列), 输出到一个新文件C中 import os file1_path="e:\\test3\\2.t ...

  8. mssql,mysql,Oracle 数据库中获得UUID字符串

    sql server : select replace(newId(),'-','') oracle :select sys_guid() from dual SQL> select sys_g ...

  9. ubuntu apt-get failed

    Err http://mirrors.163.com/ubuntu/ trusty/main libtinfo-dev i386 5.9+20140118-1ubuntu1 Could not res ...

  10. 强化学习中的无模型 基于值函数的 Q-Learning 和 Sarsa 学习

    强化学习基础: 注: 在强化学习中  奖励函数和状态转移函数都是未知的,之所以有已知模型的强化学习解法是指使用采样估计的方式估计出奖励函数和状态转移函数,然后将强化学习问题转换为可以使用动态规划求解的 ...