在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了

相关推荐
q***721934 分钟前
springBoot 和springCloud 版本对应关系
spring boot·后端·spring cloud
百***81271 小时前
【SpringBoot】SpringBoot中分页插件(PageHelper)的使用
java·spring boot·后端
百***86461 小时前
SpringBoot中自定义Starter
java·spring boot·后端
q***07141 小时前
VScode 开发 Springboot 程序
java·spring boot·后端
q***46521 小时前
Spring中使用Async进行异步功能开发实战-以大文件上传为例
java·后端·spring
q***38511 小时前
SpringCloud实战【九】 SpringCloud服务间调用
java·spring boot·spring cloud
岚天start1 小时前
K8S环境中Containerd运行时占用文件定位清理
java·rpc·kubernetes
2501_916766541 小时前
解决idea依赖导入不成功的问题
java·intellij-idea
头发还在的女程序员1 小时前
基于JAVA语言的短剧小程序-抖音短剧小程序
java·开发语言·小程序