Search in sources :

Example 11 with Verifier

use of org.scribe.model.Verifier in project restful-android by jeremyhaberman.

the class AuthorizationManager method getAccessToken.

/**
 * Creates an access token
 *
 * @param intent
 *            an Intent with a Uri as its data. The Uri must contain a query
 *            string parameter named 'oauth_verifier'.
 * @param oAuthService
 *            OAuthService
 * @param requestToken
 *            the request token that was used for authorization
 * @return access token (or null if it failed)
 */
private Token getAccessToken(Intent intent, OAuthService oAuthService, Token requestToken) {
    if (oAuthService == null || requestToken == null) {
        return null;
    }
    Uri uri = intent.getData();
    if (uri == null) {
        return null;
    }
    String oAuthVerifierString = uri.getQueryParameter("oauth_verifier");
    if (oAuthVerifierString != null) {
        Verifier oAuthVerifier = new Verifier(oAuthVerifierString);
        return oAuthService.getAccessToken(requestToken, oAuthVerifier);
    } else {
        return null;
    }
}
Also used : Verifier(org.scribe.model.Verifier) Uri(android.net.Uri)

Example 12 with Verifier

use of org.scribe.model.Verifier in project openolat by klemens.

the class OAuthDispatcher method execute.

@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String uri = request.getRequestURI();
    try {
        uri = URLDecoder.decode(uri, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new AssertException("UTF-8 encoding not supported!!!!");
    }
    String uriPrefix = DispatcherModule.getLegacyUriPrefix(request);
    UserRequest ureq = null;
    try {
        // upon creation URL is checked for
        ureq = new UserRequestImpl(uriPrefix, request, response);
    } catch (NumberFormatException nfe) {
        if (log.isDebug()) {
            log.debug("Bad Request " + request.getPathInfo());
        }
        DispatcherModule.sendBadRequest(request.getPathInfo(), response);
        return;
    }
    String error = request.getParameter("error");
    if (null != error) {
        error(ureq, translateOauthError(ureq, error));
        return;
    }
    String problem = request.getParameter("oauth_problem");
    if (problem != null && "token_rejected".equals(problem.trim())) {
        error(ureq, translateOauthError(ureq, error));
        return;
    }
    try {
        HttpSession sess = request.getSession();
        // OAuth 2.0 hasn't any request token
        Token requestToken = (Token) sess.getAttribute(OAuthConstants.REQUEST_TOKEN);
        OAuthService service = (OAuthService) sess.getAttribute(OAuthConstants.OAUTH_SERVICE);
        OAuthSPI provider = (OAuthSPI) sess.getAttribute(OAuthConstants.OAUTH_SPI);
        Token accessToken;
        if (provider == null) {
            log.audit("OAuth Login failed, no provider in request");
            DispatcherModule.redirectToDefaultDispatcher(response);
            return;
        } else if (provider.isImplicitWorkflow()) {
            String idToken = ureq.getParameter("id_token");
            if (idToken == null) {
                redirectImplicitWorkflow(ureq);
                return;
            } else {
                Verifier verifier = OpenIDVerifier.create(ureq, sess);
                accessToken = service.getAccessToken(requestToken, verifier);
            }
        } else {
            String requestVerifier = request.getParameter("oauth_verifier");
            if (requestVerifier == null) {
                // OAuth 2.0 as a code
                requestVerifier = request.getParameter("code");
            }
            accessToken = service.getAccessToken(requestToken, new Verifier(requestVerifier));
        }
        OAuthUser infos = provider.getUser(service, accessToken);
        if (infos == null || !StringHelper.containsNonWhitespace(infos.getId())) {
            error(ureq, translate(ureq, "error.no.id"));
            log.error("OAuth Login failed, no infos extracted from access token: " + accessToken);
            return;
        }
        OAuthRegistration registration = new OAuthRegistration(provider.getProviderName(), infos);
        login(infos, registration);
        if (provider instanceof OAuthUserCreator) {
            OAuthUserCreator userCreator = (OAuthUserCreator) provider;
            if (registration.getIdentity() != null) {
                Identity newIdentity = userCreator.updateUser(infos, registration.getIdentity());
                registration.setIdentity(newIdentity);
            }
        }
        if (provider instanceof OAuthUserCreator && registration.getIdentity() == null) {
            disclaimer(request, response, infos, (OAuthUserCreator) provider);
        } else if (registration.getIdentity() == null) {
            if (CoreSpringFactory.getImpl(OAuthLoginModule.class).isAllowUserCreation()) {
                register(request, response, registration);
            } else {
                error(ureq, translate(ureq, "error.account.creation"));
                log.error("OAuth Login ok but the user has not an account on OpenOLAT: " + infos);
            }
        } else {
            if (ureq.getUserSession() != null) {
                // re-init the activity logger
                ThreadLocalUserActivityLoggerInstaller.initUserActivityLogger(request);
            }
            Identity identity = registration.getIdentity();
            int loginStatus = AuthHelper.doLogin(identity, provider.getProviderName(), ureq);
            if (loginStatus != AuthHelper.LOGIN_OK) {
                if (loginStatus == AuthHelper.LOGIN_NOTAVAILABLE) {
                    DispatcherModule.redirectToServiceNotAvailable(response);
                } else {
                    // error, redirect to login screen
                    DispatcherModule.redirectToDefaultDispatcher(response);
                }
            } else {
                // update last login date and register active user
                UserDeletionManager.getInstance().setIdentityAsActiv(identity);
                MediaResource mr = ureq.getDispatchResult().getResultingMediaResource();
                if (mr instanceof RedirectMediaResource) {
                    RedirectMediaResource rmr = (RedirectMediaResource) mr;
                    rmr.prepare(response);
                } else {
                    // error, redirect to login screen
                    DispatcherModule.redirectToDefaultDispatcher(response);
                }
            }
        }
    } catch (Exception e) {
        log.error("Unexpected error", e);
        error(ureq, translate(ureq, "error.generic"));
    }
}
Also used : AssertException(org.olat.core.logging.AssertException) HttpSession(javax.servlet.http.HttpSession) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Token(org.scribe.model.Token) OpenIDVerifier(org.olat.login.oauth.spi.OpenIDVerifier) Verifier(org.scribe.model.Verifier) AssertException(org.olat.core.logging.AssertException) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) OAuthService(org.scribe.oauth.OAuthService) OAuthUser(org.olat.login.oauth.model.OAuthUser) OAuthRegistration(org.olat.login.oauth.model.OAuthRegistration) RedirectMediaResource(org.olat.core.gui.media.RedirectMediaResource) MediaResource(org.olat.core.gui.media.MediaResource) RedirectMediaResource(org.olat.core.gui.media.RedirectMediaResource) Identity(org.olat.core.id.Identity) UserRequest(org.olat.core.gui.UserRequest) UserRequestImpl(org.olat.core.gui.UserRequestImpl)

