Search in sources :

Example 31 with OAuthProblemException

use of org.apache.oltu.oauth2.common.exception.OAuthProblemException in project irida by phac-nml.

the class OltuAuthorizationController method getToken.

/**
 * Receive the OAuth2 authorization code and request an OAuth2 token
 *
 * @param request
 *            The incoming request
 * @param response
 *            The response to redirect
 * @param apiId
 *            the Long ID of the API we're requesting from
 * @param redirect
 *            The URL location to redirect to after completion
 * @return A ModelAndView redirecting back to the resource that was
 *         requested
 * @throws IOException
 * @throws OAuthSystemException
 * @throws OAuthProblemException
 * @throws URISyntaxException
 */
@RequestMapping("/token")
public ModelAndView getToken(HttpServletRequest request, HttpServletResponse response, @RequestParam("redirect") String redirect) throws IOException, OAuthSystemException, OAuthProblemException, URISyntaxException {
    // Get the OAuth2 auth code
    OAuthAuthzResponse oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
    String code = oar.getCode();
    logger.debug("got code " + code);
    // Read the RemoteAPI from the RemoteAPIService and get the base URI
    // Build the token location for this service
    URI serviceTokenLocation = UriBuilder.fromUri(serviceURI).path("oauth").path("token").build();
    logger.debug("token loc " + serviceTokenLocation);
    // Build the redirect URI to request a token from
    String tokenRedirect = buildRedirectURI(redirect);
    // Create the token request form the given auth code
    OAuthClientRequest tokenRequest = OAuthClientRequest.tokenLocation(serviceTokenLocation.toString()).setClientId(clientId).setClientSecret(clientSecret).setRedirectURI(tokenRedirect).setCode(code).setGrantType(GrantType.AUTHORIZATION_CODE).buildBodyMessage();
    // execute the request
    OAuthClient client = new OAuthClient(new URLConnectionClient());
    // read the response for the access token
    OAuthJSONAccessTokenResponse accessTokenResponse = client.accessToken(tokenRequest, OAuthJSONAccessTokenResponse.class);
    String accessToken = accessTokenResponse.getAccessToken();
    // check the token expiry
    Long expiresIn = accessTokenResponse.getExpiresIn();
    logger.debug("Token expires in " + expiresIn);
    // adding the token to the response page. This is just a demo to show
    // how to get an oauth token. NEVER DO THIS!!!
    redirect = redirect + "?token=" + accessToken;
    // redirect the response back to the requested resource
    return new ModelAndView(new RedirectView(redirect));
}
Also used : URLConnectionClient(org.apache.oltu.oauth2.client.URLConnectionClient) OAuthClient(org.apache.oltu.oauth2.client.OAuthClient) ModelAndView(org.springframework.web.servlet.ModelAndView) RedirectView(org.springframework.web.servlet.view.RedirectView) OAuthJSONAccessTokenResponse(org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) OAuthAuthzResponse(org.apache.oltu.oauth2.client.response.OAuthAuthzResponse) URI(java.net.URI) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 32 with OAuthProblemException

use of org.apache.oltu.oauth2.common.exception.OAuthProblemException in project irida by phac-nml.

the class GalaxyRedirectionEndpointController method passAuthCode.

/**
 * Receive the OAuth2 authorization code from IRIDA and pass it on to the client-side code
 * @param model
 *            the model to write to
 * @param request
 *            the incoming request
 * @param session
 *            the user's session
 * @return a template that will pass on the authorization code
 * @throws OAuthProblemException if a valid OAuth authorization response cannot be created
 * @throws IllegalStateException if the callback URL is removed from an invalid session
 */
@RequestMapping("galaxy/auth_code")
public String passAuthCode(Model model, HttpServletRequest request, HttpSession session) throws OAuthProblemException, IllegalStateException {
    logger.debug("Parsing auth code from HttpServletRequest");
    // Get the OAuth2 authorization code
    OAuthAuthzResponse oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
    String code = oar.getCode();
    model.addAttribute("auth_code", code);
    session.removeAttribute("galaxyExportToolCallbackURL");
    return "templates/galaxy_auth_code.tmpl";
}
Also used : OAuthAuthzResponse(org.apache.oltu.oauth2.client.response.OAuthAuthzResponse) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 33 with OAuthProblemException

use of org.apache.oltu.oauth2.common.exception.OAuthProblemException in project irida by phac-nml.

the class OltuAuthorizationController method getTokenFromAuthCode.

/**
 * Receive the OAuth2 authorization code and request an OAuth2 token
 *
 * @param request
 *            The incoming request
 * @param response
 *            The response to redirect
 * @param apiId
 *            the Long ID of the API we're requesting from
 * @param redirect
 *            The URL location to redirect to after completion
 * @return A ModelAndView redirecting back to the resource that was
 *         requested
 * @throws OAuthSystemException
 *             if we can't get an access token for the current request.
 * @throws OAuthProblemException
 *             if we can't get a response from the authorization server
 */
@RequestMapping(TOKEN_ENDPOINT)
public String getTokenFromAuthCode(HttpServletRequest request, HttpServletResponse response, @RequestParam("apiId") Long apiId, @RequestParam("redirect") String redirect) throws OAuthSystemException, OAuthProblemException {
    // Get the OAuth2 auth code
    OAuthAuthzResponse oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
    String code = oar.getCode();
    logger.trace("Received auth code: " + code);
    // Build the redirect URI to request a token from
    String tokenRedirect = buildRedirectURI(apiId, redirect);
    // Read the RemoteAPI from the RemoteAPIService and get the base URI
    RemoteAPI remoteAPI = remoteAPIService.read(apiId);
    tokenService.createTokenFromAuthCode(code, remoteAPI, tokenRedirect);
    // redirect the response back to the requested resource
    return "redirect:" + redirect;
}
Also used : RemoteAPI(ca.corefacility.bioinformatics.irida.model.RemoteAPI) OAuthAuthzResponse(org.apache.oltu.oauth2.client.response.OAuthAuthzResponse) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 34 with OAuthProblemException

