Skip to content

Commit

Permalink
refactor aad sample code (Azure#18691)
Browse files Browse the repository at this point in the history
*  refactor aad sample code
  • Loading branch information
backwind1233 authored Jan 25, 2021
1 parent d90271c commit 3a732af
Show file tree
Hide file tree
Showing 8 changed files with 95 additions and 55 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -87,57 +87,53 @@ As a first step you'll need to:
---
### Step 3: Configure the sample to use your Azure AD tenant

In the steps below, "ClientID" is the same as "Application ID" or "AppId".
In the steps below, "client-id" is the same as "Application ID" or "AppId".

Open application.yml in your project to configure:

```yml
azure:
activedirectory:
tenant-id: <your-tenant-id>
client-id: <your-client-id>
client-secret: <your-client-secret>
# Optional, default value is http://localhost:8080/
redirect-uri-template: <your-redirect-uri>
# groups that you created in your Azure AD tenant
user-group:
allowed-groups: group1,group2
# Optional, the default value is
# environment: global
```


Open application.properties in your project to configure:

1. If your azure account follows format xxx@xxx.partner.onmschina.cn, configure property `azure.activedirectory.environment=cn` to use [Azure China](https://docs.microsoft.com/azure/china/china-welcome), the default value is `global`.
1. If your azure account follows format xxx@xxx.partner.onmschina.cn, configure property `environment: cn` to use [Azure China][azure-china], the default value is `global`.

2. Put Application ID and client-secret in `client-id` and `client-secret` respectively e.g.
```properties
azure.activedirectory.client-id=xxxxxx-your-client-id-xxxxxx
azure.activedirectory.client-secret=xxxxxx-your-client-secret-xxxxxx
tenant-id: xxxxxx-your-client-id-xxxxxx
client-id: xxxxxx-your-client-secret-xxxxxx
```

3. List all the AAD groups `ActiveDirectoryGroups` that you want to have a Spring Security role object mapping to it. The role objects can then be used to manage access to resources that is behind Spring Security. e.g.
```properties
# groups that you created in your Azure AD tenant
azure.activedirectory.user-group.allowed-groups=group1,group2
allowed-groups: group1,group2
```

4. (Optional) If you want to configure oauth2 redirect uri, please configure by :
```properties
spring.security.oauth2.client.registration.azure.redirect-uri=xxxxxx-your-redirect-uri-xxxxxx
redirectUriTemplate: xxxxxx-your-redirect-uri-xxxxxx
```

---
---
### Step 4: Change Role_group1 to your group
1. You can use `@PreAuthorize` annotation or `UserPrincipal` to manage access to web API based on user's group membership. You will need to change `ROLE_group1` to groups you want to allow to access the API in `TodoListController.java` or you will get "Access is denied".

---
### Step 5: Angular JS
In `app.js`, make following changes. The client leverages Azure AD library for JS to handle AAD authentication in single page application. The following snippet of code configures msal provider for your registered app. ClientID is your application ID and \<tenant\> is a identifier within the directory itself (e.g. a domain associated to the tenant, such as contoso.onmicrosoft.com, or the GUID representing the TenantID property of the directory).
```js
window.applicationConfig = {
clientID: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
};

msalProvider.init(
{
auth: {
clientId: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
authority: "https://login.microsoftonline.com/<tenant>",
redirectUri: "http://localhost:8080/",
},
cache: {
cacheLocation: "sessionStorage", // This configures where your cache will be stored
storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
}
}
);
```
---

### Step 6: Give it a run
### Step 5: Give it a run

* Run with Maven
```
Expand All @@ -153,4 +149,6 @@ msalProvider.init(
## Contributing

<!-- LINKS -->

[ready-to-run-checklist]: https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/spring/azure-spring-boot-samples/README.md#ready-to-run-checklist
[azure-china]: https://docs.microsoft.com/azure/china/china-welcome
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@
<artifactId>azure-spring-boot-starter-active-directory</artifactId>
<version>3.1.0</version> <!-- {x-version-update;com.azure.spring:azure-spring-boot-starter-active-directory;current} -->
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,13 @@
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;

Expand All @@ -45,6 +47,18 @@ public Map<String, Object> home() {
return model;
}


@RequestMapping({"/"})
public ModelAndView index() {
ModelAndView model = new ModelAndView("index");
model.addObject("aad_clientId", aadAuthenticationProperties.getClientId());
model.addObject("aad_tenantId", aadAuthenticationProperties.getTenantId());
model.addObject("aad_redirectUri", Optional
.ofNullable(aadAuthenticationProperties.getRedirectUriTemplate())
.orElse("http://localhost:8080/") );
return model;
}

/**
* HTTP GET
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,20 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {

http.authorizeRequests().antMatchers("/home").permitAll();
http.authorizeRequests().antMatchers("/api/**").authenticated();

http.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/").deleteCookies("JSESSIONID").invalidateHttpSession(true);

http.authorizeRequests().anyRequest().permitAll();

http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());

http.addFilterBefore(aadAuthFilter, UsernamePasswordAuthenticationFilter.class);
http.authorizeRequests()
.antMatchers("/home").permitAll()
.antMatchers("/api/**").authenticated()
.anyRequest().permitAll()
.and()
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.deleteCookies("JSESSIONID")
.logoutSuccessUrl("/")
.invalidateHttpSession(true)
.and()
.addFilterBefore(aadAuthFilter, UsernamePasswordAuthenticationFilter.class);
}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# By default, azure.activedirectory.environment property has value `global`,
# supported value is global, cn. Please refer to the README for details.
# azure.activedirectory.environment=global
azure:
activedirectory:
tenant-id: <your-tenant-id>
client-id: <your-client-id>
client-secret: <your-client-secret>
# Optional, default value is http://localhost:8080/
# redirect-uri-template: <your-redirect-uri>
# groups that you created in your Azure AD tenant
user-group:
allowed-groups: group1,group2
# Optional, the default value is
# environment: global


Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,14 @@ angular.module('todoApp', ['ngRoute', 'MsalAngular'])
}).otherwise({redirectTo: "/Home"});

window.applicationConfig = {
clientID: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
clientID: window.aad_clientId
};

msalProvider.init(
{
auth: {
clientId: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
authority: "https://login.microsoftonline.com/xxxorg.onmicrosoft.com",
redirectUri: "http://localhost:8080/",
clientId: window.aad_clientId,
authority: "https://login.microsoftonline.com/" + window.aad_tenantId,
redirectUri: window.aad_redirectUri,
},
cache: {
cacheLocation: "sessionStorage", // This configures where your cache will be stored
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">

<head>
<title>Todo List: a SPA sample demonstrating Azure AD and MSAL JS</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">

<script th:inline="javascript">
/*<![CDATA[*/
window.aad_clientId = [[${aad_clientId}]];
window.aad_tenantId = [[${aad_tenantId}]];
window.aad_redirectUri = [[${aad_redirectUri}]];
/*]]>*/
</script>

</head>
<body ng-app="todoApp" ng-controller="homeCtrl" role="document">

Expand Down

0 comments on commit 3a732af

Please sign in to comment.