diff --git a/spring-security-oauth/src/main/java/org/baeldung/config/MyAuthorizationCodeAccessTokenProvider.java b/spring-security-oauth/src/main/java/org/baeldung/config/MyAuthorizationCodeAccessTokenProvider.java index 024873c632..c5c7226d10 100644 --- a/spring-security-oauth/src/main/java/org/baeldung/config/MyAuthorizationCodeAccessTokenProvider.java +++ b/spring-security-oauth/src/main/java/org/baeldung/config/MyAuthorizationCodeAccessTokenProvider.java @@ -25,13 +25,14 @@ import org.springframework.security.oauth2.client.token.RequestEnhancer; import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider; import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails; import org.springframework.security.oauth2.common.OAuth2AccessToken; -import org.springframework.security.oauth2.common.OAuth2RefreshToken; import org.springframework.security.oauth2.common.exceptions.InvalidRequestException; import org.springframework.security.oauth2.common.util.OAuth2Utils; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.ResponseExtractor; +import com.google.common.base.Joiner; + public class MyAuthorizationCodeAccessTokenProvider extends AuthorizationCodeAccessTokenProvider { private StateKeyGenerator stateKeyGenerator = new DefaultStateKeyGenerator(); @@ -42,7 +43,6 @@ public class MyAuthorizationCodeAccessTokenProvider extends AuthorizationCodeAcc @Override public String obtainAuthorizationCode(OAuth2ProtectedResourceDetails details, AccessTokenRequest request) throws UserRedirectRequiredException, UserApprovalRequiredException, AccessDeniedException, OAuth2AccessDeniedException { - AuthorizationCodeResourceDetails resource = (AuthorizationCodeResourceDetails) details; HttpHeaders headers = getHeadersForAuthorizationRequest(request); @@ -97,12 +97,10 @@ public class MyAuthorizationCodeAccessTokenProvider extends AuthorizationCodeAcc } request.set("code", code); return code; - } @Override public OAuth2AccessToken obtainAccessToken(OAuth2ProtectedResourceDetails details, AccessTokenRequest request) throws UserRedirectRequiredException, UserApprovalRequiredException, AccessDeniedException, OAuth2AccessDeniedException { - AuthorizationCodeResourceDetails resource = (AuthorizationCodeResourceDetails) details; if (request.getAuthorizationCode() == null) { @@ -112,24 +110,10 @@ public class MyAuthorizationCodeAccessTokenProvider extends AuthorizationCodeAcc obtainAuthorizationCode(resource, request); } return retrieveToken(request, resource, getParametersForTokenRequest(resource, request), getHeadersForTokenRequest(request)); - - } - - @Override - public OAuth2AccessToken refreshAccessToken(OAuth2ProtectedResourceDetails resource, OAuth2RefreshToken refreshToken, AccessTokenRequest request) throws UserRedirectRequiredException, OAuth2AccessDeniedException { - MultiValueMap form = new LinkedMultiValueMap(); - form.add("grant_type", "refresh_token"); - form.add("refresh_token", refreshToken.getValue()); - try { - return retrieveToken(request, resource, form, getHeadersForTokenRequest(request)); - } catch (OAuth2AccessDeniedException e) { - throw getRedirectForAuthorization((AuthorizationCodeResourceDetails) resource, request); - } } private HttpHeaders getHeadersForTokenRequest(AccessTokenRequest request) { HttpHeaders headers = new HttpHeaders(); - // No cookie for token request return headers; } @@ -143,7 +127,6 @@ public class MyAuthorizationCodeAccessTokenProvider extends AuthorizationCodeAcc } private MultiValueMap getParametersForTokenRequest(AuthorizationCodeResourceDetails resource, AccessTokenRequest request) { - MultiValueMap form = new LinkedMultiValueMap(); form.set("grant_type", "authorization_code"); form.set("code", request.getAuthorizationCode()); @@ -167,11 +150,9 @@ public class MyAuthorizationCodeAccessTokenProvider extends AuthorizationCodeAcc } return form; - } private MultiValueMap getParametersForAuthorizeRequest(AuthorizationCodeResourceDetails resource, AccessTokenRequest request) { - MultiValueMap form = new LinkedMultiValueMap(); form.set("response_type", "code"); form.set("client_id", resource.getClientId()); @@ -179,7 +160,7 @@ public class MyAuthorizationCodeAccessTokenProvider extends AuthorizationCodeAcc if (request.get("scope") != null) { form.set("scope", request.getFirst("scope")); } else { - form.set("scope", OAuth2Utils.formatParameterList(resource.getScope())); + form.set("scope", Joiner.on(',').join(resource.getScope())); } String redirectUri = resource.getPreEstablishedRedirectUri(); @@ -204,17 +185,13 @@ public class MyAuthorizationCodeAccessTokenProvider extends AuthorizationCodeAcc } return form; - } private UserRedirectRequiredException getRedirectForAuthorization(AuthorizationCodeResourceDetails resource, AccessTokenRequest request) { - - // we don't have an authorization code yet. So first get that. TreeMap requestParameters = new TreeMap(); - requestParameters.put("response_type", "code"); // oauth2 spec, section 3 + requestParameters.put("response_type", "code"); requestParameters.put("client_id", resource.getClientId()); requestParameters.put("duration", "permanent"); - // Client secret is not required in the initial authorization request String redirectUri = resource.getRedirectUri(request); if (redirectUri != null) { @@ -231,7 +208,7 @@ public class MyAuthorizationCodeAccessTokenProvider extends AuthorizationCodeAcc while (scopeIt.hasNext()) { builder.append(scopeIt.next()); if (scopeIt.hasNext()) { - builder.append(' '); + builder.append(','); } } } @@ -248,7 +225,6 @@ public class MyAuthorizationCodeAccessTokenProvider extends AuthorizationCodeAcc request.setPreservedState(redirectUri); return redirectException; - } } diff --git a/spring-security-oauth/src/main/java/org/baeldung/config/WebConfig.java b/spring-security-oauth/src/main/java/org/baeldung/config/WebConfig.java index 937dfbbd27..06f5915c0a 100644 --- a/spring-security-oauth/src/main/java/org/baeldung/config/WebConfig.java +++ b/spring-security-oauth/src/main/java/org/baeldung/config/WebConfig.java @@ -85,7 +85,7 @@ public class WebConfig extends WebMvcConfigurerAdapter { details.setAccessTokenUri(accessTokenUri); details.setUserAuthorizationUri(userAuthorizationUri); details.setTokenName("oauth_token"); - details.setScope(Arrays.asList("identity")); + details.setScope(Arrays.asList("identity", "read", "submit")); details.setGrantType("authorization_code"); return details; } diff --git a/spring-security-oauth/src/main/java/org/baeldung/web/RedditController.java b/spring-security-oauth/src/main/java/org/baeldung/web/RedditController.java index 4cf73fa098..6398039da2 100644 --- a/spring-security-oauth/src/main/java/org/baeldung/web/RedditController.java +++ b/spring-security-oauth/src/main/java/org/baeldung/web/RedditController.java @@ -1,14 +1,26 @@ package org.baeldung.web; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; import org.springframework.security.oauth2.client.OAuth2RestTemplate; import org.springframework.security.oauth2.client.resource.UserApprovalRequiredException; import org.springframework.security.oauth2.client.resource.UserRedirectRequiredException; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; @@ -36,6 +48,81 @@ public class RedditController { return "reddit"; } + @RequestMapping("/submit") + public String submit(Model model, @RequestParam Map formParams) { + try { + System.out.println(formParams.keySet()); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + HttpEntity req = new HttpEntity(headers); + + Map param = new HashMap(); + param.put("api_type", "json"); + param.put("kind", "self"); + param.put("sr", "api"); + // param.put("iden", "XCzyTdJveIcYXNhLJ4a2X9WVDswtx83u"); + // param.put("captcha", "BJMGMU"); + // param.put("title", "http2 is coming soon"); + // param.put("text", "http2 is coming soon what do you think about that"); + param.putAll(formParams); + + System.out.println(param.keySet()); + System.out.println(param.entrySet()); + ResponseEntity result = redditRestTemplate.postForEntity("https://oauth.reddit.com/api/submit", req, String.class, param); + model.addAttribute("error", result.getBody()); + } catch (UserApprovalRequiredException e) { + throw e; + } catch (UserRedirectRequiredException e) { + throw e; + } catch (Exception e) { + LOGGER.error("Error occurred", e); + model.addAttribute("error", e.getLocalizedMessage()); + } + return "reddit"; + } + + @RequestMapping("/post") + public String showSubmissionForm(Model model) throws JsonProcessingException, IOException { + String needsCaptchaResult = needsCaptcha(); + if (needsCaptchaResult.equalsIgnoreCase("true")) { + String newCaptchaResult = getNewCaptcha(); + String[] split = newCaptchaResult.split("\""); + String iden = split[split.length - 2]; + model.addAttribute("iden", iden.trim()); + } + return "submissionForm"; + } + + // + + public List getSubreddit(Model model) throws JsonProcessingException, IOException { + String result = redditRestTemplate.getForObject("https://oauth.reddit.com/subreddits/popular", String.class); + JsonNode node = new ObjectMapper().readTree(result); + node = node.get("data").get("children"); + List subreddits = new ArrayList(); + for (JsonNode child : node) { + subreddits.add(child.get("data").get("display_name").asText()); + } + return subreddits; + } + + public String needsCaptcha() { + String result = redditRestTemplate.getForObject("https://oauth.reddit.com/api/needs_captcha.json", String.class); + return result; + } + + public String getNewCaptcha() { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + HttpEntity req = new HttpEntity(headers); + + Map param = new HashMap(); + param.put("api_type", "json"); + + ResponseEntity result = redditRestTemplate.postForEntity("https://oauth.reddit.com/api/new_captcha", req, String.class, param); + return result.getBody(); + } + public void setRedditRestTemplate(OAuth2RestTemplate redditRestTemplate) { this.redditRestTemplate = redditRestTemplate; } diff --git a/spring-security-oauth/src/main/webapp/WEB-INF/jsp/reddit.jsp b/spring-security-oauth/src/main/webapp/WEB-INF/jsp/reddit.jsp index 9ea6cb84fe..d0c53411bc 100755 --- a/spring-security-oauth/src/main/webapp/WEB-INF/jsp/reddit.jsp +++ b/spring-security-oauth/src/main/webapp/WEB-INF/jsp/reddit.jsp @@ -9,6 +9,8 @@

Your Reddit Info

Your reddit username is ${info} +
+ Submit to Reddit
Sorry, error occurred diff --git a/spring-security-oauth/src/main/webapp/WEB-INF/jsp/submissionForm.jsp b/spring-security-oauth/src/main/webapp/WEB-INF/jsp/submissionForm.jsp new file mode 100755 index 0000000000..87c03adc9f --- /dev/null +++ b/spring-security-oauth/src/main/webapp/WEB-INF/jsp/submissionForm.jsp @@ -0,0 +1,40 @@ +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> + + + +Spring Security OAuth + + + + +
+

Submit to Reddit

+
+
+
+ + +
+

+
+ + +
+

+ + + +
+ + +
+

+ captcha +
+

+ +
+
+
+ + \ No newline at end of file