use of org.apache.oltu.oauth2.common.exception.OAuthProblemException in project structr by structr.

the class StructrOAuthClient method getCode.

private static String getCode(final HttpServletRequest request) {
    OAuthAuthzResponse oar;
    try {
        logger.info("Trying to get authorization code from request {}", request);
        oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
        String code = oar.getCode();
        logger.info("Got code {} from authorization request", code);
        return oar.getCode();
    } catch (OAuthProblemException e) {
        logger.error("Could not read authorization request: {}, {}", new Object[] { e.getError(), e.getDescription() });
    }
    return null;
}
Also used : OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) OAuthAuthzResponse(org.apache.oltu.oauth2.client.response.OAuthAuthzResponse)

Example 35 with OAuthProblemException

use of org.apache.oltu.oauth2.common.exception.OAuthProblemException in project dq-easy-cloud by dq-open-cloud.

the class EcAuthorizeController method authorize.

@RequestMapping("/toAuthorize")
public Object authorize(Model model, HttpServletRequest request) throws URISyntaxException, OAuthSystemException {
    // http://localhost:8100/authorize/toAuthorize?redirect_uri=https://www.baidu.com/&response_type=code&client_id=1&state=bb38108d1aaf567c72da0f1167e87142d0e20cb2bb24ec5a
    try {
        // 构建OAuth 授权请求
        OAuthAuthzRequest oauthRequest = new OAuthAuthzRequest(request);
        boolean checkClient = false;
        // 检查传入的客户端id是否正确
        if (checkClient) {
            OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).setError(OAuthError.TokenResponse.INVALID_CLIENT).setErrorDescription("非法用户").buildJSONMessage();
            return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
        }
        Subject subject = SecurityUtils.getSubject();
        // 如果用户没有登录,跳转到登陆页面
        if (!subject.isAuthenticated()) {
            if (!login(subject, request)) {
                // model.addAttribute("client", clientService.findByClientId(oauthRequest.getClientId()));
                return "oauth2login";
            }
        }
        String username = (String) subject.getPrincipal();
        // 生成授权码
        String authorizationCode = null;
        // responseType目前仅支持CODE,另外还有TOKEN
        String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);
        if (responseType.equals(ResponseType.CODE.toString())) {
            OAuthIssuerImpl oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
            authorizationCode = oauthIssuerImpl.authorizationCode();
            codeCache.put(authorizationCode, "zhangsan");
        // oAuthService.addAuthCode(authorizationCode, username);
        }
        // 进行OAuth响应构建
        OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse.authorizationResponse(request, HttpServletResponse.SC_FOUND);
        // 设置授权码
        builder.setCode(authorizationCode);
        // 得到到客户端重定向地址
        String redirectURI = oauthRequest.getParam(OAuth.OAUTH_REDIRECT_URI);
        // 构建响应
        final OAuthResponse response = builder.location(redirectURI).buildQueryMessage();
        // 根据OAuthResponse返回ResponseEntity响应
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(new URI(response.getLocationUri()));
        return new ResponseEntity(headers, HttpStatus.valueOf(response.getResponseStatus()));
    } catch (OAuthProblemException e) {
        logger.error(e.getMessage(), e);
        // 出错处理
        String redirectUri = e.getRedirectUri();
        if (OAuthUtils.isEmpty(redirectUri)) {
            // 告诉客户端没有传入redirectUri直接报错
            return new ResponseEntity("OAuth callback url needs to be provided by client!!!", HttpStatus.NOT_FOUND);
        }
        // 返回错误消息(如?error=)
        final OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_FOUND).error(e).location(redirectUri).buildQueryMessage();
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(new URI(response.getLocationUri()));
        return new ResponseEntity(headers, HttpStatus.valueOf(response.getResponseStatus()));
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) URI(java.net.URI) Subject(org.apache.shiro.subject.Subject) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) OAuthIssuerImpl(org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl) ResponseEntity(org.springframework.http.ResponseEntity) OAuthAuthzRequest(org.apache.oltu.oauth2.as.request.OAuthAuthzRequest) MD5Generator(org.apache.oltu.oauth2.as.issuer.MD5Generator) OAuthASResponse(org.apache.oltu.oauth2.as.response.OAuthASResponse) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)24 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)20 IOException (java.io.IOException)15 OAuthClientRequest (org.apache.oltu.oauth2.client.request.OAuthClientRequest)15 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)12 MediaType (okhttp3.MediaType)9 Request (okhttp3.Request)9 RequestBody (okhttp3.RequestBody)9 Response (okhttp3.Response)9 OAuthClientResponse (org.apache.oltu.oauth2.client.response.OAuthClientResponse)9 Builder (okhttp3.Request.Builder)8 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)8 URI (java.net.URI)6 MD5Generator (org.apache.oltu.oauth2.as.issuer.MD5Generator)5 OAuthAccessResourceRequest (org.apache.oltu.oauth2.rs.request.OAuthAccessResourceRequest)5 OAuthIssuerImpl (org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl)4 OAuthAuthzResponse (org.apache.oltu.oauth2.client.response.OAuthAuthzResponse)4 OAuthJSONAccessTokenResponse (org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse)4 AccessToken (io.github.tesla.authz.domain.AccessToken)3 ServletException (javax.servlet.ServletException)3