Skip to content

Commit 43c9028

Browse files
committed
refactored the code
1 parent 69dc5fb commit 43c9028

File tree

7 files changed

+88
-78
lines changed

7 files changed

+88
-78
lines changed

pom.xml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,9 @@
3030
<rooms.version>1.4.3</rooms.version>
3131
<click.version>1.5.0</click.version>
3232
<monitor.version>1.4.0</monitor.version>
33-
<admin.version>2.0.0-RC1</admin.version>
34-
<webforms.version>1.0.2-RC12</webforms.version>
35-
<maestro.version>2.0.0-RC1</maestro.version>
33+
<admin.version>2.0.0-RC2</admin.version>
34+
<webforms.version>2.0.0-RC1</webforms.version>
35+
<maestro.version>2.0.0</maestro.version>
3636
<swagger-core-version>2.2.22</swagger-core-version>
3737
<jackson-version>2.17.2</jackson-version>
3838
<jersey2.version>3.1.8</jersey2.version>

src/main/java/com/docusign/DSConfiguration.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ public ManifestStructure getCodeExamplesText() {
168168

169169
try {
170170
codeExamplesText = new ObjectMapper().readValue(loadFileData(codeExamplesManifest),
171-
ManifestStructure.class);
171+
ManifestStructure.class);
172172
} catch (Exception e) {
173173
e.printStackTrace();
174174
}
@@ -182,8 +182,8 @@ public String loadFileData(String linkToManifestFile) throws Exception {
182182
httpConnection.setRequestMethod(HttpMethod.GET);
183183

184184
httpConnection.setRequestProperty(
185-
HttpHeaders.CONTENT_TYPE,
186-
String.valueOf(MediaType.APPLICATION_JSON));
185+
HttpHeaders.CONTENT_TYPE,
186+
String.valueOf(MediaType.APPLICATION_JSON));
187187

188188
int responseCode = httpConnection.getResponseCode();
189189

src/main/java/com/docusign/WebSecurityConfig.java

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -24,27 +24,27 @@ public RequestCache requestCache() {
2424
@Bean
2525
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
2626
http
27-
.authorizeHttpRequests(authorize -> {
28-
try {
29-
authorize
30-
.antMatchers("/", "/error**", "/assets/**", "/ds/mustAuthenticate**",
31-
"/ds/authenticate**", "/ds/selectApi**", "/con001", "/pkce")
32-
.permitAll()
33-
.anyRequest().authenticated()
34-
.and()
35-
.exceptionHandling()
36-
.authenticationEntryPoint(
37-
new LoginUrlAuthenticationEntryPoint("/ds/mustAuthenticate"));
38-
} catch (Exception e) {
39-
throw new RuntimeException(e);
40-
}
41-
})
42-
.requestCache().requestCache(requestCache()).and()
43-
.oauth2Login(Customizer.withDefaults())
44-
.oauth2Client(Customizer.withDefaults())
45-
.logout(logout -> logout
46-
.logoutSuccessUrl("/"))
47-
.csrf().disable();
27+
.authorizeHttpRequests(authorize -> {
28+
try {
29+
authorize
30+
.antMatchers("/", "/error**", "/assets/**", "/ds/mustAuthenticate**",
31+
"/ds/authenticate**", "/ds/selectApi**", "/con001", "/pkce")
32+
.permitAll()
33+
.anyRequest().authenticated()
34+
.and()
35+
.exceptionHandling()
36+
.authenticationEntryPoint(
37+
new LoginUrlAuthenticationEntryPoint("/ds/mustAuthenticate"));
38+
} catch (Exception e) {
39+
throw new RuntimeException(e);
40+
}
41+
})
42+
.requestCache().requestCache(requestCache()).and()
43+
.oauth2Login(Customizer.withDefaults())
44+
.oauth2Client(Customizer.withDefaults())
45+
.logout(logout -> logout
46+
.logoutSuccessUrl("/"))
47+
.csrf().disable();
4848

4949
return http.build();
5050
}

src/main/java/com/docusign/core/controller/IndexController.java

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ public String index(ModelMap model, HttpServletResponse response) throws Excepti
9595
}
9696

