在Spring Boot中实现Azure的SSO+VUE3前端配置

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
  1. 编写安全配置类 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了

相关推荐
葫芦和十三6 小时前
图解 MongoDB 21|选举与 failover:Primary 是怎么选出来的
后端·mongodb·agent
GetcharZp7 小时前
26k Star 开源内网穿透神器 NetBird,一分钟实现全球设备互联!
后端
考虑考虑7 小时前
Mybatis实现批量插入
java·后端·mybatis
咖啡八杯8 小时前
GoF设计模式——中介者模式
java·后端·spring·设计模式
lizhongxuan10 小时前
多Agent之间的区别
后端
青石路12 小时前
记一次多JDK版本问题的排查,一坑套一坑,差点没爬上来
java
杨充12 小时前
1.面向对象设计思想
后端
IT_陈寒13 小时前
Java的Date类又坑了我一次,改用时间戳真香
前端·人工智能·后端
systemPro13 小时前
2.6亿条设备数据,历史查询从超时到50ms,我做了什么
后端
要阿尔卑斯吗13 小时前
提示词优化启示:为什么“按顺序输出“比“关键度评分“更有效
后端