1.在项目的pom.xml文件添加相关依赖,依赖是分开存放还是统一存放根据需要。
XML
<properties>
<spring-cloud-azure-dependencies.version>5.22.0</spring-cloud-azure-dependencies.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
</dependency>
<dependency>
<groupId>com.azure.spring</groupId>
<artifactId>spring-cloud-azure-dependencies</artifactId>
<version>${spring-cloud-azure-dependencies.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
XML
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>com.azure.spring</groupId>
<artifactId>spring-cloud-azure-starter-active-directory</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
</dependencies>
2.在application.yml文件里配置相关参数
XML
spring:
application:
name: your-dashboard-name
cloud:
azure:
active-directory:
app-id-uri: api://113xxxx59a9
authorization-clients:
graph:
scopes: https://graph.microsoft.com/User.ReadBasic.All
credential:
client-id: 113xxxx59a9
client-secret: uZnxxxxxKalK
enabled: true
profile:
tenant-id: 5dxxxxxxb0
- 编写安全配置类 SecurityConfig.java, 定义哪些 URL 路径需要登录,哪些不需要.permitAll()里的路径是公开的,没有登录也可以访问。anyRequest().authenticated()表示除了上面定义的其他都需要通过认证。
java
import com.azure.spring.cloud.autoconfigure.implementation.aad.security.AadResourceServerHttpSecurityConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@Configuration(proxyBeanMethods = false)
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain apiFilterChain(HttpSecurity http) throws Exception {
http.apply(AadResourceServerHttpSecurityConfigurer.aadResourceServer());
http.authorizeHttpRequests(authorize -> authorize
.requestMatchers(
new AntPathRequestMatcher("/actuator/**"),
new AntPathRequestMatcher("/public/operation/**")
).permitAll()
.anyRequest().authenticated()
);
//关闭跨站请求伪造(CSRF)保护
http.csrf(AbstractHttpConfigurer::disable);
http.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
return http.build();
}
}
基本上就配置好了。接下来就可以编写你的前端和controller了。
我的项目中用的是VUE3作为前端。所以前端配置是这样的:
1.Vue 项目中安装 msal-browser
java
npm install @azure/msal-browser
2.在src\authConfig.ts里配置 Azure AD 的信息
java
import { LogLevel, PublicClientApplication, InteractionRequiredAuthError } from '@azure/msal-browser'
import type { SilentRequest, RedirectRequest } from '@azure/msal-browser'
export const msalConfig = {
auth: {
clientId: '5acxxxx57',
authority: 'https://login.microsoftonline.com/5d47xxxxx0b0',
redirectUri: window.location.origin, // Must be registered as a SPA redirectURI on your app registration
postLogoutRedirectUri: window.location.origin, // Must be registered as a SPA redirectURI on your app registration
navigateToLoginRequestUrl: true
},
cache: {
cacheLocation: 'localStorage'
}
}
export const msalInstance = new PublicClientApplication(msalConfig)
3.编写SSO拦截逻辑
java
export function registerGuard(router: Router) {
router.beforeEach(async (to: RouteLocationNormalized) => {
if (to.meta.requiresAuth) {
const request = {
...loginRequest,
redirectStartPage: to.fullPath
}
const shouldProceed = await isAuthenticated(
msalInstance,
InteractionType.Redirect,
request
)
return shouldProceed || '/failed'
}
return true
})
}
export async function isAuthenticated(
msalInstance: PublicClientApplication,
interactionType: InteractionType,
loginRequest: RedirectRequest | PopupRequest
): Promise<boolean> {
return instance
.handleRedirectPromise()
.then(() => {
const accounts = instance.getAllAccounts()
if (accounts.length > 0) {
return true
}
if (interactionType === InteractionType.Popup) {
....................
} else if (interactionType === InteractionType.Redirect) {
....................
}
return false
})
.catch(() => {
return false
})
}
通过添加requiresAuth: true检测登录状态,如下
java
const routes: Array<RouteRecordRaw> = [
{
path: '/user/favorites',
component: () => import('@/views/user/UserFavoritesView.vue'),
meta: { requiresAuth: true }
}
]
O了