Search in sources :

Example 21 with OAuth20Service

use of com.github.scribejava.core.oauth.OAuth20Service in project tutorials by eugenp.

the class GithubController method authorization.

@GetMapping(value = "/authorization")
public RedirectView authorization(HttpServletRequest servletReq) throws InterruptedException, ExecutionException, IOException {
    String state = String.valueOf(new Random().nextInt(999_999));
    OAuth20Service githubService = createService(state);
    servletReq.getSession().setAttribute("state", state);
    String authorizationUrl = githubService.getAuthorizationUrl();
    RedirectView redirectView = new RedirectView();
    redirectView.setUrl(authorizationUrl);
    return redirectView;
}
Also used : Random(java.util.Random) RedirectView(org.springframework.web.servlet.view.RedirectView) OAuth20Service(com.github.scribejava.core.oauth.OAuth20Service) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 22 with OAuth20Service

use of com.github.scribejava.core.oauth.OAuth20Service in project pac4j by pac4j.

the class OAuth20RedirectActionBuilder method redirect.

@Override
public RedirectAction redirect(final WebContext context) {
    try {
        final OAuth20Service service;
        // with state: generate a state, save it in session and build a new service with this state
        if (this.configuration.isWithState()) {
            final String state = getStateParameter();
            logger.debug("save sessionState: {}", state);
            context.getSessionStore().set(context, this.configuration.getStateSessionAttributeName(client.getName()), state);
            service = this.configuration.buildService(context, client, state);
        } else {
            service = this.configuration.buildService(context, client, null);
        }
        final String authorizationUrl = service.getAuthorizationUrl(this.configuration.getCustomParams());
        logger.debug("authorizationUrl: {}", authorizationUrl);
        return RedirectAction.redirect(authorizationUrl);
    } catch (final OAuthException e) {
        throw new TechnicalException(e);
    }
}
Also used : TechnicalException(org.pac4j.core.exception.TechnicalException) OAuthException(com.github.scribejava.core.exceptions.OAuthException) OAuth20Service(com.github.scribejava.core.oauth.OAuth20Service)

Example 23 with OAuth20Service

use of com.github.scribejava.core.oauth.OAuth20Service in project dataverse by IQSS.

the class AbstractOAuth2AuthenticationProvider method getUserRecord.

public OAuth2UserRecord getUserRecord(String code, String state, String redirectUrl) throws IOException, OAuth2Exception {
    OAuth20Service service = getService(state, redirectUrl);
    OAuth2AccessToken accessToken = service.getAccessToken(code);
    final String userEndpoint = getUserEndpoint(accessToken);
    final OAuthRequest request = new OAuthRequest(Verb.GET, userEndpoint, service);
    request.addHeader("Authorization", "Bearer " + accessToken.getAccessToken());
    request.setCharset("UTF-8");
    final Response response = request.send();
    int responseCode = response.getCode();
    final String body = response.getBody();
    logger.log(Level.FINE, "In getUserRecord. Body: {0}", body);
    if (responseCode == 200) {
        final ParsedUserResponse parsed = parseUserResponse(body);
        return new OAuth2UserRecord(getId(), parsed.userIdInProvider, parsed.username, OAuth2TokenData.from(accessToken), parsed.displayInfo, parsed.emails);
    } else {
        throw new OAuth2Exception(responseCode, body, "Error getting the user info record.");
    }
}
Also used : OAuthRequest(com.github.scribejava.core.model.OAuthRequest) Response(com.github.scribejava.core.model.Response) OAuth2AccessToken(com.github.scribejava.core.model.OAuth2AccessToken) OAuth20Service(com.github.scribejava.core.oauth.OAuth20Service)

Example 24 with OAuth20Service

use of com.github.scribejava.core.oauth.OAuth20Service in project legendarybot by greatman.

the class WoWLinkPlugin method start.