Example 13 with Verifier

use of org.scribe.model.Verifier in project muikku by otavanopisto.

the class PyramusAuthenticationStrategy method processResponse.

@Override
protected AuthenticationResult processResponse(AuthSource authSource, Map<String, String[]> requestParameters, OAuthService service, String[] requestedScopes) {
    ObjectMapper objectMapper = new ObjectMapper();
    String verifier = getFirstRequestParameter(requestParameters, "code");
    Verifier v = new Verifier(verifier);
    Token accessToken = service.getAccessToken(null, v);
    PyramusAccessToken pyramusAccessToken;
    try {
        pyramusAccessToken = objectMapper.readValue(accessToken.getRawResponse(), PyramusAccessToken.class);
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(new Date());
        calendar.add(Calendar.SECOND, pyramusAccessToken.getExpiresIn());
        Date expires = calendar.getTime();
        sessionController.addOAuthAccessToken("pyramus", expires, accessToken.getToken(), pyramusAccessToken.getRefreshToken());
    } catch (IOException e) {
        logger.log(Level.SEVERE, "Token extraction failed a JSON parsing error", e);
        return new AuthenticationResult(AuthenticationResult.Status.ERROR);
    }
    WhoAmI whoAmI = null;
    OAuthRequest request = new OAuthRequest(Verb.GET, getWhoAmIUrl());
    service.signRequest(accessToken, request);
    Response response = request.send();
    try {
        whoAmI = objectMapper.readValue(response.getBody(), WhoAmI.class);
    } catch (IOException e) {
        logger.log(Level.SEVERE, "Logging in failed because of a JSON parsing exception", e);
        return new AuthenticationResult(AuthenticationResult.Status.ERROR);
    }
    return processLogin(authSource, requestParameters, whoAmI.getId().toString(), whoAmI.getEmails(), whoAmI.getFirstName(), whoAmI.getLastName());
}
Also used : OAuthRequest(org.scribe.model.OAuthRequest) Calendar(java.util.Calendar) GregorianCalendar(java.util.GregorianCalendar) GregorianCalendar(java.util.GregorianCalendar) Token(org.scribe.model.Token) IOException(java.io.IOException) Verifier(org.scribe.model.Verifier) Date(java.util.Date) AuthenticationResult(fi.otavanopisto.muikku.auth.AuthenticationResult) Response(org.scribe.model.Response) WhoAmI(fi.otavanopisto.pyramus.rest.model.WhoAmI) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 14 with Verifier

