Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature] Sso Backend support #3366

Open
wants to merge 23 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions dinky-admin/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,34 @@

<properties>
<expand.scope>provided</expand.scope>
<!-- Pac4j 4.x for jdk 8 -->
<pac4j.version>4.2.0</pac4j.version>
<postgresql.version>42.5.1</postgresql.version>
<spring-webmvc-pac4j.version>4.0.1</spring-webmvc-pac4j.version>

</properties>

<dependencies>
<dependency>
<groupId>org.pac4j</groupId>
<artifactId>spring-webmvc-pac4j</artifactId>
<version>${spring-webmvc-pac4j.version}</version>
</dependency>
<dependency>
<groupId>org.pac4j</groupId>
<artifactId>pac4j-config</artifactId>
<version>${pac4j.version}</version>
</dependency>
<dependency>
<groupId>org.pac4j</groupId>
<artifactId>pac4j-oauth</artifactId>
<version>${pac4j.version}</version>
</dependency>
<dependency>
<groupId>org.pac4j</groupId>
<artifactId>pac4j-http</artifactId>
<version>${pac4j.version}</version>
</dependency>
<dependency>
<groupId>org.mitre.dsmiley.httpproxy</groupId>
<artifactId>smiley-http-proxy-servlet</artifactId>
Expand Down
39 changes: 36 additions & 3 deletions dinky-admin/src/main/java/org/dinky/configure/AppConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,17 @@

import java.util.Locale;

import org.pac4j.core.config.Config;
import org.pac4j.core.http.adapter.JEEHttpActionAdapter;
import org.pac4j.springframework.annotation.AnnotationConfig;
import org.pac4j.springframework.component.ComponentConfig;
import org.pac4j.springframework.web.SecurityInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
Expand All @@ -36,14 +45,23 @@
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;

