本文整理汇总了Java中org.apache.oltu.oauth2.common.message.types.ResponseType类的典型用法代码示例。如果您正苦于以下问题:Java ResponseType类的具体用法?Java ResponseType怎么用?Java ResponseType使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
ResponseType类属于org.apache.oltu.oauth2.common.message.types包,在下文中一共展示了ResponseType类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: __parseResponseType
import org.apache.oltu.oauth2.common.message.types.ResponseType; //导入依赖的package包/类
private OAuthResponse __parseResponseType(HttpServletRequest request, ResponseType _responseType, IOAuth.IOAuthAuthzHelper _authzHelper, OAuthAuthzRequest _oauthRequest, String _redirectURI, String _scope, String uid, String state) throws Exception {
OAuthResponse _response;
switch (_responseType) {
case CODE:
_response = OAuthASResponse.authorizationResponse(request, HttpServletResponse.SC_FOUND)
.location(_redirectURI)
.setCode(_authzHelper.createOrUpdateAuthCode(_redirectURI, _scope).getCode())
.setParam(org.apache.oltu.oauth2.common.OAuth.OAUTH_STATE, state)
.buildQueryMessage();
break;
case TOKEN:
_response = OAuthResponseUtils.tokenToResponse(OAuth.get().tokenHelper(_oauthRequest.getClientId(), _oauthRequest.getClientSecret(), _oauthRequest.getParam(org.apache.oltu.oauth2.common.OAuth.OAUTH_CODE), uid).createOrUpdateAccessToken(), state);
break;
default:
_response = OAuthResponseUtils.badRequest(OAuthError.CodeResponse.UNSUPPORTED_RESPONSE_TYPE);
}
return _response;
}
示例2: testTokenAuth
import org.apache.oltu.oauth2.common.message.types.ResponseType; //导入依赖的package包/类
@Test
public void testTokenAuth() throws Exception {
responseType = ResponseType.TOKEN.toString();
MvcResult result = mockMvc
.perform(
get("/authentication").param("client_id", clientID).param("response_type", responseType)
.param("redirect_uri", redirectUri).param("state", "public")
.accept(MediaTypes.HAL_JSON)).andExpect(status().isFound()) // 302
.andReturn();
String redirect = result.getResponse().getRedirectedUrl();
assertTrue(redirect.matches(".*access_token=.*"));
Pattern pattern = Pattern.compile(".*access_token=([^&]*)");
Matcher matcher = pattern.matcher(redirect);
String accessToken = null;
if (matcher.find()) {
accessToken = matcher.group(1);
}
mockMvc.perform(get("/users/1").header("Authorization", "Bearer " + accessToken).accept(MediaTypes.HAL_JSON))
.andExpect(status().isOk()) // 200
.andExpect(content().contentType(MediaTypes.HAL_JSON)) // 验证响应contentType
.andReturn();
mockMvc.perform(get("/users/1")).andExpect(status().isUnauthorized()) // 401
.andReturn();
}
示例3: authorize
import org.apache.oltu.oauth2.common.message.types.ResponseType; //导入依赖的package包/类
@RequestMapping("/authorize/{channel}")
public ModelAndView authorize(@PathVariable String channel, Model model) throws Exception {
OpenAPI openAPI = dispatcher.dispatch(channel);
OpenAPIConfig config = openAPI.getOpenAPIConfig();
OAuthClientRequest request = OAuthClientRequest
.authorizationLocation(config.getCodeUrl())
.setClientId(config.getAppkey())
.setRedirectURI(config.getRedirectUri())
.setResponseType(ResponseType.CODE.toString())
.setScope(config.getScope())
.setState(config.getState())
.buildQueryMessage();
return new ModelAndView(new RedirectView(request.getLocationUri()));
}
示例4: OAuth
import org.apache.oltu.oauth2.common.message.types.ResponseType; //导入依赖的package包/类
public OAuth(Client client, OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) {
this(client, OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes), OAuthClientRequest.authorizationLocation(authorizationUrl).setScope(scopes));
switch (flow) {
case accessCode:
tokenRequestBuilder.setGrantType(GrantType.AUTHORIZATION_CODE);
authenticationRequestBuilder.setResponseType(ResponseType.CODE.name().toLowerCase());
break;
case implicit:
tokenRequestBuilder.setGrantType(GrantType.IMPLICIT);
authenticationRequestBuilder.setResponseType(ResponseType.TOKEN.name().toLowerCase());
break;
case password:
tokenRequestBuilder.setGrantType(GrantType.PASSWORD);
break;
case application:
tokenRequestBuilder.setGrantType(GrantType.CLIENT_CREDENTIALS);
break;
default:
break;
}
}
示例5: getAuthCode
import org.apache.oltu.oauth2.common.message.types.ResponseType; //导入依赖的package包/类
/**
* 获取授权码
* @return
*/
private static String getAuthCode() throws Exception{
Map<String,Object> params = new LinkedHashMap<String,Object>();
params.put("username",ClientParams.USERNAME);
params.put("password",ClientParams.PASSWORD);
params.put("client_id",ClientParams.CLIENT_ID);
params.put("response_type", ResponseType.CODE.toString());
params.put("redirect_uri",ClientParams.OAUTH_SERVER_REDIRECT_URI);
StringBuilder postStr = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (postStr.length() != 0){postStr.append('&');}
postStr.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postStr.append('=');
postStr.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postStrBytes = postStr.toString().getBytes("UTF-8");
URL url = new URL(ClientParams.OAUTH_SERVER_URL);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod(HttpMethod.POST);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", String.valueOf(postStrBytes.length));
connection.getOutputStream().write(postStrBytes);
((HttpURLConnection) connection).setInstanceFollowRedirects(false);// 必须设置该属性
String location = connection.getHeaderField("Location");
System.out.println(location);
return location.substring(location.indexOf("=")+1);
}
示例6: processOAuthRequest
import org.apache.oltu.oauth2.common.message.types.ResponseType; //导入依赖的package包/类
/**
* process new OAuth request
*
* @param request
* HTTP request
* @param response
* HTTP response
* @return always return false
* @throws IOException
* If an input or output exception occurs
* @throws OAuthSystemException
* If an OAuth system exception occurs
* @throws OAuthProblemException
* If an OAuth problem exception occurs
*/
protected boolean processOAuthRequest(HttpServletRequest request, HttpServletResponse response)
throws IOException, OAuthProblemException, OAuthSystemException {
I18N i18n = new I18N(request.getLocale());
OAuthAuthzRequest oAuthRequest = new OAuthAuthzRequest(request);
String clientId = oAuthRequest.getClientId();
String redirectURI = oAuthRequest.getRedirectURI();
// check client id
if (!oAuthService.checkClient(clientId))
return ResponseUtils.processResponse(response, redirectURI,
ResponseUtils.responseInvalidClient(i18n.getString("INVALID_CLIENT_ID")));
// check response type
String responseType = oAuthRequest.getResponseType();
if (!ResponseType.CODE.toString().equals(responseType))
return ResponseUtils.processResponse(response, redirectURI,
ResponseUtils.responseInvalidRequest(i18n.getString("UNSUPPORT_RESP_TYPE")));
// check scopes
Set<String> scopes = oAuthRequest.getScopes();
if (scopes.isEmpty() && oAuthService.scopeRequired(clientId))
return ResponseUtils.processResponse(response, redirectURI,
ResponseUtils.responseInvalidScope(i18n.getString("SCOPE_REQUIRED")));
for (String scope : scopes) {
if (!oAuthService.checkScope(clientId, scope))
return ResponseUtils.processResponse(response, redirectURI,
ResponseUtils.responseInvalidScope(i18n.getString("INVALID_SCOPE") + " " + scope));
}
// determine whether need confirmation or not
String confirmationURI = oAuthService.confirmationURI(clientId, scopes);
if (!OAuthUtils.isEmpty(confirmationURI))
return redirectToConfirmation(request, response, oAuthRequest, confirmationURI);
// generate authorization code and redirect back
return generateAuthorizationCode(request, response, new SavedOAuthRequest(oAuthRequest));
}
示例7: getQueryURI
import org.apache.oltu.oauth2.common.message.types.ResponseType; //导入依赖的package包/类
/**
* get full authorize URI with parameters
*
* @return full authorize URI with parameters
*/
public String getQueryURI() {
URIBuilder builder = new URIBuilder(URI.create(authorizeURI));
builder.addParameter(OAuth.OAUTH_RESPONSE_TYPE, ResponseType.CODE.toString());
builder.addParameter(OAuth.OAUTH_CLIENT_ID, clientId);
if (scopes != null)
builder.addParameter(OAuth.OAUTH_SCOPE, OAuthUtils.encodeScopes(scopes));
return builder.addParameter(OAuth.OAUTH_STATE, state).toString();
}
示例8: validateAccessDelegation
import org.apache.oltu.oauth2.common.message.types.ResponseType; //导入依赖的package包/类
@Override
public boolean validateAccessDelegation(OAuthAuthzReqMessageContext oauthAuthzMsgCtx)
throws IdentityOAuth2Exception {
OAuth2AuthorizeReqDTO authzReqDTO = oauthAuthzMsgCtx.getAuthorizationReqDTO();
String responseType = authzReqDTO.getResponseType();
OAuthAppDO oAuthAppDO = (OAuthAppDO)oauthAuthzMsgCtx.getProperty("OAuthAppDO");
// If the application has defined a limited set of grant types, then check the grant
if (oAuthAppDO.getGrantTypes() != null) {
if (ResponseType.CODE.toString().equals(responseType)) {
//Do not change this log format as these logs use by external applications
if (!oAuthAppDO.getGrantTypes().contains("authorization_code")) {
log.debug("Unsupported Response Type : " + responseType +
" for client id : " + authzReqDTO.getConsumerKey());
handleErrorRequest(oauthAuthzMsgCtx, OAuthError.CodeResponse.UNSUPPORTED_RESPONSE_TYPE,
"Unsupported Response Type!");
return false;
}
} else if (StringUtils.contains(responseType, ResponseType.TOKEN.toString()) &&
!oAuthAppDO.getGrantTypes().contains(IMPLICIT)) {
//Do not change this log format as these logs use by external applications
log.debug("Unsupported Response Type : " + responseType + " for client id : " + authzReqDTO
.getConsumerKey());
handleErrorRequest(oauthAuthzMsgCtx, OAuthError.CodeResponse.UNSUPPORTED_RESPONSE_TYPE,
"Unsupported Response Type!");
return false;
}
}
OAuth2AuthorizeReqDTO authorizationReqDTO = oauthAuthzMsgCtx.getAuthorizationReqDTO();
OAuthCallback authzCallback = new OAuthCallback(authorizationReqDTO.getUser(),
authorizationReqDTO.getConsumerKey(), OAuthCallback.OAuthCallbackType.ACCESS_DELEGATION_AUTHZ);
authzCallback.setRequestedScope(authorizationReqDTO.getScopes());
authzCallback.setResponseType(authorizationReqDTO.getResponseType());
callbackManager.handleCallback(authzCallback);
oauthAuthzMsgCtx.setValidityPeriod(authzCallback.getValidityPeriod());
return authzCallback.isAuthorized();
}
示例9: generateForwardUrl
import org.apache.oltu.oauth2.common.message.types.ResponseType; //导入依赖的package包/类
public String generateForwardUrl(String registrationEndpoint, String authorizeUrl, String returnUrl) throws ServerException, UserException {
try (DatabaseSession session = getBimServer().getDatabase().createSession()) {
OAuthServer oAuthServer = session.querySingle(StorePackage.eINSTANCE.getOAuthServer_RegistrationEndpoint(), registrationEndpoint);
if (oAuthServer == null) {
throw new UserException("Application not registered");
}
OAuthClientRequest request2 = OAuthClientRequest.authorizationLocation(authorizeUrl).setParameter("auth_type", "service").setClientId(oAuthServer.getClientId()).setRedirectURI(returnUrl).setResponseType(ResponseType.CODE.toString()).setState("state").buildQueryMessage();
return request2.getLocationUri();
} catch (Exception e) {
return handleException(e);
}
}
示例10: getAuthorizationRequest
import org.apache.oltu.oauth2.common.message.types.ResponseType; //导入依赖的package包/类
/**
* Build an OAuth authorization request.
*
* @param clientId The OAuth client id obtained from tvtag.
* @param redirectUri The URI to redirect to with appended auth code query parameter.
* @throws OAuthSystemException
*/
public static OAuthClientRequest getAuthorizationRequest(String clientId, String redirectUri)
throws OAuthSystemException {
return OAuthClientRequest
.authorizationLocation(OAUTH2_AUTHORIZATION_URL)
.setScope("public read write")
.setResponseType(ResponseType.CODE.toString())
.setClientId(clientId)
.setRedirectURI(redirectUri)
.buildQueryMessage();
}
示例11: isCode
import org.apache.oltu.oauth2.common.message.types.ResponseType; //导入依赖的package包/类
public boolean isCode() {
return ResponseType.CODE.name().equalsIgnoreCase(this.getResponseType());
}
示例12: isToken
import org.apache.oltu.oauth2.common.message.types.ResponseType; //导入依赖的package包/类
public boolean isToken() {
return ResponseType.TOKEN.name().equalsIgnoreCase(this.getResponseType());
}
示例13: makeAuthCodeRequest
import org.apache.oltu.oauth2.common.message.types.ResponseType; //导入依赖的package包/类
/**
* 获取授权码
* @return
* @throws OAuthSystemException
* @throws MalformedURLException
* @throws URISyntaxException
*/
private static Response makeAuthCodeRequest() throws OAuthSystemException,
MalformedURLException, URISyntaxException {
// OAuthClientRequest request = OAuthClientRequest
// .authorizationLocation(ClientParams.OAUTH_SERVER_URL) // oauth2 认证授权地址
// .setClientId(ClientParams.CLIENT_ID) // CLIENT_ID
// .setRedirectURI(ClientParams.OAUTH_SERVER_REDIRECT_URI) // 回调地址
// .setResponseType(ResponseType.CODE.toString()) // 返回类型值
// .buildQueryMessage();
// 创建表单,模拟填充表单并提交表单
Form form = new Form();
form.param("username",ClientParams.USERNAME);
form.param("password",ClientParams.PASSWORD);
form.param("client_id",ClientParams.CLIENT_ID);
form.param("response_type",ResponseType.CODE.toString());
form.param("redirect_uri",ClientParams.OAUTH_SERVER_REDIRECT_URI);
ResteasyClient client = new ResteasyClientBuilder().build();
Response response = client.target(ClientParams.OAUTH_SERVER_URL)
.request()
.post(Entity.form(form));
System.out.println(response.getStatus());
String location = response.getLocation().toURL().toString();
System.out.println(response.getLocation());
String authCode = location.substring(location.lastIndexOf("=")+1);
try {
System.out.println(authCode);
makeTokenRequestWithAuthCode(authCode);
} catch (OAuthProblemException e) {
e.printStackTrace();
} finally {
}
return response;
}
示例14: processOpenID
import org.apache.oltu.oauth2.common.message.types.ResponseType; //导入依赖的package包/类
protected void processOpenID(HttpServletRequest request, HttpServletResponse response, String provider, String returnURL, boolean isRegister) {
HttpSession session = request.getSession();
String state = generateState();
session.setAttribute(SA_REGISTRATION, isRegister);
session.setAttribute(SA_OPENID_PROVIDER, provider);
session.setAttribute(SA_STATE, state);
if (returnURL == null || returnURL.isEmpty()) {
returnURL = "/ui/admin";
}
if (Oauth2Util.istUseHttps()) {
returnURL = returnURL.replaceFirst("^/", "");
returnURL = uriInfo.getBaseUri().toString() + returnURL;
log.info(String.format("OAuth returnURL is %s", returnURL));
String secureReturnURL = returnURL.replace("http://", "https://");
session.setAttribute(SA_RETURN_URL, secureReturnURL);
} else {
session.setAttribute(SA_RETURN_URL, returnURL);
}
if (provider == null || provider.isEmpty()) {
provider = DEFAULT_PROVIDER;
}
log.info("Authentication request for " + provider + (isRegister ? " (registration)" : ""));
String responseURL = uriInfo.getBaseUri().toString() + "system/security/responseoa";
if (Oauth2Util.istUseHttps()) {
responseURL = responseURL.replace("http://", "https://");
}
log.info(String.format("response URL for auth request: %s", responseURL));
session.setAttribute(SA_RESPONSE_URL, responseURL);
try
{
// obtain a AuthRequest message to be sent to the OpenID provider
OAuthClientRequest oauthRequest = OAuthClientRequest
.authorizationProvider(OAuthProviderType.GOOGLE)
.setClientId(Oauth2Util.getClientId())
.setRedirectURI(responseURL)
.setResponseType(ResponseType.CODE.toString())
.setScope(GOOGLE_SCOPE)
.setState(state)
.buildQueryMessage();
// For version2 endpoints can do a form-redirect but this is easier,
// Relies on payload being less ~ 2k, currently ~ 800 bytes
response.sendRedirect(oauthRequest.getLocationUri());
}
catch (Exception e)
{
throw new WebApiException(Status.BAD_REQUEST, "Login/registration action failed: " + e);
}
}
示例15: doFilter
import org.apache.oltu.oauth2.common.message.types.ResponseType; //导入依赖的package包/类
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (request instanceof HttpServletRequest
&& response instanceof HttpServletResponse) {
// we're only interested in HTTP traffic
HttpServletRequest httpRequest = (HttpServletRequest)request;
String uid = null;
HttpSession session = httpRequest.getSession(false);
if (session != null) {
Object uidObject = session.getAttribute(UID_ATTRIBUTE);
if (uidObject != null && uidObject instanceof String) {
uid = (String)uidObject;
}
}
if (AccessTokenStorage.getInstance().containsTokenFor(uid)) {
// user is authenticated, OK
} else {
// no access token ready, need to authenticate
String uri = httpRequest.getScheme()
+ "://"
+ httpRequest.getServerName()
+ ("http".equals(httpRequest.getScheme())
&& httpRequest.getServerPort() == 80
|| "https".equals(httpRequest.getScheme())
&& httpRequest.getServerPort() == 443 ? ""
: ":" + httpRequest.getServerPort())
+ httpRequest.getRequestURI()
+ (httpRequest.getQueryString() != null ? "?"
+ httpRequest.getQueryString() : "");
try {
OAuthClientRequest authRequest = OAuthClientRequest
.authorizationLocation(
AuthenticationServlet.AUTHORIZATION_LOCATION)
.setResponseType(ResponseType.CODE.toString())
.setClientId(AuthenticationServlet.CLIENT_ID)
.setState(uri)
.setRedirectURI(AuthenticationServlet.REDIRECT_URI)
.buildQueryMessage();
// send the client to the authentication process
((HttpServletResponse) response).sendRedirect(authRequest
.getLocationUri());
return;
} catch (OAuthSystemException e) {
throw new ServletException(e);
}
}
}
// pass the request along the filter chain
chain.doFilter(request, response);
}