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 4 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
25 changes: 25 additions & 0 deletions dinky-admin/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,35 @@

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

</properties>

<dependencies>

<!-- Include pac4j-config/core/oauth/oidc-->
<dependency>
<groupId>org.pac4j</groupId>
<artifactId>pac4j-springboot</artifactId>
<version>${pac4jVersion}</version>
<exclusions>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-to-slf4j</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
</exclusion>
<exclusion>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
</exclusion>
</exclusions>
</dependency>

<dependency>
<groupId>org.mitre.dsmiley.httpproxy</groupId>
<artifactId>smiley-http-proxy-servlet</artifactId>
Expand Down
18 changes: 17 additions & 1 deletion dinky-admin/src/main/java/org/dinky/configure/AppConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,14 @@
import org.dinky.data.constant.BaseConstant;
import org.dinky.interceptor.LocaleChangeInterceptor;
import org.dinky.interceptor.TenantInterceptor;
import org.dinky.sso.web.SecurityInterceptor;

import java.util.Locale;

import org.pac4j.core.config.Config;
import org.pac4j.core.http.adapter.JEEHttpActionAdapter;
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.Configuration;
import org.springframework.web.servlet.LocaleResolver;
Expand All @@ -44,6 +49,11 @@
*/
@Configuration
public class AppConfig implements WebMvcConfigurer {
@Autowired
private Config config;

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

if (ssoEnabled) {
registry.addInterceptor(buildInterceptor("GitHubClient")).addPathPatterns("/sso/*");
}
registry.addInterceptor(new TenantInterceptor())
.addPathPatterns("/api/**")
.excludePathPatterns("/api/login", "/api/ldap/ldapEnableStatus")
Expand All @@ -109,4 +121,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);
}
}
110 changes: 110 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,110 @@
/*
*
* 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 org.dinky.sso.web.LogoutController;

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.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import lombok.NoArgsConstructor;

/**
* @author 杨泽翰
*/
@RestController
@NoArgsConstructor
@ConfigurationProperties(prefix = "pac4j")
public class SsoCpntroller {
@Value("${sso.enabled:false}")
private Boolean ssoEnabled;

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

@Value("${sso.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("/sso/token")
public Result<UserDTO> token() 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("/sso/logout")
public void logout() {
logoutController.logout(webContext.getNativeRequest(), webContext.getNativeResponse());
}
}
10 changes: 10 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,12 @@ 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() {

return isLdapLogin() ? UserType.LDAP : UserType.SSO;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -177,9 +177,19 @@ public Boolean removeUser(Integer id) {
@Override
public Result<UserDTO> loginUser(LoginDTO loginDTO) {
User user = null;

try {
// Determine the login method (LDAP or local) based on the flag in loginDTO
user = loginDTO.isLdapLogin() ? ldapLogin(loginDTO) : localLogin(loginDTO);

switch (loginDTO.getLoginType()) {
case LDAP:
user = ldapLogin(loginDTO);
break;
case SSO:
user = ssoLogin(loginDTO);
break;
default:
user = localLogin(loginDTO);
}
} catch (AuthException e) {
// Handle authentication exceptions and return the corresponding error status
return Result.authorizeFailed(e.getStatus());
Expand Down Expand Up @@ -210,6 +220,36 @@ public Result<UserDTO> loginUser(LoginDTO loginDTO) {
return Result.succeed(userInfo, Status.LOGIN_SUCCESS);
}

private User ssoLogin(LoginDTO loginDTO) throws AuthException {
// Get user from local database by username
User user = getUserByUsername(loginDTO.getUsername());
if (Asserts.isNull(user)) {
// User doesn't exist,Create a user
// Get default tenant from system configuration
String defaultTeantCode =
SystemConfiguration.getInstances().getLdapDefaultTeant().getValue();
Tenant tenant = tenantService.getTenantByTenantCode(defaultTeantCode);
User userForm = new User();
userForm.setUsername(loginDTO.getUsername());
userForm.setNickname(loginDTO.getUsername());
userForm.setUserType(UserType.SSO.getCode());
userForm.setEnabled(true);
userForm.setSuperAdminFlag(false);
userForm.setIsDelete(false);
this.getBaseMapper().insert(userForm);
// Assign the user to the default tenant
List<Integer> userIds = getUserIdsByTenantId(tenant.getId());
userIds.add(userForm.getId());
tenantService.assignUserToTenant(new AssignUserToTenantDTO(tenant.getId(), userIds));
return userForm;
} else {
if (user.getUserType() != UserType.SSO.getCode()) {
throw new AuthException(Status.USER_TYPE_ERROR);
}
}
return user;
}

private void upsertToken(UserDTO userInfo) {
Integer userId = userInfo.getUser().getId();
SysToken sysToken = new SysToken();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
*
* 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.sso.annotation;

import org.dinky.sso.annotation.ui.UIAnnotationAspect;
import org.dinky.sso.annotation.ws.WSAnnotationAspect;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

/**
* The configuration for aspects.
*
* @author Jerome Leleu
* @since 3.2.0
*/
@Configuration
@EnableAspectJAutoProxy
public class AnnotationConfig {

@Bean
public WSAnnotationAspect wsAnnotationAspect() {
return new WSAnnotationAspect();
}

@Bean
public UIAnnotationAspect uiAnnotationAspect() {
return new UIAnnotationAspect();
}
}
Loading
Loading