@Override
public void start() {
    // Load the configuration
    props = new Properties();
    try {
        props.load(new FileInputStream("app.properties"));
    } catch (java.io.IOException e) {
        e.printStackTrace();
        getBot().getStacktraceHandler().sendStacktrace(e);
    }
    path("/auth", () -> get("/battlenetcallback", (req, res) -> {
        String state = req.queryParams("state");
        String region = state.split(":")[0];
        OAuth20Service service = new ServiceBuilder(props.getProperty("battlenetoauth.key")).apiSecret(props.getProperty("battlenetoauth.secret")).scope("wow.profile").callback("https://legendarybot.greatmancode.com/auth/battlenetcallback").build(new OAuthBattleNetApi(region));
        String oAuthCode = req.queryParams("code");
        // TODO: Save oauth code to do a character refresh.
        OAuth2AccessToken token = service.getAccessToken(oAuthCode);
        OAuthRequest request = new OAuthRequest(Verb.GET, "https://" + region + ".api.battle.net/wow/user/characters");
        service.signRequest(token, request);
        Response response = service.execute(request);
        JSONParser parser = new JSONParser();
        JSONObject obj = (JSONObject) parser.parse(response.getBody());
        JSONArray charactersArray = (JSONArray) obj.get("characters");
        List<WoWCharacter> characterList = new ArrayList<>();
        charactersArray.forEach((c) -> {
            JSONObject jsonObject = (JSONObject) c;
            if (jsonObject.containsKey("guild")) {
                characterList.add(new WoWCharacter((String) jsonObject.get("name"), ((String) jsonObject.get("realm")).toLowerCase(), (String) jsonObject.get("guild"), region, HeroClass.values()[((Long) jsonObject.get("class")).intValue()]));
                log.info("User " + state.split(":")[1] + " user have the character " + jsonObject.get("name") + " in guild " + jsonObject.get("guild"));
            }
        });
        if (characterList.size() > 0) {
            MongoCollection<Document> collection = getBot().getMongoDatabase().getCollection(MONGO_WOW_CHARACTERS_COLLECTION);
            characterList.forEach((c) -> collection.updateOne(and(eq("region", c.getRegion()), eq("realm", c.getRealm()), eq("name", c.getCharacterName())), and(set("guild", c.getGuild()), set("owner", state.split(":")[1])), new UpdateOptions().upsert(true)));
        }
        return "Your WoW characters are now synced to LegendaryBot!";
    }));
    getBot().getCommandHandler().addCommand("linkwowchars", new LinkWoWCharsCommand(this), "World of Warcraft Character");
    getBot().getCommandHandler().addCommand("guildchars", new GuildCharsCommand(this), "World of Warcraft Character");
    getBot().getCommandHandler().addCommand("setmainchar", new SetMainCharacterCommand(this), "World of Warcraft Character");
    getBot().getCommandHandler().addCommand("enableautorank", new EnableAutoRankCommand(this), "WoW Admin Commands");
    getBot().getCommandHandler().addCommand("disableautorank", new DisableAutoRankCommand(this), "WoW Admin Commands");
    getBot().getCommandHandler().addCommand("setwowrank", new SetWoWRankCommand(this), "WoW Admin Commands");
    getBot().getCommandHandler().addCommand("syncrank", new SyncRankCommand(this), "World of Warcraft Character");
    getBot().getCommandHandler().addCommand("syncguild", new SyncGuildCommand(this), "WoW Admin Commands");
    getBot().getCommandHandler().addCommand("enableautorankupdate", new EnableAutoRankUpdateCommand(this), "WoW Admin Commands");
    getBot().getCommandHandler().addCommand("disableautorankupdate", new DisableAutoRankUpdateCommand(this), "WoW Admin Commands");
    // We load the scheduler
    getBot().getJDA().forEach((jda -> {
        jda.getGuilds().forEach(guild -> {
            if (getBot().getGuildSettings(guild).getSetting(SETTING_SCHEDULER) != null && getBot().getGuildSettings(guild).getSetting(SETTING_RANKSET_ENABLED) != null) {
                scheduler.put(guild.getId(), new SyncRankScheduler(this, guild));
            }
        });
    }));
}
Also used : OAuthBattleNetApi(com.greatmancode.legendarybot.plugins.wowlink.utils.OAuthBattleNetApi) Document(org.bson.Document) Spark.get(spark.Spark.get) java.util(java.util) ServiceBuilder(com.github.scribejava.core.builder.ServiceBuilder) WoWCharacter(com.greatmancode.legendarybot.plugins.wowlink.utils.WoWCharacter) MongoCollection(com.mongodb.client.MongoCollection) LegendaryBotPlugin(com.greatmancode.legendarybot.api.plugin.LegendaryBotPlugin) LoggerFactory(org.slf4j.LoggerFactory) OAuth20Service(com.github.scribejava.core.oauth.OAuth20Service) BattleNetAPIInterceptor(com.greatmancode.legendarybot.api.utils.BattleNetAPIInterceptor) HeroClass(com.greatmancode.legendarybot.api.utils.HeroClass) Spark.path(spark.Spark.path) JSONArray(org.json.simple.JSONArray) PluginWrapper(org.pf4j.PluginWrapper) com.greatmancode.legendarybot.plugins.wowlink.commands(com.greatmancode.legendarybot.plugins.wowlink.commands) PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) Filters.and(com.mongodb.client.model.Filters.and) ParseException(org.json.simple.parser.ParseException) OAuth2AccessToken(com.github.scribejava.core.model.OAuth2AccessToken) GuildSettings(com.greatmancode.legendarybot.api.server.GuildSettings) ResultSet(java.sql.ResultSet) Filters.eq(com.mongodb.client.model.Filters.eq) UpdateOptions(com.mongodb.client.model.UpdateOptions) Updates.unset(com.mongodb.client.model.Updates.unset) Role(net.dv8tion.jda.core.entities.Role) Request(okhttp3.Request) Logger(org.slf4j.Logger) JSONParser(org.json.simple.parser.JSONParser) Verb(com.github.scribejava.core.model.Verb) IOException(java.io.IOException) Filters.exists(com.mongodb.client.model.Filters.exists) FileInputStream(java.io.FileInputStream) Updates.set(com.mongodb.client.model.Updates.set) Guild(net.dv8tion.jda.core.entities.Guild) OkHttpClient(okhttp3.OkHttpClient) JSONObject(org.json.simple.JSONObject) OAuthRequest(com.github.scribejava.core.model.OAuthRequest) Block(com.mongodb.Block) User(net.dv8tion.jda.core.entities.User) Response(com.github.scribejava.core.model.Response) HttpUrl(okhttp3.HttpUrl) Spark(spark.Spark) OAuthRequest(com.github.scribejava.core.model.OAuthRequest) UpdateOptions(com.mongodb.client.model.UpdateOptions) OAuth20Service(com.github.scribejava.core.oauth.OAuth20Service) ServiceBuilder(com.github.scribejava.core.builder.ServiceBuilder) OAuth2AccessToken(com.github.scribejava.core.model.OAuth2AccessToken) WoWCharacter(com.greatmancode.legendarybot.plugins.wowlink.utils.WoWCharacter) JSONArray(org.json.simple.JSONArray) IOException(java.io.IOException) OAuthBattleNetApi(com.greatmancode.legendarybot.plugins.wowlink.utils.OAuthBattleNetApi) FileInputStream(java.io.FileInputStream) Response(com.github.scribejava.core.model.Response) MongoCollection(com.mongodb.client.MongoCollection) JSONObject(org.json.simple.JSONObject) JSONParser(org.json.simple.parser.JSONParser)

