@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. connection reset 分析解决(转载)

    文章转自:https://my.oschina.net/xionghui/blog/508758;记录下来以便以后复习查阅; 在使用HttpClient调用后台resetful服务时,“Connect ...

  2. <Dr.Elephant><How to tune ur application>

    Why Dr.Elephant? Most of Hadoop optimization tools out there, but they are focused on simplifying th ...

  3. pycharm运行pytest

    pycharm运行三种方式 1.以xx.py脚本方式直接执行,当写的代码里面没用到unittest和pytest框架时,并且脚本名称不是以test_开头命名的,此时pycharm会以xx.py脚本方式 ...

  4. 解决The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers.

    SpringMVC中当在浏览器中输入对应的MappingUrl时,报The resource identified by this request is only capable of generat ...

  5. mysql cast

    之前讲到了orcale的字符串与日期等类型的转换,现在我们来看看Mysql是怎么转换的.比起orcale,MySQL相比之下就简单得多了,只需要一个Cast()函数就能搞定.其语法为:Cast(字段名 ...

  6. SpringBoot 添加fastjson

    1.先在项目中添加fastjson依赖: <dependency> <groupId>com.alibaba</groupId> <artifactId> ...

  7. java问题排查工具之一板斧jstack——使用 jstack 定位 java进程CPU过高的问题

    jstack主要用来查看某个Java进程内的线程堆栈信息.语法格式如下: jstack [option] pid jstack [option] executable core jstack [opt ...

  8. pyx文件 生成pyd 文件用于 cython调用

    转于:https://www.2cto.com/kf/201405/304168.html 1. 初衷 最近学用python,python不愧是为程序员考虑的编程语言,写起来很快很方便,大大节省开发效 ...

  9. web前端优化

    在谈到Web优化之前,我们回到一个更原始的问题,Web前端的本质是什么.我的理解是: 将信息快速并友好的展示给用户并能够与用户进行交互.快速的意思就是在尽可能短的时间内完成页面的加载,试想一下当你在淘 ...

  10. linux下数学函数

    linux 下如果用数学函数比如sin,需要加上“-lm”参数编译,如:gcc test.c -lglut -lGLU -lGL -lm && ./a.out