/**
* AppConfiguration
*
* @since 2021/11/28 19:35
*/
@Configuration
@Slf4j
@Import({ComponentConfig.class, AnnotationConfig.class})
@ComponentScan(basePackages = "org.pac4j.springframework.web")
public class AppConfig implements WebMvcConfigurer {
@Autowired
private Config config;

@Value("${sso.enabled:false}")
private boolean ssoEnabled;
/**
* Cookie
*
Expand Down Expand Up @@ -85,11 +103,22 @@ public void addInterceptors(InterceptorRegistry registry) {
}
}))
.addPathPatterns("/api/**", "/openapi/**")
.excludePathPatterns("/api/login", "/api/ldap/ldapEnableStatus", "/download/**", "/druid/**");

.excludePathPatterns(
"/api/sso/ssoEnableStatus",
"/api/login",
"/api/ldap/ldapEnableStatus",
"/download/**",
"/druid/**");
if (ssoEnabled) {
log.info("Load{}", config.getClients().getClients().get(0).getName());
registry.addInterceptor(buildInterceptor(
config.getClients().getClients().get(0).getName()))
.addPathPatterns("/api/sso/login")
.addPathPatterns("/api/sso/token");
}
registry.addInterceptor(new TenantInterceptor())
.addPathPatterns("/api/**")
.excludePathPatterns("/api/login", "/api/ldap/ldapEnableStatus")
.excludePathPatterns("/api/sso/ssoEnableStatus", "/api/login", "/api/ldap/ldapEnableStatus")
.addPathPatterns("/api/alertGroup/**")
.addPathPatterns("/api/alertHistory/**")
.addPathPatterns("/api/alertInstance/**")
Expand All @@ -109,4 +138,8 @@ public void addInterceptors(InterceptorRegistry registry) {
.addPathPatterns("/api/git/**")
.addPathPatterns("/api/jar/*");
}

private SecurityInterceptor buildInterceptor(final String client) {
return new SecurityInterceptor(config, client, JEEHttpActionAdapter.INSTANCE);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/

package org.dinky.configure;

import org.dinky.configure.propertie.Pac4jConfigurationProperties;

import org.pac4j.config.client.PropertiesConfigFactory;
import org.pac4j.core.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
* The Pac4jConfigAutoConfiguration class for Spring.
*
* @author yangzehan
*
*/
@Configuration(value = "Pac4jConfigAutoConfiguration", proxyBeanMethods = false)
@EnableConfigurationProperties(org.dinky.configure.propertie.Pac4jConfigurationProperties.class)
public class Pac4jConfigAutoConfiguration {

@Autowired
private Pac4jConfigurationProperties pac4j;

@Bean
@ConditionalOnMissingBean
public Config config() {
final PropertiesConfigFactory factory =
new PropertiesConfigFactory(pac4j.getCallbackUrl(), pac4j.getProperties());
return factory.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/

package org.dinky.configure.propertie;

import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.boot.context.properties.ConfigurationProperties;

import lombok.Getter;
import lombok.Setter;

/**
* The pac4j configuration and callback URL.
*
* @author yangzehan
*
*/
@ConfigurationProperties(prefix = "pac4j", ignoreUnknownFields = false)
@Getter
@Setter
public class Pac4jConfigurationProperties {
private Map<String, String> properties = new LinkedHashMap<>();
private Map<String, String> callback = new LinkedHashMap<>();
private Map<String, String> centralLogout = new LinkedHashMap<>();
private Map<String, String> logout = new LinkedHashMap<>();
private String callbackUrl;
}
131 changes: 131 additions & 0 deletions dinky-admin/src/main/java/org/dinky/controller/SsoCpntroller.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/

package org.dinky.controller;

import org.dinky.data.dto.LoginDTO;
import org.dinky.data.dto.UserDTO;
import org.dinky.data.enums.Status;
import org.dinky.data.exception.AuthException;
import org.dinky.data.result.Result;
import org.dinky.service.UserService;

import java.util.List;

import javax.annotation.PostConstruct;

import org.pac4j.core.config.Config;
import org.pac4j.core.context.JEEContext;
import org.pac4j.core.profile.CommonProfile;
import org.pac4j.core.profile.ProfileManager;
import org.pac4j.springframework.web.LogoutController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import cn.dev33.satoken.annotation.SaIgnore;
import io.swagger.annotations.ApiOperation;
import lombok.NoArgsConstructor;

/**
* @author 杨泽翰
*/
@RestController
@NoArgsConstructor
@RequestMapping("/api/sso")
public class SsoCpntroller {
@Value("${sso.redirect}")
private String redirect;
Zzm0809 marked this conversation as resolved.
Show resolved Hide resolved

@Value("${sso.enabled:false}")
private Boolean ssoEnabled;

@Value("${pac4j.centralLogout.defaultUrl:#{null}}")
private String defaultUrl;

@Value("${pac4j.centralLogout.logoutUrlPattern:#{null}}")
private String logoutUrlPattern;

@Value("${pac4j.properties.principalNameAttribute:#{null}}")
private String principalNameAttribute;

@Autowired
private Config config;

@Autowired
private JEEContext webContext;

@Autowired
private ProfileManager profileManager;

private LogoutController logoutController;

@Autowired
private UserService userService;

@PostConstruct
protected void afterPropertiesSet() {
logoutController = new LogoutController();
logoutController.setDefaultUrl(defaultUrl);
logoutController.setLogoutUrlPattern(logoutUrlPattern);
logoutController.setLocalLogout(true);
logoutController.setCentralLogout(true);
logoutController.setConfig(config);
logoutController.setDestroySession(true);
}

@GetMapping("/token")
public Result<UserDTO> ssoToken() throws AuthException {
if (!ssoEnabled) {
return Result.failed(Status.SINGLE_LOGIN_DISABLED);
}
List<CommonProfile> all = profileManager.getAll(true);
String username = all.get(0).getAttribute(principalNameAttribute).toString();
if (username == null) {
throw new AuthException(Status.NOT_MATCHED_PRINCIPAL_NAME_ATTRIBUTE);
}
LoginDTO loginDTO = new LoginDTO();
loginDTO.setUsername(username);
loginDTO.setSsoLogin(true);
return userService.loginUser(loginDTO);
}

@GetMapping("/login")
public ModelAndView ssoLogin() {
RedirectView redirectView = new RedirectView(redirect);
return new ModelAndView(redirectView);
}

@GetMapping("/logout")
public void ssoLogout() {

logoutController.logout(webContext.getNativeRequest(), webContext.getNativeResponse());
}

@GetMapping("/ssoEnableStatus")
@SaIgnore
@ApiOperation("Get SSO enable status")
public Result<Boolean> ssoStatus() {
return Result.succeed(ssoEnabled);
}
}
16 changes: 16 additions & 0 deletions dinky-admin/src/main/java/org/dinky/data/dto/LoginDTO.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@

package org.dinky.data.dto;

import org.dinky.data.enums.UserType;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
Expand Down Expand Up @@ -48,4 +50,18 @@ public class LoginDTO {

@ApiModelProperty(value = "ldapLogin", required = true, example = "false", dataType = "Boolean")
private boolean ldapLogin;

@ApiModelProperty(value = "ssoLogin", required = true, example = "false", dataType = "Boolean")
private boolean ssoLogin;

public UserType getLoginType() {
if (isLdapLogin()) {
return UserType.LDAP;
}
if (isSsoLogin()) {
return UserType.SSO;
}

return UserType.LOCAL;
}
}
Loading