Example 25 with OAuth20Service

use of com.github.scribejava.core.oauth.OAuth20Service in project sonarqube by SonarSource.

the class GitHubIdentityProvider method onCallback.

private void onCallback(CallbackContext context) throws InterruptedException, ExecutionException, IOException {
    context.verifyCsrfState();
    HttpServletRequest request = context.getRequest();
    OAuth20Service scribe = newScribeBuilder(context).build(scribeApi);
    String code = request.getParameter("code");
    OAuth2AccessToken accessToken = scribe.getAccessToken(code);
    GsonUser user = gitHubRestClient.getUser(scribe, accessToken);
    check(scribe, accessToken, user);
    final String email;
    if (user.getEmail() == null) {
        // if the user has not specified a public email address in their profile
        email = gitHubRestClient.getEmail(scribe, accessToken);
    } else {
        email = user.getEmail();
    }
    UserIdentity userIdentity = userIdentityFactory.create(user, email, settings.syncGroups() ? gitHubRestClient.getTeams(scribe, accessToken) : null);
    context.authenticate(userIdentity);
    context.redirectToRequestedPage();
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) OAuth2AccessToken(com.github.scribejava.core.model.OAuth2AccessToken) UserIdentity(org.sonar.api.server.authentication.UserIdentity) OAuth20Service(com.github.scribejava.core.oauth.OAuth20Service)

Aggregations

OAuth20Service (com.github.scribejava.core.oauth.OAuth20Service)63 OAuth2AccessToken (com.github.scribejava.core.model.OAuth2AccessToken)49 ServiceBuilder (com.github.scribejava.core.builder.ServiceBuilder)47 OAuthRequest (com.github.scribejava.core.model.OAuthRequest)45 Response (com.github.scribejava.core.model.Response)45 Scanner (java.util.Scanner)40 Random (java.util.Random)17 HashMap (java.util.HashMap)6 OAuthException (com.github.scribejava.core.exceptions.OAuthException)4 NingHttpClientConfig (com.github.scribejava.httpclient.ning.NingHttpClientConfig)3 AsyncHttpClientConfig (com.ning.http.client.AsyncHttpClientConfig)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)3 AsyncSimpleTask (com.codepath.utils.AsyncSimpleTask)2 SalesforceToken (com.github.scribejava.apis.salesforce.SalesforceToken)2 OAuth1RequestToken (com.github.scribejava.core.model.OAuth1RequestToken)2 OAuth10aService (com.github.scribejava.core.oauth.OAuth10aService)2 OAuthBattleNetApi (com.greatmancode.legendarybot.plugins.wowlink.utils.OAuthBattleNetApi)2 IOException (java.io.IOException)2 ExecutionException (java.util.concurrent.ExecutionException)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2