use of org.scribe.model.Verifier in project pyramus by otavanopisto.

the class GoogleOauthAuthorizationStrategy method processResponse.

public User processResponse(RequestContext requestContext) throws AuthenticationException {
    HttpServletRequest req = requestContext.getRequest();
    HttpSession session = req.getSession();
    String authCode = req.getParameter("code");
    Verifier verifier = new Verifier(authCode);
    OAuthService service = new ServiceBuilder().provider(GoogleApi20.class).apiKey(this.getClientId()).apiSecret(this.getClientSecret()).callback(this.getRedirectUrl()).scope(this.getScope()).build();
    Token accessToken = service.getAccessToken(null, verifier);
    OAuthRequest request = new OAuthRequest(Verb.GET, "https://www.googleapis.com/oauth2/v1/userinfo?alt=json");
    service.signRequest(accessToken, request);
    Response response = request.send();
    JSONObject userInfo = JSONObject.fromObject(response.getBody());
    if (userInfo != null) {
        try {
            return processLogin(userInfo.getString("id"), userInfo.getString("email"));
        } finally {
            setGoogleLoggedIn(session, true);
        }
    } else {
        throw new AuthenticationException(AuthenticationException.EXTERNAL_LOGIN_SERVER_ERROR);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) OAuthRequest(org.scribe.model.OAuthRequest) Response(org.scribe.model.Response) GoogleApi20(fi.otavanopisto.pyramus.plugin.googleoauth.scribe.GoogleApi20) OAuthService(org.scribe.oauth.OAuthService) JSONObject(net.sf.json.JSONObject) AuthenticationException(fi.otavanopisto.pyramus.plugin.auth.AuthenticationException) HttpSession(javax.servlet.http.HttpSession) Token(org.scribe.model.Token) Verifier(org.scribe.model.Verifier) ServiceBuilder(org.scribe.builder.ServiceBuilder)

Aggregations

Verifier (org.scribe.model.Verifier)14 Token (org.scribe.model.Token)13 IOException (java.io.IOException)7 OAuthRequest (org.scribe.model.OAuthRequest)4 Response (org.scribe.model.Response)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 FlickrException (com.flickr4java.flickr.FlickrException)3 AuthInterface (com.flickr4java.flickr.auth.AuthInterface)3 AuthenticationResult (fi.otavanopisto.muikku.auth.AuthenticationResult)3 Calendar (java.util.Calendar)3 Date (java.util.Date)3 GregorianCalendar (java.util.GregorianCalendar)3 HttpSession (javax.servlet.http.HttpSession)3 OAuthService (org.scribe.oauth.OAuthService)3 Uri (android.net.Uri)2 Get (br.com.caelum.vraptor.Get)2 SocialAPI (org.mamute.auth.SocialAPI)2 ServiceBuilder (org.scribe.builder.ServiceBuilder)2 Auth (com.flickr4java.flickr.auth.Auth)1 AuthenticationException (fi.otavanopisto.pyramus.plugin.auth.AuthenticationException)1