9797
if (config.getQuickstart().equals("true") && config.getSelectedApiIndex().equals(ApiIndex.ESIGNATURE) &&
98-
!(SecurityContextHolder.getContext().getAuthentication() instanceof OAuth2AuthenticationToken)) {
98+
!(SecurityContextHolder.getContext().getAuthentication() instanceof OAuth2AuthenticationToken)) {
9999
String site = ApiIndex.ESIGNATURE.getPathOfFirstExample();
100100
response.setStatus(response.SC_MOVED_TEMPORARILY);
101101
response.setHeader(LOCATION_HEADER, site);
@@ -114,7 +114,7 @@ public String index(ModelMap model, HttpServletResponse response) throws Excepti
114114

115115
@GetMapping(path = "/ds/mustAuthenticate")
116116
public ModelAndView mustAuthenticateController(ModelMap model, HttpServletRequest req, HttpServletResponse resp)
117-
throws IOException {
117+
throws IOException {
118118
model.addAttribute(LAUNCHER_TEXTS, config.getCodeExamplesText().SupportingTexts);
119119
model.addAttribute(ATTR_TITLE, config.getCodeExamplesText().SupportingTexts.LoginPage.LoginButton);
120120

@@ -127,8 +127,8 @@ public ModelAndView mustAuthenticateController(ModelMap model, HttpServletReques
127127
return new ModelAndView(new JWTAuthenticationMethod().loginUsingJWT(config, session, redirectURL));
128128
}
129129

130-
boolean isRedirectToMonitor = redirectURL.toLowerCase().contains("/m")
131-
&& !redirectURL.toLowerCase().contains("/mae");
130+
boolean isRedirectToMonitor = redirectURL.toLowerCase().contains("/m") &&
131+
!redirectURL.toLowerCase().contains("/mae");
132132
if (session.isRefreshToken() || config.getQuickstart().equals("true")) {
133133
config.setQuickstart("false");
134134

@@ -153,7 +153,7 @@ private ModelAndView checkForMonitorRedirects(String redirectURL) {
153153

154154
@GetMapping("/pkce")
155155
public RedirectView pkce(String code, String state, HttpServletRequest req, HttpServletResponse resp)
156-
throws Exception {
156+
throws Exception {
157157
String redirectURL = getRedirectURLForJWTAuthentication(req, resp);
158158
RedirectView redirect;
159159
try {
@@ -167,16 +167,16 @@ public RedirectView pkce(String code, String state, HttpServletRequest req, Http
167167
}
168168

169169
@PostMapping("/ds/authenticate")
170-
public RedirectView authenticate(ModelMap model, @RequestBody MultiValueMap<String, String> formParams,
171-
HttpServletRequest req, HttpServletResponse resp) throws Exception {
170+
public RedirectView authenticate(ModelMap model, @RequestBody MultiValueMap <String, String> formParams,
171+
HttpServletRequest req, HttpServletResponse resp) throws Exception {
172172
if (!formParams.containsKey("selectAuthType")) {
173173
model.addAttribute("message", "Select option with selectAuthType name must be provided.");
174174
return new RedirectView("pages/error");
175175
}
176176

177177
String redirectURL = getRedirectURLForJWTAuthentication(req, resp);
178178

179-
List<String> selectAuthTypeObject = formParams.get("selectAuthType");
179+
List <String> selectAuthTypeObject = formParams.get("selectAuthType");
180180
AuthType authTypeSelected = AuthType.valueOf(selectAuthTypeObject.get(0));
181181

182182
if (authTypeSelected.equals(AuthType.JWT)) {
@@ -196,7 +196,7 @@ private String getRedirectURLForJWTAuthentication(HttpServletRequest req, HttpSe
196196
SavedRequest savedRequest = requestCache.getRequest(req, resp);
197197

198198
String[] examplesCodes = new String[] {
199-
ApiIndex.CLICK.getExamplesPathCode(),
199+
ApiIndex.CLICK.getExamplesPathCode(),
200200
ApiIndex.ESIGNATURE.getExamplesPathCode(),
201201
ApiIndex.MONITOR.getExamplesPathCode(),
202202
ApiIndex.ADMIN.getExamplesPathCode(),
@@ -209,7 +209,7 @@ private String getRedirectURLForJWTAuthentication(HttpServletRequest req, HttpSe
209209

210210
if (indexOfExampleCodeInRedirect != -1) {
211211
Boolean hasNumbers = savedRequest.getRedirectUrl().substring(indexOfExampleCodeInRedirect)
212-
.matches(".*\\d.*");
212+
.matches(".*\\d.*");
213213

214214
return "GET".equals(savedRequest.getMethod()) && hasNumbers ? savedRequest.getRedirectUrl() : "/";
215215
}
@@ -220,8 +220,8 @@ private String getRedirectURLForJWTAuthentication(HttpServletRequest req, HttpSe
220220

221221
@GetMapping(path = "/ds-return")
222222
public String returnController(@RequestParam(value = ATTR_STATE, required = false) String state,
223-
@RequestParam(value = ATTR_EVENT, required = false) String event,
224-
@RequestParam(required = false) String envelopeId, ModelMap model) {
223+
@RequestParam(value = ATTR_EVENT, required = false) String event,
224+
@RequestParam(required = false) String envelopeId, ModelMap model) {
225225
model.addAttribute(LAUNCHER_TEXTS, config.getCodeExamplesText().SupportingTexts);
226226
model.addAttribute(ATTR_TITLE, "Return from DocuSign");
227227
model.addAttribute(ATTR_EVENT, event);
@@ -244,4 +244,4 @@ private String getLoginPath(AuthType authTypeSelected) {
244244
}
245245
return loginPath;
246246
}
247-
}
247+
}

src/main/java/com/docusign/core/security/JWTOAuth2User.java

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,9 @@
99
import java.util.*;
1010

1111
public class JWTOAuth2User implements OAuth2User {
12-
private List<GrantedAuthority> authorities;
12+
private List <GrantedAuthority> authorities;
1313

14-
private Map<String, Object> attributes;
14+
private Map <String, Object> attributes;
1515

1616
private String sub;
1717

@@ -25,27 +25,27 @@ public class JWTOAuth2User implements OAuth2User {
2525

2626
private String email;
2727

28-
private List<Map<String, Object>> accounts;
28+
private List <Map <String, Object>> accounts;
2929

3030
private String created;
3131

3232
@Override
33-
public Collection<? extends GrantedAuthority> getAuthorities() {
33+
public Collection <? extends GrantedAuthority> getAuthorities() {
3434
return this.authorities;
3535
}
3636

37-
public void setAuthorities(List<String> scopes) {
37+
public void setAuthorities(List < String > scopes) {
3838
String authoritiesString = "ROLE_USER";
39-
for (String scope : scopes) {
39+
for (String scope: scopes) {
4040
authoritiesString += ",SCOPE_" + scope;
4141
}
4242
authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(authoritiesString);
4343
}
4444

4545
@Override
46-
public Map<String, Object> getAttributes() {
46+
public Map <String, Object> getAttributes() {
4747
if (this.attributes == null) {
48-
this.attributes = new HashMap<>();
48+
this.attributes = new HashMap <> ();
4949
this.attributes.put("sub", this.getSub());
5050
this.attributes.put("name", this.getName());
5151
this.attributes.put("given_name", this.getGivenName());
@@ -115,15 +115,15 @@ public void setEmail(String email) {
115115
this.email = email;
116116
}
117117

118-
public List<Map<String, Object>> getAccounts() {
118+
public List <Map <String, Object>> getAccounts() {
119119
return this.accounts;
120120
}
121121

122-
public void setAccounts(List<OAuth.Account> accounts) {
123-
this.accounts = new ArrayList<>();
124-
for (OAuth.Account account : accounts) {
122+
public void setAccounts(List <OAuth.Account> accounts) {
123+
this.accounts = new ArrayList <> ();
124+
for (OAuth.Account account: accounts) {
125125
ObjectMapper mapObject = new ObjectMapper();
126-
Map<String, Object> mapObj = mapObject.convertValue(account, Map.class);
126+
Map <String, Object> mapObj = mapObject.convertValue(account, Map.class);
127127
this.accounts.add(mapObj);
128128
}
129129
}

src/main/java/com/docusign/core/security/SecurityHelpers.java

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,13 @@ public static String parseJsonField(String jsonResponse, String field) throws IO
4545
return jsonNode.get(field).asText();
4646
}
4747

48-
public static void setSpringSecurityAuthentication(List<String> scopes, String oAuthToken, OAuth.UserInfo userInfo,
49-
String accountId, Session session, String expiresIn) {
48+
public static void setSpringSecurityAuthentication(
49+
List<String> scopes,
50+
String oAuthToken,
51+
OAuth.UserInfo userInfo,
52+
String accountId,
53+
Session session,
54+
String expiresIn) {
5055
JWTOAuth2User principal = new JWTOAuth2User();
5156
principal.setAuthorities(scopes);
5257
principal.setCreated(userInfo.getCreated());

src/main/java/com/docusign/core/security/acg/ACGAuthenticationMethod.java

Lines changed: 28 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -19,41 +19,46 @@
1919

2020
public class ACGAuthenticationMethod {
2121
private static final String REDIRECT_URI = "/pkce";
22+
2223
private static final String STATE = "random_state_string";
24+
2325
private static String codeVerifier;
26+
2427
private static String codeChallenge;
2528

2629
public RedirectView initiateAuthorization(DSConfiguration configuration) throws Exception {
27-
List<String> scopes = SecurityHelpers.getScopeList();
30+
List <String> scopes = SecurityHelpers.getScopeList();
2831

2932
codeVerifier = SecurityHelpers.generateCodeVerifier();
3033
codeChallenge = SecurityHelpers.generateCodeChallenge(codeVerifier);
3134

3235
String authorizationURL = String.format(
33-
"%s&redirect_uri=%s&scope=%s&client_id=%s&state=%s&response_type=code&code_challenge=%s&code_challenge_method=S256",
34-
configuration.getAuthorizationEndpoint(),
35-
URLEncoder.encode(configuration.getAppUrl() + REDIRECT_URI, StandardCharsets.UTF_8),
36-
URLEncoder.encode(String.join(" ", scopes), StandardCharsets.UTF_8), configuration.getUserId(), STATE,
37-
codeChallenge);
36+
"%s&redirect_uri=%s&scope=%s&client_id=%s&state=%s&response_type=code&code_challenge=%s&code_challenge_method=S256",
37+
configuration.getAuthorizationEndpoint(),
38+
URLEncoder.encode(configuration.getAppUrl() + REDIRECT_URI, StandardCharsets.UTF_8),
39+
URLEncoder.encode(String.join(" ", scopes), StandardCharsets.UTF_8), configuration.getUserId(), STATE,
40+
codeChallenge);
3841

3942
return new RedirectView(authorizationURL);
4043
}
4144

42-
public RedirectView exchangeCodeForToken(String oAuthToken, DSConfiguration configuration, Session session,
43-
String redirect)
44-
throws Exception {
45+
public RedirectView exchangeCodeForToken(
46+
String oAuthToken,
47+
DSConfiguration configuration,
48+
Session session,
49+
String redirect) throws Exception {
4550
String requestBody = buildRequestBody(oAuthToken);
4651
String authHeader = generateAuthHeader(configuration);
4752

4853
HttpClient client = HttpClient.newHttpClient();
4954
HttpRequest request = HttpRequest.newBuilder()
50-
.uri(URI.create(configuration.getTokenEndpoint()))
51-
.header("Authorization", "Basic " + authHeader)
52-
.header("Content-Type", "application/x-www-form-urlencoded")
53-
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
54-
.build();
55+
.uri(URI.create(configuration.getTokenEndpoint()))
56+
.header("Authorization", "Basic " + authHeader)
57+
.header("Content-Type", "application/x-www-form-urlencoded")
58+
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
59+
.build();
5560

56-
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
61+
HttpResponse <String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
5762

5863
if (response.statusCode() == 200) {
5964
processTokenResponse(response.body(), configuration, session);
@@ -66,18 +71,18 @@ public RedirectView exchangeCodeForToken(String oAuthToken, DSConfiguration conf
6671

6772
private String buildRequestBody(String oAuthToken) throws IOException {
6873
return "grant_type=authorization_code" +
69-
"&code=" + URLEncoder.encode(oAuthToken, StandardCharsets.UTF_8) +
70-
"&redirect_uri=" + URLEncoder.encode(REDIRECT_URI, StandardCharsets.UTF_8) +
71-
"&code_verifier=" + URLEncoder.encode(codeVerifier, StandardCharsets.UTF_8);
74+
"&code=" + URLEncoder.encode(oAuthToken, StandardCharsets.UTF_8) +
75+
"&redirect_uri=" + URLEncoder.encode(REDIRECT_URI, StandardCharsets.UTF_8) +
76+
"&code_verifier=" + URLEncoder.encode(codeVerifier, StandardCharsets.UTF_8);
7277
}
7378

7479
private String generateAuthHeader(DSConfiguration configuration) {
7580
return Base64.getEncoder().encodeToString(
76-
(configuration.getUserId() + ":" + configuration.getSecretUserId()).getBytes(StandardCharsets.UTF_8));
81+
(configuration.getUserId() + ":" + configuration.getSecretUserId()).getBytes(StandardCharsets.UTF_8));
7782
}
7883

7984
private void processTokenResponse(String responseBody, DSConfiguration configuration, Session session)
80-
throws Exception {
85+
throws Exception {
8186
ApiClient apiClient = new ApiClient(configuration.getBasePath());
8287
String accessToken = SecurityHelpers.parseJsonField(responseBody, "access_token");
8388
String expiresIn = SecurityHelpers.parseJsonField(responseBody, "expires_in");
@@ -86,7 +91,7 @@ private void processTokenResponse(String responseBody, DSConfiguration configura
8691
String accountId = userInfo.getAccounts().size() > 0 ? userInfo.getAccounts().get(0).getAccountId() : "";
8792

8893
SecurityHelpers.setSpringSecurityAuthentication(SecurityHelpers.getScopeList(), accessToken, userInfo,
89-
accountId, session,
90-
expiresIn);
94+
accountId, session,
95+
expiresIn);
9196
}
92-
}
97+
}

0 commit comments

Comments
 (0)