Skip to content

Commit 2a5327e

Browse files
Rujun Chenrujche
andauthored
Make code easier to read (Azure#15101)
* No logic change, just make code easier to read. * Add class: AccessTokenClaims. * No logic change, just make code easier to read. * Remame AccessTokenClaim to AccessTokenClaims. * Combine 2 kinds of Exception, delete ErrorCode. * Add AADOAuth2ErrorCode. * Rename AccessTokenClaim to AADAccessTokenClaim. * No logic change, just make code easier to read. * setStatus before sendRedirect. * No logic change, just make code easier to read. * Fix error reported by maven-checkstyle-plugin. Co-authored-by: Rujun Chen <rujche@microsoft.com>
1 parent d113b38 commit 2a5327e

File tree

5 files changed

+85
-54
lines changed

5 files changed

+85
-54
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
2+
// Licensed under the MIT License.
3+
4+
package com.microsoft.azure.spring.autoconfigure.aad;
5+
6+
/**
7+
* Refs: https://docs.microsoft.com/en-us/azure/active-directory/develop/access-tokens
8+
*/
9+
public class AADAccessTokenClaim {
10+
11+
/**
12+
* Provides a human-readable value that identifies the subject of the token. The value is not guaranteed to be
13+
* unique, it is mutable, and it's designed to be used only for display purposes. The profile scope is required in
14+
* order to receive this claim.
15+
*/
16+
public static final String NAME = "name";
17+
}

sdk/spring/azure-spring-boot/src/main/java/com/microsoft/azure/spring/autoconfigure/aad/AADAuthenticationFailureHandler.java

Lines changed: 28 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -23,41 +23,43 @@
2323
* configured on Azure Active Directory.
2424
*/
2525
public class AADAuthenticationFailureHandler implements AuthenticationFailureHandler {
26-
27-
private AuthenticationFailureHandler defaultHandler;
26+
private static final String DEFAULT_FAILURE_URL = "/login?error";
27+
private final AuthenticationFailureHandler defaultHandler;
2828

2929
public AADAuthenticationFailureHandler() {
30-
this.defaultHandler = new SimpleUrlAuthenticationFailureHandler(Constants.FAILURE_DEFAULT_URL);
30+
this.defaultHandler = new SimpleUrlAuthenticationFailureHandler(DEFAULT_FAILURE_URL);
3131
}
3232

3333
@Override
3434
public void onAuthenticationFailure(HttpServletRequest request,
3535
HttpServletResponse response,
3636
AuthenticationException exception) throws IOException, ServletException {
37-
final OAuth2AuthenticationException targetException = (OAuth2AuthenticationException) exception;
3837
// Handle conditional access policy
39-
if (Constants.CONDITIONAL_ACCESS_POLICY.equals((targetException.getError().getErrorCode()))) {
40-
// Get infos
41-
final Throwable cause = targetException.getCause();
42-
if (cause instanceof MsalServiceException) {
43-
// Put claims into session
44-
Optional.of(cause)
45-
.map(c -> (MsalServiceException) c)
46-
.map(MsalServiceException::claims)
47-
.ifPresent(claims -> request.getSession().setAttribute(Constants.CAP_CLAIMS, claims));
48-
// Redirect
49-
String redirectUrl = Optional.of(request)
50-
.map(HttpServletRequest::getSession)
51-
.map(s -> s.getAttribute(Constants.SAVED_REQUEST))
52-
.map(r -> (DefaultSavedRequest) r)
53-
.map(DefaultSavedRequest::getRedirectUrl)
54-
.orElse(null);
55-
response.sendRedirect(redirectUrl);
56-
response.setStatus(302);
57-
return;
58-
}
38+
MsalServiceException msalServiceException = (MsalServiceException)
39+
Optional.of(exception)
40+
.filter(e -> e instanceof OAuth2AuthenticationException)
41+
.map(e -> (OAuth2AuthenticationException) e)
42+
.filter(e -> AADOAuth2ErrorCode.CONDITIONAL_ACCESS_POLICY.equals((e.getError().getErrorCode())))
43+
.map(Throwable::getCause)
44+
.filter(cause -> cause instanceof MsalServiceException)
45+
.orElse(null);
46+
if (msalServiceException == null) {
47+
// Default handle logic
48+
defaultHandler.onAuthenticationFailure(request, response, exception);
49+
} else {
50+
// Put claims into session
51+
Optional.of(msalServiceException)
52+
.map(MsalServiceException::claims)
53+
.ifPresent(claims -> request.getSession().setAttribute(Constants.CAP_CLAIMS, claims));
54+
// Redirect
55+
response.setStatus(302);
56+
String redirectUrl = Optional.of(request)
57+
.map(HttpServletRequest::getSession)
58+
.map(s -> s.getAttribute(Constants.SAVED_REQUEST))
59+
.map(r -> (DefaultSavedRequest) r)
60+
.map(DefaultSavedRequest::getRedirectUrl)
61+
.orElse(null);
62+
response.sendRedirect(redirectUrl);
5963
}
60-
// Default handle logic
61-
defaultHandler.onAuthenticationFailure(request, response, exception);
6264
}
6365
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
2+
// Licensed under the MIT License.
3+
4+
package com.microsoft.azure.spring.autoconfigure.aad;
5+
6+
public class AADOAuth2ErrorCode {
7+
public static final String CONDITIONAL_ACCESS_POLICY = "conditional_access_policy";
8+
public static final String INVALID_REQUEST = "invalid_request";
9+
public static final String SERVER_SERVER = "server_error";
10+
}

sdk/spring/azure-spring-boot/src/main/java/com/microsoft/azure/spring/autoconfigure/aad/AADOAuth2UserService.java

Lines changed: 30 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -21,23 +21,22 @@
2121
import java.util.Optional;
2222
import java.util.Set;
2323

24+
import static com.microsoft.azure.spring.autoconfigure.aad.AADOAuth2ErrorCode.CONDITIONAL_ACCESS_POLICY;
25+
import static com.microsoft.azure.spring.autoconfigure.aad.AADOAuth2ErrorCode.INVALID_REQUEST;
26+
import static com.microsoft.azure.spring.autoconfigure.aad.AADOAuth2ErrorCode.SERVER_SERVER;
27+
2428
/**
2529
* This implementation will retrieve group info of user from Microsoft Graph and map groups to {@link GrantedAuthority}.
2630
*/
2731
public class AADOAuth2UserService implements OAuth2UserService<OidcUserRequest, OidcUser> {
28-
private static final String CONDITIONAL_ACCESS_POLICY = "conditional_access_policy";
29-
private static final String INVALID_REQUEST = "invalid_request";
30-
private static final String SERVER_ERROR = "server_error";
31-
private static final String DEFAULT_USERNAME_ATTR_NAME = "name";
32-
33-
private AADAuthenticationProperties aadAuthProps;
34-
private ServiceEndpointsProperties serviceEndpointsProps;
35-
private OidcUserService oidcUserService;
32+
private final AADAuthenticationProperties aadAuthenticationProperties;
33+
private final ServiceEndpointsProperties serviceEndpointsProperties;
34+
private final OidcUserService oidcUserService;
3635

37-
public AADOAuth2UserService(AADAuthenticationProperties aadAuthProps,
38-
ServiceEndpointsProperties serviceEndpointsProps) {
39-
this.aadAuthProps = aadAuthProps;
40-
this.serviceEndpointsProps = serviceEndpointsProps;
36+
public AADOAuth2UserService(AADAuthenticationProperties aadAuthenticationProperties,
37+
ServiceEndpointsProperties serviceEndpointsProperties) {
38+
this.aadAuthenticationProperties = aadAuthenticationProperties;
39+
this.serviceEndpointsProperties = serviceEndpointsProperties;
4140
this.oidcUserService = new OidcUserService();
4241
}
4342

@@ -50,25 +49,28 @@ public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2Authenticatio
5049
// https://github.com/MicrosoftDocs/azure-docs/issues/8121#issuecomment-387090099
5150
// In AAD App Registration configure oauth2AllowImplicitFlow to true
5251
final ClientRegistration registration = userRequest.getClientRegistration();
53-
final AzureADGraphClient graphClient = new AzureADGraphClient(
52+
final AzureADGraphClient azureADGraphClient = new AzureADGraphClient(
5453
registration.getClientId(),
5554
registration.getClientSecret(),
56-
aadAuthProps,
57-
serviceEndpointsProps
55+
aadAuthenticationProperties,
56+
serviceEndpointsProperties
5857
);
59-
String graphApiToken = graphClient
60-
.acquireTokenForGraphApi(userRequest.getIdToken().getTokenValue(), aadAuthProps.getTenantId())
58+
String graphApiToken = azureADGraphClient
59+
.acquireTokenForGraphApi(
60+
userRequest.getIdToken().getTokenValue(),
61+
aadAuthenticationProperties.getTenantId()
62+
)
6163
.accessToken();
62-
mappedAuthorities = graphClient.getGrantedAuthorities(graphApiToken);
64+
mappedAuthorities = azureADGraphClient.getGrantedAuthorities(graphApiToken);
6365
} catch (MalformedURLException e) {
64-
throw wrapException(INVALID_REQUEST, "Failed to acquire token for Graph API.", null, e);
66+
throw toOAuth2AuthenticationException(INVALID_REQUEST, "Failed to acquire token for Graph API.", e);
6567
} catch (ServiceUnavailableException e) {
66-
throw wrapException(SERVER_ERROR, "Failed to acquire token for Graph API.", null, e);
68+
throw toOAuth2AuthenticationException(SERVER_SERVER, "Failed to acquire token for Graph API.", e);
6769
} catch (IOException e) {
68-
throw wrapException(SERVER_ERROR, "Failed to map group to authorities.", null, e);
70+
throw toOAuth2AuthenticationException(SERVER_SERVER, "Failed to map group to authorities.", e);
6971
} catch (MsalServiceException e) {
7072
if (e.claims() != null && !e.claims().isEmpty()) {
71-
throw wrapException(CONDITIONAL_ACCESS_POLICY, "Handle conditional access policy", null, e);
73+
throw toOAuth2AuthenticationException(CONDITIONAL_ACCESS_POLICY, "Handle conditional access policy", e);
7274
} else {
7375
throw e;
7476
}
@@ -79,13 +81,15 @@ public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2Authenticatio
7981
.map(ClientRegistration.ProviderDetails::getUserInfoEndpoint)
8082
.map(ClientRegistration.ProviderDetails.UserInfoEndpoint::getUserNameAttributeName)
8183
.filter(s -> !s.isEmpty())
82-
.orElse(DEFAULT_USERNAME_ATTR_NAME);
84+
.orElse(AADAccessTokenClaim.NAME);
8385
// Create a copy of oidcUser but use the mappedAuthorities instead
8486
return new DefaultOidcUser(mappedAuthorities, oidcUser.getIdToken(), nameAttributeKey);
8587
}
8688

87-
private OAuth2AuthenticationException wrapException(String errorCode, String errDesc, String uri, Exception e) {
88-
final OAuth2Error oAuth2Error = new OAuth2Error(errorCode, errDesc, uri);
89-
throw new OAuth2AuthenticationException(oAuth2Error, e);
89+
private OAuth2AuthenticationException toOAuth2AuthenticationException(String errorCode,
90+
String description,
91+
Exception cause) {
92+
OAuth2Error oAuth2Error = new OAuth2Error(errorCode, description, null);
93+
return new OAuth2AuthenticationException(oAuth2Error, cause);
9094
}
9195
}

sdk/spring/azure-spring-boot/src/main/java/com/microsoft/azure/spring/autoconfigure/aad/Constants.java

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,8 @@
44
package com.microsoft.azure.spring.autoconfigure.aad;
55

66
public class Constants {
7-
public static final String CONDITIONAL_ACCESS_POLICY = "conditional_access_policy";
87
public static final String SAVED_REQUEST = "SPRING_SECURITY_SAVED_REQUEST";
98
public static final String CAP_CLAIMS = "CAP_Claims";
109
public static final String CLAIMS = "claims";
11-
public static final String FAILURE_DEFAULT_URL = "/login?error";
1210
public static final String OBJECT_TYPE_GROUP = "Group";
1311
}

0 commit comments

Comments
 (0)