This commit is contained in:
MaxKey 2022-04-13 18:47:33 +08:00
parent 3e0764c7cf
commit 786ca40b3c
95 changed files with 1146 additions and 513 deletions

View File

@ -1,5 +1,5 @@
/* /*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top] * Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.

View File

@ -1,5 +1,5 @@
/* /*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top] * Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -156,42 +156,30 @@ public class RealmAuthenticationProvider extends AbstractAuthenticationProvider
} }
public UsernamePasswordAuthenticationToken createOnlineSession(LoginCredential credential,UserInfo userInfo) { public UsernamePasswordAuthenticationToken createOnlineSession(LoginCredential credential,UserInfo userInfo) {
String currentUserSessionId = WebContext.genId(); //Online Tickit
//Online Tickit Id OnlineTicket onlineTicket = new OnlineTicket();
String onlineTickitId = WebConstants.ONLINE_TICKET_PREFIX + "-" + currentUserSessionId;
_logger.debug("set online Tickit Cookie {} on domain {}",
onlineTickitId,
this.applicationConfig.getBaseDomainName()
);
OnlineTicket onlineTicket = new OnlineTicket(onlineTickitId); userInfo.setOnlineTicket(onlineTicket.getTicketId());
//set ONLINE_TICKET cookie SigninPrincipal principal = new SigninPrincipal(userInfo);
WebContext.setCookie(WebContext.getResponse(),
this.applicationConfig.getBaseDomainName(),
WebConstants.ONLINE_TICKET_NAME,
onlineTickitId);
userInfo.setOnlineTicket(currentUserSessionId);
SigninPrincipal signinPrincipal = new SigninPrincipal(userInfo);
//set OnlineTicket //set OnlineTicket
signinPrincipal.setOnlineTicket(onlineTicket); principal.setOnlineTicket(onlineTicket);
ArrayList<GrantedAuthority> grantedAuthoritys = authenticationRealm.grantAuthority(userInfo); ArrayList<GrantedAuthority> grantedAuthoritys = authenticationRealm.grantAuthority(userInfo);
signinPrincipal.setAuthenticated(true); principal.setAuthenticated(true);
for(GrantedAuthority administratorsAuthority : grantedAdministratorsAuthoritys) { for(GrantedAuthority administratorsAuthority : grantedAdministratorsAuthoritys) {
if(grantedAuthoritys.contains(administratorsAuthority)) { if(grantedAuthoritys.contains(administratorsAuthority)) {
signinPrincipal.setRoleAdministrators(true); principal.setRoleAdministrators(true);
_logger.trace("ROLE ADMINISTRATORS Authentication ."); _logger.trace("ROLE ADMINISTRATORS Authentication .");
} }
} }
_logger.debug("Granted Authority {}" , grantedAuthoritys); _logger.debug("Granted Authority {}" , grantedAuthoritys);
signinPrincipal.setGrantedAuthorityApps(authenticationRealm.queryAuthorizedApps(grantedAuthoritys)); principal.setGrantedAuthorityApps(authenticationRealm.queryAuthorizedApps(grantedAuthoritys));
UsernamePasswordAuthenticationToken authenticationToken = UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken( new UsernamePasswordAuthenticationToken(
signinPrincipal, principal,
"PASSWORD", "PASSWORD",
grantedAuthoritys grantedAuthoritys
); );
@ -202,7 +190,7 @@ public class RealmAuthenticationProvider extends AbstractAuthenticationProvider
onlineTicket.setAuthentication(authenticationToken); onlineTicket.setAuthentication(authenticationToken);
//store onlineTicket //store onlineTicket
this.onlineTicketServices.store(onlineTickitId, onlineTicket); this.onlineTicketServices.store(onlineTicket.getTicketId(), onlineTicket);
/* /*
* put Authentication to current session context * put Authentication to current session context

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.authn.annotation; package org.maxkey.authn.annotation;
import java.lang.annotation.Documented; import java.lang.annotation.Documented;

View File

@ -1 +1,18 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.authn.annotation; package org.maxkey.authn.annotation;

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.authn.jwt; package org.maxkey.authn.jwt;
import java.util.ArrayList; import java.util.ArrayList;
@ -35,18 +52,18 @@ public class AuthJwt {
} }
public AuthJwt(String token, Authentication authentication) { public AuthJwt(String token, Authentication authentication) {
SigninPrincipal signinPrincipal = ((SigninPrincipal)authentication.getPrincipal()); SigninPrincipal principal = ((SigninPrincipal)authentication.getPrincipal());
this.token = token; this.token = token;
this.ticket = signinPrincipal.getOnlineTicket().getTicketId().substring(3); this.ticket = principal.getOnlineTicket().getTicketId();
this.id = signinPrincipal.getUserInfo().getId(); this.id = principal.getUserInfo().getId();
this.username = signinPrincipal.getUserInfo().getUsername(); this.username = principal.getUserInfo().getUsername();
this.name = this.username; this.name = this.username;
this.displayName = signinPrincipal.getUserInfo().getDisplayName(); this.displayName = principal.getUserInfo().getDisplayName();
this.email = signinPrincipal.getUserInfo().getEmail(); this.email = principal.getUserInfo().getEmail();
this.instId = signinPrincipal.getUserInfo().getInstId(); this.instId = principal.getUserInfo().getInstId();
this.instName = signinPrincipal.getUserInfo().getInstName(); this.instName = principal.getUserInfo().getInstName();
this.authorities = new ArrayList<String>(); this.authorities = new ArrayList<String>();
for(GrantedAuthority grantedAuthority :authentication.getAuthorities()) { for(GrantedAuthority grantedAuthority :authentication.getAuthorities()) {

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.authn.jwt; package org.maxkey.authn.jwt;
import java.text.ParseException; import java.text.ParseException;
@ -33,18 +50,18 @@ public class AuthJwtService {
public String generateToken(Authentication authentication) { public String generateToken(Authentication authentication) {
String token = ""; String token = "";
SigninPrincipal signinPrincipal = ((SigninPrincipal)authentication.getPrincipal()); SigninPrincipal principal = ((SigninPrincipal)authentication.getPrincipal());
UserInfo userInfo = signinPrincipal.getUserInfo(); UserInfo userInfo = principal.getUserInfo();
DateTime currentDateTime = DateTime.now(); DateTime currentDateTime = DateTime.now();
Date expirationTime = currentDateTime.plusSeconds(authJwkConfig.getExpires()).toDate(); Date expirationTime = currentDateTime.plusSeconds(authJwkConfig.getExpires()).toDate();
_logger.debug("expiration Time : {}" , expirationTime); _logger.debug("expiration Time : {}" , expirationTime);
String subject = signinPrincipal.getUsername(); String subject = principal.getUsername();
_logger.trace("jwt subject : {}" , subject); _logger.trace("jwt subject : {}" , subject);
JWTClaimsSet jwtClaims =new JWTClaimsSet.Builder() JWTClaimsSet jwtClaims =new JWTClaimsSet.Builder()
.issuer(authJwkConfig.getIssuer()) .issuer(authJwkConfig.getIssuer())
.subject(subject) .subject(subject)
.jwtID(signinPrincipal.getOnlineTicket().getTicketId()) .jwtID(principal.getOnlineTicket().getFormattedTicketId())
.issueTime(currentDateTime.toDate()) .issueTime(currentDateTime.toDate())
.expirationTime(expirationTime) .expirationTime(expirationTime)
.claim("locale", userInfo.getLocale()) .claim("locale", userInfo.getLocale())

View File

@ -1 +1,18 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.authn.jwt; package org.maxkey.authn.jwt;

View File

@ -0,0 +1,124 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.authn.online;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.time.LocalTime;
import java.util.Date;
import java.util.List;
import org.maxkey.entity.HistoryLogin;
import org.maxkey.entity.UserInfo;
import org.maxkey.util.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
public class AbstractOnlineTicketService implements OnlineTicketService{
private static Logger _logger = LoggerFactory.getLogger(AbstractOnlineTicketService.class);
protected JdbcTemplate jdbcTemplate;
private static final String DEFAULT_DEFAULT_SELECT_STATEMENT =
"select id,sessionid,userId,username,displayname,logintime from mxk_history_login where sessionstatus = 1";
private static final String LOGOUT_USERINFO_UPDATE_STATEMENT =
"update mxk_userinfo set lastlogofftime = ? , online = " + UserInfo.ONLINE.OFFLINE + " where id = ?";
private static final String HISTORY_LOGOUT_UPDATE_STATEMENT =
"update mxk_history_login set logouttime = ? ,sessionstatus = 7 where sessionid = ?";
public List<HistoryLogin> query() {
List<HistoryLogin> listOnlineTicket = jdbcTemplate.query(
DEFAULT_DEFAULT_SELECT_STATEMENT,
new OnlineTicketRowMapper());
return listOnlineTicket;
}
public void profileLastLogoffTime(String userId,String lastLogoffTime) {
_logger.trace("userId {} , lastlogofftime {}" ,userId, lastLogoffTime);
jdbcTemplate.update( LOGOUT_USERINFO_UPDATE_STATEMENT,
new Object[] { lastLogoffTime, userId },
new int[] { Types.TIMESTAMP, Types.VARCHAR });
}
public void sessionLogoff(String sessionId,String lastLogoffTime) {
_logger.trace("sessionId {} , lastlogofftime {}" ,sessionId, lastLogoffTime);
jdbcTemplate.update(HISTORY_LOGOUT_UPDATE_STATEMENT,
new Object[] { lastLogoffTime, sessionId },
new int[] { Types.VARCHAR, Types.VARCHAR });
}
@Override
public void terminate(String onlineTicket,String userId,String username) {
String lastLogoffTime = DateUtils.formatDateTime(new Date());
_logger.trace("{} user {} terminate Ticket {} ." ,lastLogoffTime,username, onlineTicket);
this.profileLastLogoffTime(userId, lastLogoffTime);
this.sessionLogoff(userId, lastLogoffTime);
remove(onlineTicket);
}
private final class OnlineTicketRowMapper implements RowMapper<HistoryLogin> {
@Override
public HistoryLogin mapRow(ResultSet rs, int rowNum)
throws SQLException {
HistoryLogin history=new HistoryLogin();
history.setId(rs.getString(1));
history.setSessionId(rs.getString(2));
history.setUserId(rs.getString(3));
history.setUsername(rs.getString(4));
history.setDisplayName(rs.getString(5));
history.setLoginTime(rs.getString(6));
return history;
}
}
@Override
public void store(String ticketId, OnlineTicket ticket) {
}
@Override
public OnlineTicket remove(String ticket) {
return null;
}
@Override
public OnlineTicket get(String ticketId) {
return null;
}
@Override
public void refresh(String ticketId, LocalTime refreshTime) {
}
@Override
public void refresh(String ticketId) {
}
@Override
public void setValiditySeconds(int validitySeconds) {
}
}

View File

@ -23,12 +23,13 @@ import java.util.concurrent.TimeUnit;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine; import com.github.benmanes.caffeine.cache.Caffeine;
public class InMemoryOnlineTicketService implements OnlineTicketService{ public class InMemoryOnlineTicketService extends AbstractOnlineTicketService{
private static final Logger _logger = LoggerFactory.getLogger(InMemoryOnlineTicketService.class); private static final Logger _logger = LoggerFactory.getLogger(InMemoryOnlineTicketService.class);
protected static Cache<String, OnlineTicket> onlineTicketStore = protected static Cache<String, OnlineTicket> onlineTicketStore =
@ -37,8 +38,9 @@ public class InMemoryOnlineTicketService implements OnlineTicketService{
.maximumSize(200000) .maximumSize(200000)
.build(); .build();
public InMemoryOnlineTicketService() { public InMemoryOnlineTicketService(JdbcTemplate jdbcTemplate) {
super(); super();
this.jdbcTemplate = jdbcTemplate;
} }
@Override @Override

View File

@ -22,18 +22,16 @@ import java.time.LocalTime;
import java.util.HashMap; import java.util.HashMap;
import org.maxkey.entity.apps.Apps; import org.maxkey.entity.apps.Apps;
import org.maxkey.web.WebContext;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
public class OnlineTicket implements Serializable{ public class OnlineTicket implements Serializable{
private static final long serialVersionUID = 9008067569150338296L;
/** public static final String ONLINE_TICKET_PREFIX = "OT";
*
*/
public static final int MAX_EXPIRY_DURATION = 60 * 10; //default 10 minutes. public static final int MAX_EXPIRY_DURATION = 60 * 10; //default 10 minutes.
private static final long serialVersionUID = 9008067569150338296L;
public String ticketId; public String ticketId;
public LocalTime ticketTime; public LocalTime ticketTime;
@ -42,6 +40,11 @@ public class OnlineTicket implements Serializable{
private HashMap<String , Apps> authorizedApps = new HashMap<String , Apps>(); private HashMap<String , Apps> authorizedApps = new HashMap<String , Apps>();
public OnlineTicket() {
super();
this.ticketId = WebContext.genId();;
this.ticketTime = LocalTime.now();
}
public OnlineTicket(String ticketId) { public OnlineTicket(String ticketId) {
super(); super();
@ -56,19 +59,18 @@ public class OnlineTicket implements Serializable{
this.ticketTime = LocalTime.now(); this.ticketTime = LocalTime.now();
} }
public String getTicketId() { public String getTicketId() {
return ticketId; return ticketId;
} }
public String getFormattedTicketId() {
return ticketId;
}
public void setTicketId(String ticketId) { public void setTicketId(String ticketId) {
this.ticketId = ticketId; this.ticketId = ticketId;
} }
public LocalTime getTicketTime() { public LocalTime getTicketTime() {
return ticketTime; return ticketTime;
} }
@ -81,20 +83,14 @@ public class OnlineTicket implements Serializable{
return authentication; return authentication;
} }
public void setAuthentication(Authentication authentication) { public void setAuthentication(Authentication authentication) {
this.authentication = authentication; this.authentication = authentication;
} }
public HashMap<String, Apps> getAuthorizedApps() { public HashMap<String, Apps> getAuthorizedApps() {
return authorizedApps; return authorizedApps;
} }
public void setAuthorizedApps(HashMap<String, Apps> authorizedApps) { public void setAuthorizedApps(HashMap<String, Apps> authorizedApps) {
this.authorizedApps = authorizedApps; this.authorizedApps = authorizedApps;
} }
@ -103,8 +99,6 @@ public class OnlineTicket implements Serializable{
this.authorizedApps.put(authorizedApp.getId(), authorizedApp); this.authorizedApps.put(authorizedApp.getId(), authorizedApp);
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();

View File

@ -1,5 +1,5 @@
/* /*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top] * Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -32,4 +32,6 @@ public interface OnlineTicketService {
public void refresh(String ticketId); public void refresh(String ticketId);
public void setValiditySeconds(int validitySeconds); public void setValiditySeconds(int validitySeconds);
public void terminate(String onlineTicket,String userId,String username);
} }

View File

@ -34,12 +34,12 @@ public class OnlineTicketServiceFactory {
OnlineTicketService onlineTicketServices = null; OnlineTicketService onlineTicketServices = null;
if (persistence == ConstsPersistence.INMEMORY) { if (persistence == ConstsPersistence.INMEMORY) {
onlineTicketServices = new InMemoryOnlineTicketService(); onlineTicketServices = new InMemoryOnlineTicketService(jdbcTemplate);
_logger.debug("InMemoryOnlineTicketServices"); _logger.debug("InMemoryOnlineTicketServices");
} else if (persistence == ConstsPersistence.JDBC) { } else if (persistence == ConstsPersistence.JDBC) {
_logger.debug("OnlineTicketServices not support "); _logger.debug("OnlineTicketServices not support ");
} else if (persistence == ConstsPersistence.REDIS) { } else if (persistence == ConstsPersistence.REDIS) {
onlineTicketServices = new RedisOnlineTicketService(redisConnFactory); onlineTicketServices = new RedisOnlineTicketService(redisConnFactory,jdbcTemplate);
_logger.debug("RedisOnlineTicketServices"); _logger.debug("RedisOnlineTicketServices");
} }

View File

@ -24,9 +24,10 @@ import org.maxkey.persistence.redis.RedisConnection;
import org.maxkey.persistence.redis.RedisConnectionFactory; import org.maxkey.persistence.redis.RedisConnectionFactory;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
public class RedisOnlineTicketService implements OnlineTicketService { public class RedisOnlineTicketService extends AbstractOnlineTicketService {
private static final Logger _logger = LoggerFactory.getLogger(RedisOnlineTicketService.class); private static final Logger _logger = LoggerFactory.getLogger(RedisOnlineTicketService.class);
protected int serviceTicketValiditySeconds = 60 * 30; //default 30 minutes. protected int serviceTicketValiditySeconds = 60 * 30; //default 30 minutes.
@ -37,9 +38,12 @@ public class RedisOnlineTicketService implements OnlineTicketService {
/** /**
* @param connectionFactory * @param connectionFactory
*/ */
public RedisOnlineTicketService(RedisConnectionFactory connectionFactory) { public RedisOnlineTicketService(
RedisConnectionFactory connectionFactory,
JdbcTemplate jdbcTemplate) {
super(); super();
this.connectionFactory = connectionFactory; this.connectionFactory = connectionFactory;
this.jdbcTemplate = jdbcTemplate;
} }
/** /**

View File

@ -20,7 +20,6 @@ package org.maxkey.authn.realm;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.maxkey.authn.SigninPrincipal; import org.maxkey.authn.SigninPrincipal;
import org.maxkey.authn.realm.ldap.LdapAuthenticationRealmService; import org.maxkey.authn.realm.ldap.LdapAuthenticationRealmService;
@ -158,32 +157,6 @@ public abstract class AbstractAuthenticationRealm {
return true; return true;
} }
/**
* logout user and remove RemeberMe token
* @param response
* @return
*/
public boolean logout(HttpServletResponse response) {
Authentication authentication = (Authentication ) WebContext.getAttribute(WebConstants.AUTHENTICATION);
if(authentication != null && authentication.getPrincipal() instanceof SigninPrincipal) {
SigninPrincipal signinPrincipal = ((SigninPrincipal) authentication.getPrincipal());
UserInfo userInfo = signinPrincipal.getUserInfo();
userInfo.setLastLogoffTime(DateUtils.formatDateTime(new Date()));
loginHistoryRepository.logoff(userInfo.getLastLogoffTime(), signinPrincipal.getOnlineTicket().getTicketId());
loginRepository.updateLastLogoff(userInfo);
_logger.debug("Session " + signinPrincipal.getOnlineTicket().getTicketId() + ", user "
+ userInfo.getUsername() + " Logout, datetime " + userInfo.getLastLogoffTime() + " .");
}
return true;
}
public Browser resolveBrowser() { public Browser resolveBrowser() {
Browser browser =new Browser(); Browser browser =new Browser();
String userAgent = WebContext.getRequest().getHeader("User-Agent"); String userAgent = WebContext.getRequest().getHeader("User-Agent");

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.authn.web; package org.maxkey.authn.web;
import java.text.ParseException; import java.text.ParseException;
@ -17,7 +34,7 @@ import org.springframework.security.core.Authentication;
public class AuthorizationUtils { public class AuthorizationUtils {
static final String Authorization = "Authorization"; static final String Authorization_Cookie = "AuthJWT";
public static void authenticateWithCookie( public static void authenticateWithCookie(
HttpServletRequest request, HttpServletRequest request,
@ -25,10 +42,10 @@ public class AuthorizationUtils {
OnlineTicketService onlineTicketService OnlineTicketService onlineTicketService
) throws ParseException{ ) throws ParseException{
if(getAuthentication() == null) { if(getAuthentication() == null) {
Cookie authCookie = WebContext.getCookie(request, Authorization); Cookie authCookie = WebContext.getCookie(request, Authorization_Cookie);
if(authCookie != null ) { if(authCookie != null ) {
String authorization = authCookie.getValue(); String authorization = authCookie.getValue();
doAuthenticate(authorization,authJwtService,onlineTicketService); doJwtAuthenticate(authorization,authJwtService,onlineTicketService);
} }
} }
} }
@ -41,12 +58,12 @@ public class AuthorizationUtils {
if(getAuthentication() == null) { if(getAuthentication() == null) {
String authorization = AuthorizationHeaderUtils.resolveBearer(request); String authorization = AuthorizationHeaderUtils.resolveBearer(request);
if(authorization != null ) { if(authorization != null ) {
doAuthenticate(authorization,authJwtService,onlineTicketService); doJwtAuthenticate(authorization,authJwtService,onlineTicketService);
} }
} }
} }
public static void doAuthenticate( public static void doJwtAuthenticate(
String authorization, String authorization,
AuthJwtService authJwtService, AuthJwtService authJwtService,
OnlineTicketService onlineTicketService) throws ParseException { OnlineTicketService onlineTicketService) throws ParseException {
@ -59,13 +76,17 @@ public class AuthorizationUtils {
} }
} }
public static void setAuthentication(Authentication authentication) { public static void setAuthentication(Authentication authentication) {
WebContext.setAttribute(WebConstants.AUTHENTICATION, authentication); WebContext.setAttribute(WebConstants.AUTHENTICATION, authentication);
} }
public static Authentication getAuthentication() { public static Authentication getAuthentication() {
Authentication authentication = (Authentication) WebContext.getAttribute(WebConstants.AUTHENTICATION); Authentication authentication = (Authentication) getAuthentication(WebContext.getRequest());
return authentication;
}
public static Authentication getAuthentication(HttpServletRequest request) {
Authentication authentication = (Authentication) request.getSession().getAttribute(WebConstants.AUTHENTICATION);
return authentication; return authentication;
} }
@ -74,22 +95,29 @@ public class AuthorizationUtils {
} }
public static boolean isNotAuthenticated() { public static boolean isNotAuthenticated() {
return getAuthentication() == null; return ! isAuthenticated();
} }
public static SigninPrincipal getPrincipal() { public static SigninPrincipal getPrincipal() {
Authentication authentication = getAuthentication(); Authentication authentication = getAuthentication();
return getPrincipal(authentication);
}
public static SigninPrincipal getPrincipal(Authentication authentication) {
return authentication == null ? null : (SigninPrincipal) authentication.getPrincipal(); return authentication == null ? null : (SigninPrincipal) authentication.getPrincipal();
} }
public static UserInfo getUserInfo() { public static UserInfo getUserInfo(Authentication authentication) {
Authentication authentication = getAuthentication();
UserInfo userInfo = null; UserInfo userInfo = null;
if(isAuthenticated() && (authentication.getPrincipal() instanceof SigninPrincipal)) { SigninPrincipal principal = getPrincipal(authentication);
SigninPrincipal signinPrincipal = ((SigninPrincipal) authentication.getPrincipal()); if(principal != null ) {
userInfo = signinPrincipal.getUserInfo(); userInfo = principal.getUserInfo();
} }
return userInfo; return userInfo;
} }
public static UserInfo getUserInfo() {
return getUserInfo(getAuthentication());
}
} }

View File

@ -1,6 +1,22 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.authn.web; package org.maxkey.authn.web;
import org.maxkey.authn.SigninPrincipal;
import org.maxkey.authn.annotation.CurrentUser; import org.maxkey.authn.annotation.CurrentUser;
import org.maxkey.entity.UserInfo; import org.maxkey.entity.UserInfo;
import org.maxkey.web.WebConstants; import org.maxkey.web.WebConstants;
@ -14,23 +30,23 @@ import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.support.MissingServletRequestPartException; import org.springframework.web.multipart.support.MissingServletRequestPartException;
public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver { public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
Authentication authentication =
(Authentication ) webRequest.getAttribute(
WebConstants.AUTHENTICATION, RequestAttributes.SCOPE_SESSION);
UserInfo userInfo = AuthorizationUtils.getUserInfo(authentication);
if (userInfo != null) {
return userInfo;
}
throw new MissingServletRequestPartException("currentUser");
}
@Override @Override
public boolean supportsParameter(MethodParameter parameter) { public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterType().isAssignableFrom(UserInfo.class) return parameter.getParameterType().isAssignableFrom(UserInfo.class)
&& parameter.hasParameterAnnotation(CurrentUser.class); && parameter.hasParameterAnnotation(CurrentUser.class);
} }
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
UserInfo userInfo = null;
Authentication authentication = (Authentication ) webRequest.getAttribute(WebConstants.AUTHENTICATION, RequestAttributes.SCOPE_SESSION);
if((authentication != null) && (authentication.getPrincipal() instanceof SigninPrincipal)) {
SigninPrincipal signinPrincipal = ((SigninPrincipal) authentication.getPrincipal());
userInfo = signinPrincipal.getUserInfo();
if (userInfo != null) {
return userInfo;
}
}
throw new MissingServletRequestPartException("currentUser");
}
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright [2021] [MaxKey of copyright http://www.maxkey.top] * Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -22,48 +22,22 @@ import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener; import javax.servlet.http.HttpSessionListener;
import org.apache.mybatis.jpa.util.WebContext;
import org.maxkey.authn.SigninPrincipal; import org.maxkey.authn.SigninPrincipal;
import org.maxkey.entity.UserInfo;
import org.maxkey.persistence.repository.LoginHistoryRepository;
import org.maxkey.persistence.repository.LoginRepository;
import org.maxkey.util.DateUtils; import org.maxkey.util.DateUtils;
import org.maxkey.web.WebConstants; import org.maxkey.web.WebConstants;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
@WebListener @WebListener
public class SessionListenerAdapter implements HttpSessionListener { public class SessionListenerAdapter implements HttpSessionListener {
private static final Logger _logger = LoggerFactory.getLogger(SessionListenerAdapter.class); private static final Logger _logger = LoggerFactory.getLogger(SessionListenerAdapter.class);
LoginRepository loginRepository;
LoginHistoryRepository loginHistoryRepository;
public SessionListenerAdapter() { public SessionListenerAdapter() {
super(); super();
_logger.debug("SessionListenerAdapter inited . "); _logger.debug("SessionListenerAdapter inited . ");
} }
public SessionListenerAdapter(LoginRepository loginRepository, LoginHistoryRepository loginHistoryRepository) {
super();
this.loginRepository = loginRepository;
this.loginHistoryRepository = loginHistoryRepository;
_logger.debug("SessionListenerAdapter inited . ");
}
public void init() {
if(loginRepository == null ) {
loginRepository = (LoginRepository)WebContext.getBean("loginRepository");
loginHistoryRepository = (LoginHistoryRepository)WebContext.getBean("loginHistoryRepository");
_logger.debug("SessionListenerAdapter function inited . ");
}
_logger.info("SecurityContextHolder StrategyName " + SessionSecurityContextHolderStrategy.class.getCanonicalName());
SecurityContextHolder.setStrategyName(SessionSecurityContextHolderStrategy.class.getCanonicalName());
}
/** /**
* session Created * session Created
*/ */
@ -79,31 +53,16 @@ public class SessionListenerAdapter implements HttpSessionListener {
public void sessionDestroyed(HttpSessionEvent sessionEvent) { public void sessionDestroyed(HttpSessionEvent sessionEvent) {
HttpSession session = sessionEvent.getSession(); HttpSession session = sessionEvent.getSession();
Authentication authentication = (Authentication ) session.getAttribute(WebConstants.AUTHENTICATION); Authentication authentication = (Authentication ) session.getAttribute(WebConstants.AUTHENTICATION);
if(authentication != null && authentication.getPrincipal() instanceof SigninPrincipal) { SigninPrincipal principal = AuthorizationUtils.getPrincipal(authentication);
SigninPrincipal signinPrincipal = ((SigninPrincipal) authentication.getPrincipal()); if(principal != null ) {
_logger.trace("session Id : " + session.getId()); _logger.trace("{} HttpSession Id {} for userId {} , username {} @Ticket {} Destroyed" ,
init(); DateUtils.formatDateTime(new Date()),
UserInfo userInfo = signinPrincipal.getUserInfo(); session.getId(),
userInfo.setLastLogoffTime(DateUtils.formatDateTime(new Date())); principal.getUserInfo().getId(),
loginRepository.updateLastLogoff(userInfo); principal.getUserInfo().getUsername(),
loginHistoryRepository.logoff(userInfo.getLastLogoffTime(), userInfo.getOnlineTicket()); principal.getOnlineTicket().getTicketId());
_logger.debug(
"session {} Destroyed as {} userId : {} , username : {}" ,
userInfo.getOnlineTicket(),
userInfo.getLastLogoffTime(),
userInfo.getId(),
userInfo.getUsername());
} }
} }
public void setLoginRepository(LoginRepository loginRepository) {
this.loginRepository = loginRepository;
}
public void setLoginHistoryRepository(LoginHistoryRepository loginHistoryRepository) {
this.loginHistoryRepository = loginHistoryRepository;
}
} }

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.authn.web; package org.maxkey.authn.web;
import java.io.IOException; import java.io.IOException;

View File

@ -1,5 +1,5 @@
/* /*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top] * Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -33,8 +33,6 @@ import org.springframework.stereotype.Component;
import org.springframework.web.servlet.AsyncHandlerInterceptor; import org.springframework.web.servlet.AsyncHandlerInterceptor;
/** /**
* 权限Interceptor处理 * 权限Interceptor处理
* 权限处理需在servlet.xml中配置
* mvc:interceptors permission
* @author Crystal.Sea * @author Crystal.Sea
* *
*/ */
@ -51,6 +49,8 @@ public class PermissionInterceptor implements AsyncHandlerInterceptor {
@Autowired @Autowired
AuthJwtService authJwtService ; AuthJwtService authJwtService ;
boolean mgmt = false;
/* /*
* 请求前处理 * 请求前处理
* (non-Javadoc) * (non-Javadoc)
@ -60,25 +60,29 @@ public class PermissionInterceptor implements AsyncHandlerInterceptor {
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception { public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
_logger.trace("PermissionAdapter preHandle"); _logger.trace("PermissionAdapter preHandle");
AuthorizationUtils.authenticate(request, authJwtService, onlineTicketService); AuthorizationUtils.authenticate(request, authJwtService, onlineTicketService);
//判断用户是否登录 SigninPrincipal principal = AuthorizationUtils.getPrincipal();
if(AuthorizationUtils.getAuthentication()==null //判断用户是否登录,判断用户是否登录用户
||AuthorizationUtils.getAuthentication().getAuthorities()==null){//判断用户和角色判断用户是否登录用户 if(principal == null){
_logger.trace("No Authentication ... forward to /auth/entrypoint"); _logger.trace("No Authentication ... forward to /auth/entrypoint");
RequestDispatcher dispatcher = request.getRequestDispatcher("/auth/entrypoint"); RequestDispatcher dispatcher = request.getRequestDispatcher("/auth/entrypoint");
dispatcher.forward(request, response); dispatcher.forward(request, response);
return false; return false;
} }
//非管理员用户直接注销 //管理端必须使用管理员登录,非管理员用户直接注销
if (!((SigninPrincipal) AuthorizationUtils.getAuthentication().getPrincipal()).isRoleAdministrators()) { if (this.mgmt && !principal.isRoleAdministrators()) {
_logger.debug("Not ADMINISTRATORS Authentication ."); _logger.debug("Not ADMINISTRATORS Authentication .");
RequestDispatcher dispatcher = request.getRequestDispatcher("/logout"); RequestDispatcher dispatcher = request.getRequestDispatcher("/auth/entrypoint");
dispatcher.forward(request, response); dispatcher.forward(request, response);
return false; return false;
} }
boolean hasAccess=true; return true;
}
return hasAccess; public void setMgmt(boolean mgmt) {
this.mgmt = mgmt;
_logger.debug("Permission for ADMINISTRATORS {}", this.mgmt);
} }
} }

View File

@ -1 +1,18 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.authn.web.interceptor; package org.maxkey.authn.web.interceptor;

View File

@ -1 +1,18 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.authn.web; package org.maxkey.authn.web;

View File

@ -137,13 +137,8 @@ public class AuthenticationAutoConfiguration implements InitializingBean {
} }
@Bean(name = "sessionListenerAdapter") @Bean(name = "sessionListenerAdapter")
public SessionListenerAdapter sessionListenerAdapter( public SessionListenerAdapter sessionListenerAdapter() {
LoginRepository loginRepository, return new SessionListenerAdapter();
LoginHistoryRepository loginHistoryRepository
) {
SessionListenerAdapter sessionListenerAdapter =
new SessionListenerAdapter(loginRepository,loginHistoryRepository);
return sessionListenerAdapter;
} }
@Override @Override

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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 me.zhyd.oauth.config; package me.zhyd.oauth.config;
import me.zhyd.oauth.request.AuthDefaultRequest; import me.zhyd.oauth.request.AuthDefaultRequest;

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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 me.zhyd.oauth.request; package me.zhyd.oauth.request;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.crypto.jwt; package org.maxkey.crypto.jwt;
import java.text.ParseException; import java.text.ParseException;

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.entity; package org.maxkey.entity;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.crypto.signature; package org.maxkey.crypto.signature;
import org.maxkey.crypto.jwt.HMAC512Service; import org.maxkey.crypto.jwt.HMAC512Service;

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.crypto.signature; package org.maxkey.crypto.signature;
import java.text.ParseException; import java.text.ParseException;

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.configuration; package org.maxkey.configuration;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.entity; package org.maxkey.entity;
import javax.persistence.Column; import javax.persistence.Column;

View File

@ -18,7 +18,6 @@
package org.maxkey.persistence.repository; package org.maxkey.persistence.repository;
import java.sql.Types; import java.sql.Types;
import org.maxkey.entity.HistoryLogin; import org.maxkey.entity.HistoryLogin;
import org.maxkey.web.WebContext; import org.maxkey.web.WebContext;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -30,8 +29,6 @@ public class LoginHistoryRepository {
private static final String HISTORY_LOGIN_INSERT_STATEMENT = "insert into mxk_history_login (id , sessionid , userid , username , displayname , logintype , message , code , provider , sourceip , ipregion , iplocation, browser , platform , application , loginurl , sessionstatus ,instid)values( ? , ? , ? , ? , ? , ? , ? , ? , ?, ? , ? , ?, ? , ? , ?, ? , ? , ?)"; private static final String HISTORY_LOGIN_INSERT_STATEMENT = "insert into mxk_history_login (id , sessionid , userid , username , displayname , logintype , message , code , provider , sourceip , ipregion , iplocation, browser , platform , application , loginurl , sessionstatus ,instid)values( ? , ? , ? , ? , ? , ? , ? , ? , ?, ? , ? , ?, ? , ? , ?, ? , ? , ?)";
private static final String HISTORY_LOGOUT_UPDATE_STATEMENT = "update mxk_history_login set logouttime = ? ,sessionstatus = 7 where sessionid = ?";
protected JdbcTemplate jdbcTemplate; protected JdbcTemplate jdbcTemplate;
public LoginHistoryRepository(JdbcTemplate jdbcTemplate) { public LoginHistoryRepository(JdbcTemplate jdbcTemplate) {
@ -58,21 +55,4 @@ public class LoginHistoryRepository {
}); });
} }
public void logoff(String lastLogoffTime,String sessionId) {
_logger.debug(" sessionId {} , lastlogofftime {}" ,sessionId, lastLogoffTime);
jdbcTemplate.update(HISTORY_LOGOUT_UPDATE_STATEMENT,
new Object[] { lastLogoffTime, sessionId },
new int[] { Types.VARCHAR, Types.VARCHAR });
}
public void logoff(HistoryLogin historyLogin) {
_logger.debug(" sessionId {} , LogoutTime {}" ,
historyLogin.getSessionId(), historyLogin.getLogoutTime()
);
jdbcTemplate.update(HISTORY_LOGOUT_UPDATE_STATEMENT,
new Object[] { historyLogin.getLogoutTime(), historyLogin.getSessionId() },
new int[] { Types.VARCHAR, Types.VARCHAR });
}
} }

View File

@ -49,8 +49,7 @@ public class LoginRepository {
private static final String LOGIN_USERINFO_UPDATE_STATEMENT = "update mxk_userinfo set lastlogintime = ? , lastloginip = ? , logincount = ?, online = " private static final String LOGIN_USERINFO_UPDATE_STATEMENT = "update mxk_userinfo set lastlogintime = ? , lastloginip = ? , logincount = ?, online = "
+ UserInfo.ONLINE.ONLINE + " where id = ?"; + UserInfo.ONLINE.ONLINE + " where id = ?";
private static final String LOGOUT_USERINFO_UPDATE_STATEMENT = "update mxk_userinfo set lastlogofftime = ? , online = "
+ UserInfo.ONLINE.OFFLINE + " where id = ?";
private static final String GROUPS_SELECT_STATEMENT = "select distinct g.id,g.name from mxk_userinfo u,mxk_groups g,mxk_group_member gm where u.id = ? and u.id=gm.memberid and gm.groupid=g.id "; private static final String GROUPS_SELECT_STATEMENT = "select distinct g.id,g.name from mxk_userinfo u,mxk_groups g,mxk_group_member gm where u.id = ? and u.id=gm.memberid and gm.groupid=g.id ";
@ -260,12 +259,6 @@ public class LoginRepository {
new int[] { Types.TIMESTAMP, Types.VARCHAR, Types.INTEGER, Types.VARCHAR }); new int[] { Types.TIMESTAMP, Types.VARCHAR, Types.INTEGER, Types.VARCHAR });
} }
public void updateLastLogoff(UserInfo userInfo) {
jdbcTemplate.update( LOGOUT_USERINFO_UPDATE_STATEMENT,
new Object[] { userInfo.getLastLogoffTime(), userInfo.getId() },
new int[] { Types.TIMESTAMP, Types.VARCHAR });
}
public class UserInfoRowMapper implements RowMapper<UserInfo> { public class UserInfoRowMapper implements RowMapper<UserInfo> {
@Override @Override
public UserInfo mapRow(ResultSet rs, int rowNum) throws SQLException { public UserInfo mapRow(ResultSet rs, int rowNum) throws SQLException {

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.web; package org.maxkey.web;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;

View File

@ -1,5 +1,5 @@
/* /*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top] * Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.web.ipregion; package org.maxkey.web.ipregion;
public abstract class AbstractIpRegion implements IpRegion{ public abstract class AbstractIpRegion implements IpRegion{

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.web.ipregion; package org.maxkey.web.ipregion;
public interface IpRegion { public interface IpRegion {

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.web.ipregion; package org.maxkey.web.ipregion;
import java.util.ArrayList; import java.util.ArrayList;

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.web.ipregion; package org.maxkey.web.ipregion;
import java.io.IOException; import java.io.IOException;

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.web.ipregion; package org.maxkey.web.ipregion;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.web.ipregion; package org.maxkey.web.ipregion;
import java.io.IOException; import java.io.IOException;

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.web.ipregion; package org.maxkey.web.ipregion;
public class IpRegionIp360Response { public class IpRegionIp360Response {

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.web.ipregion; package org.maxkey.web.ipregion;
import java.io.IOException; import java.io.IOException;

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.web.ipregion; package org.maxkey.web.ipregion;
import java.io.IOException; import java.io.IOException;

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.web.ipregion; package org.maxkey.web.ipregion;
public class IpRegionLocal extends AbstractIpRegion implements IpRegion{ public class IpRegionLocal extends AbstractIpRegion implements IpRegion{

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.web.ipregion; package org.maxkey.web.ipregion;
import org.maxkey.util.JsonUtils; import org.maxkey.util.JsonUtils;

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.web.ipregion; package org.maxkey.web.ipregion;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

View File

@ -1 +1,18 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.web.ipregion; package org.maxkey.web.ipregion;

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.web.ipregion; package org.maxkey.web.ipregion;
import org.junit.Test; import org.junit.Test;

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.web.ipregion; package org.maxkey.web.ipregion;
import org.junit.Test; import org.junit.Test;

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.web.ipregion; package org.maxkey.web.ipregion;
import org.junit.Test; import org.junit.Test;

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.web.ipregion; package org.maxkey.web.ipregion;
import org.junit.Test; import org.junit.Test;

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.web.ipregion; package org.maxkey.web.ipregion;
import org.junit.Test; import org.junit.Test;

View File

@ -1,3 +1,20 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.web.ipregion; package org.maxkey.web.ipregion;
import org.junit.Test; import org.junit.Test;

View File

@ -32,8 +32,8 @@ import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@Component @Component
public class MqPersistService { public class MessageQueueService {
private static final Logger _logger = LoggerFactory.getLogger(MqPersistService.class); private static final Logger _logger = LoggerFactory.getLogger(MessageQueueService.class);
@Autowired @Autowired
protected ApplicationConfig applicationConfig; protected ApplicationConfig applicationConfig;

View File

@ -29,7 +29,7 @@ import org.maxkey.entity.UserInfo;
import org.maxkey.persistence.mapper.AccountsMapper; import org.maxkey.persistence.mapper.AccountsMapper;
import org.maxkey.persistence.mq.MqIdentityAction; import org.maxkey.persistence.mq.MqIdentityAction;
import org.maxkey.persistence.mq.MqIdentityTopic; import org.maxkey.persistence.mq.MqIdentityTopic;
import org.maxkey.persistence.mq.MqPersistService; import org.maxkey.persistence.mq.MessageQueueService;
import org.maxkey.util.StringUtils; import org.maxkey.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
@ -45,7 +45,7 @@ import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombi
public class AccountsService extends JpaBaseService<Accounts>{ public class AccountsService extends JpaBaseService<Accounts>{
@Autowired @Autowired
MqPersistService mqPersistService; MessageQueueService mqPersistService;
@Autowired @Autowired
UserInfoService userInfoService; UserInfoService userInfoService;

View File

@ -1,5 +1,5 @@
/* /*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top] * Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.

View File

@ -26,7 +26,7 @@ import org.maxkey.entity.Organizations;
import org.maxkey.persistence.mapper.OrganizationsMapper; import org.maxkey.persistence.mapper.OrganizationsMapper;
import org.maxkey.persistence.mq.MqIdentityAction; import org.maxkey.persistence.mq.MqIdentityAction;
import org.maxkey.persistence.mq.MqIdentityTopic; import org.maxkey.persistence.mq.MqIdentityTopic;
import org.maxkey.persistence.mq.MqPersistService; import org.maxkey.persistence.mq.MessageQueueService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
@ -35,7 +35,7 @@ import org.springframework.stereotype.Repository;
public class OrganizationsService extends JpaBaseService<Organizations>{ public class OrganizationsService extends JpaBaseService<Organizations>{
@Autowired @Autowired
MqPersistService mqPersistService; MessageQueueService messageQueueService;
public OrganizationsService() { public OrganizationsService() {
super(OrganizationsMapper.class); super(OrganizationsMapper.class);
@ -51,7 +51,7 @@ public class OrganizationsService extends JpaBaseService<Organizations>{
public boolean insert(Organizations organization) { public boolean insert(Organizations organization) {
if(super.insert(organization)){ if(super.insert(organization)){
mqPersistService.send( messageQueueService.send(
MqIdentityTopic.ORG_TOPIC, organization, MqIdentityAction.CREATE_ACTION); MqIdentityTopic.ORG_TOPIC, organization, MqIdentityAction.CREATE_ACTION);
return true; return true;
} }
@ -60,7 +60,7 @@ public class OrganizationsService extends JpaBaseService<Organizations>{
public boolean update(Organizations organization) { public boolean update(Organizations organization) {
if(super.update(organization)){ if(super.update(organization)){
mqPersistService.send( messageQueueService.send(
MqIdentityTopic.ORG_TOPIC, organization, MqIdentityAction.UPDATE_ACTION); MqIdentityTopic.ORG_TOPIC, organization, MqIdentityAction.UPDATE_ACTION);
return true; return true;
} }
@ -84,7 +84,7 @@ public class OrganizationsService extends JpaBaseService<Organizations>{
public boolean delete(Organizations organization) { public boolean delete(Organizations organization) {
if(super.delete(organization)){ if(super.delete(organization)){
mqPersistService.send( messageQueueService.send(
MqIdentityTopic.ORG_TOPIC, organization, MqIdentityAction.DELETE_ACTION); MqIdentityTopic.ORG_TOPIC, organization, MqIdentityAction.DELETE_ACTION);
return true; return true;
} }

View File

@ -29,7 +29,7 @@ import org.maxkey.entity.UserInfo;
import org.maxkey.persistence.mapper.UserInfoMapper; import org.maxkey.persistence.mapper.UserInfoMapper;
import org.maxkey.persistence.mq.MqIdentityAction; import org.maxkey.persistence.mq.MqIdentityAction;
import org.maxkey.persistence.mq.MqIdentityTopic; import org.maxkey.persistence.mq.MqIdentityTopic;
import org.maxkey.persistence.mq.MqPersistService; import org.maxkey.persistence.mq.MessageQueueService;
import org.maxkey.persistence.repository.PasswordPolicyValidator; import org.maxkey.persistence.repository.PasswordPolicyValidator;
import org.maxkey.util.DateUtils; import org.maxkey.util.DateUtils;
import org.maxkey.util.StringUtils; import org.maxkey.util.StringUtils;
@ -37,7 +37,6 @@ import org.maxkey.web.WebContext;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
@ -57,10 +56,7 @@ public class UserInfoService extends JpaBaseService<UserInfo> {
PasswordPolicyValidator passwordPolicyValidator; PasswordPolicyValidator passwordPolicyValidator;
@Autowired @Autowired
MqPersistService mqPersistService; MessageQueueService messageQueueService;
@Autowired
protected JdbcTemplate jdbcTemplate;
AccountsService accountsService; AccountsService accountsService;
@ -79,9 +75,9 @@ public class UserInfoService extends JpaBaseService<UserInfo> {
public boolean insert(UserInfo userInfo) { public boolean insert(UserInfo userInfo) {
this.passwordEncoder(userInfo); this.passwordEncoder(userInfo);
if (super.insert(userInfo)) { if (super.insert(userInfo)) {
if(mqPersistService.getApplicationConfig().isMessageQueueSupport()) { if(messageQueueService.getApplicationConfig().isMessageQueueSupport()) {
UserInfo loadUserInfo = findUserRelated(userInfo.getId()); UserInfo loadUserInfo = findUserRelated(userInfo.getId());
mqPersistService.send( messageQueueService.send(
MqIdentityTopic.USERINFO_TOPIC, MqIdentityTopic.USERINFO_TOPIC,
loadUserInfo, loadUserInfo,
MqIdentityAction.CREATE_ACTION); MqIdentityAction.CREATE_ACTION);
@ -96,10 +92,10 @@ public class UserInfoService extends JpaBaseService<UserInfo> {
public boolean update(UserInfo userInfo) { public boolean update(UserInfo userInfo) {
ChangePassword changePassword = this.passwordEncoder(userInfo); ChangePassword changePassword = this.passwordEncoder(userInfo);
if (super.update(userInfo)) { if (super.update(userInfo)) {
if(mqPersistService.getApplicationConfig().isMessageQueueSupport()) { if(messageQueueService.getApplicationConfig().isMessageQueueSupport()) {
UserInfo loadUserInfo = findUserRelated(userInfo.getId()); UserInfo loadUserInfo = findUserRelated(userInfo.getId());
accountUpdate(loadUserInfo); accountUpdate(loadUserInfo);
mqPersistService.send( messageQueueService.send(
MqIdentityTopic.USERINFO_TOPIC, MqIdentityTopic.USERINFO_TOPIC,
loadUserInfo, loadUserInfo,
MqIdentityAction.UPDATE_ACTION); MqIdentityAction.UPDATE_ACTION);
@ -113,12 +109,12 @@ public class UserInfoService extends JpaBaseService<UserInfo> {
public boolean delete(UserInfo userInfo) { public boolean delete(UserInfo userInfo) {
UserInfo loadUserInfo = null; UserInfo loadUserInfo = null;
if(mqPersistService.getApplicationConfig().isMessageQueueSupport()) { if(messageQueueService.getApplicationConfig().isMessageQueueSupport()) {
loadUserInfo = findUserRelated(userInfo.getId()); loadUserInfo = findUserRelated(userInfo.getId());
} }
if( super.delete(userInfo)){ if( super.delete(userInfo)){
mqPersistService.send( messageQueueService.send(
MqIdentityTopic.USERINFO_TOPIC, MqIdentityTopic.USERINFO_TOPIC,
loadUserInfo, loadUserInfo,
MqIdentityAction.DELETE_ACTION); MqIdentityAction.DELETE_ACTION);
@ -313,7 +309,7 @@ public class UserInfoService extends JpaBaseService<UserInfo> {
if(changePassworded !=null && StringUtils.isNotBlank(changePassworded.getPassword())) { if(changePassworded !=null && StringUtils.isNotBlank(changePassworded.getPassword())) {
UserInfo loadUserInfo = findByUsername(changePassworded.getUsername()); UserInfo loadUserInfo = findByUsername(changePassworded.getUsername());
ChangePassword changePassword = new ChangePassword(loadUserInfo); ChangePassword changePassword = new ChangePassword(loadUserInfo);
mqPersistService.send( messageQueueService.send(
MqIdentityTopic.PASSWORD_TOPIC, MqIdentityTopic.PASSWORD_TOPIC,
changePassword, changePassword,
MqIdentityAction.PASSWORD_ACTION); MqIdentityAction.PASSWORD_ACTION);

View File

@ -42,6 +42,6 @@ public class OnlineTicketEndpoint {
public String ticketValidate( public String ticketValidate(
@RequestParam(value ="ticket",required = true) String ticket) { @RequestParam(value ="ticket",required = true) String ticket) {
OnlineTicket onlineTicket = onlineTicketService.get(ticket); OnlineTicket onlineTicket = onlineTicketService.get(ticket);
return onlineTicket == null ? "" : onlineTicket.getTicketId(); return onlineTicket == null ? "" : onlineTicket.getFormattedTicketId();
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top] * Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -44,7 +44,7 @@ public abstract class AbstractAuthorizeAdapter {
protected Accounts account; protected Accounts account;
protected SigninPrincipal authentication; protected SigninPrincipal principal;
public abstract Object generateInfo(); public abstract Object generateInfo();
@ -127,12 +127,9 @@ public abstract class AbstractAuthorizeAdapter {
return ""; return "";
}; };
public void setAuthentication(SigninPrincipal authentication) { public void setPrincipal(SigninPrincipal principal) {
this.authentication = authentication; this.principal = principal;
} this.userInfo = principal.getUserInfo();
public void setUserInfo(UserInfo userInfo) {
this.userInfo = userInfo;
} }
public void setApp(Apps app) { public void setApp(Apps app) {

View File

@ -34,7 +34,7 @@ public class DefaultSingleLogout extends SingleLogout{
logoutParameters.put("principal", authentication.getName()); logoutParameters.put("principal", authentication.getName());
logoutParameters.put("request", "logoutRequest"); logoutParameters.put("request", "logoutRequest");
logoutParameters.put("issueInstant", DateUtils.getCurrentDateAsString(DateUtils.FORMAT_DATE_ISO_TIMESTAMP)); logoutParameters.put("issueInstant", DateUtils.getCurrentDateAsString(DateUtils.FORMAT_DATE_ISO_TIMESTAMP));
logoutParameters.put("ticket", ((SigninPrincipal)authentication.getPrincipal()).getOnlineTicket().getTicketId()); logoutParameters.put("ticket", ((SigninPrincipal)authentication.getPrincipal()).getOnlineTicket().getFormattedTicketId());
postMessage(logoutApp.getLogoutUrl(),logoutParameters); postMessage(logoutApp.getLogoutUrl(),logoutParameters);
} }

View File

@ -36,7 +36,6 @@ import org.maxkey.authz.cas.endpoint.ticket.ProxyTicketImpl;
import org.maxkey.authz.cas.endpoint.ticket.Ticket; import org.maxkey.authz.cas.endpoint.ticket.Ticket;
import org.maxkey.authz.endpoint.adapter.AbstractAuthorizeAdapter; import org.maxkey.authz.endpoint.adapter.AbstractAuthorizeAdapter;
import org.maxkey.constants.ConstsBoolean; import org.maxkey.constants.ConstsBoolean;
import org.maxkey.entity.UserInfo;
import org.maxkey.util.Instance; import org.maxkey.util.Instance;
import org.maxkey.util.StringUtils; import org.maxkey.util.StringUtils;
import org.maxkey.web.HttpResponseConstants; import org.maxkey.web.HttpResponseConstants;
@ -228,11 +227,8 @@ For all error codes, it is RECOMMENDED that CAS provide a more detailed message
_logger.error("setProperty error . ", e); _logger.error("setProperty error . ", e);
} }
UserInfo userInfo = (UserInfo) userInfoService.findByUsername(authentication.getUsername());
AbstractAuthorizeAdapter adapter =(AbstractAuthorizeAdapter)samlAdapter; AbstractAuthorizeAdapter adapter =(AbstractAuthorizeAdapter)samlAdapter;
adapter.setAuthentication(authentication); adapter.setPrincipal(authentication);
adapter.setUserInfo(userInfo);
adapter.setApp(storedTicket.getCasDetails()); adapter.setApp(storedTicket.getCasDetails());
adapter.generateInfo(); adapter.generateInfo();
} }
@ -345,11 +341,8 @@ Response on ticket validation failure:
_logger.error("setProperty error . ", e); _logger.error("setProperty error . ", e);
} }
UserInfo userInfo = (UserInfo) userInfoService.findByUsername(authentication.getUsername());
AbstractAuthorizeAdapter adapter =(AbstractAuthorizeAdapter)samlAdapter; AbstractAuthorizeAdapter adapter =(AbstractAuthorizeAdapter)samlAdapter;
adapter.setAuthentication(authentication); adapter.setPrincipal(authentication);
adapter.setUserInfo(userInfo);
adapter.setApp(storedTicket.getCasDetails()); adapter.setApp(storedTicket.getCasDetails());
adapter.generateInfo(); adapter.generateInfo();
} }

View File

@ -36,7 +36,6 @@ import org.maxkey.authz.cas.endpoint.ticket.ProxyTicketImpl;
import org.maxkey.authz.cas.endpoint.ticket.Ticket; import org.maxkey.authz.cas.endpoint.ticket.Ticket;
import org.maxkey.authz.endpoint.adapter.AbstractAuthorizeAdapter; import org.maxkey.authz.endpoint.adapter.AbstractAuthorizeAdapter;
import org.maxkey.constants.ConstsBoolean; import org.maxkey.constants.ConstsBoolean;
import org.maxkey.entity.UserInfo;
import org.maxkey.util.Instance; import org.maxkey.util.Instance;
import org.maxkey.util.StringUtils; import org.maxkey.util.StringUtils;
import org.maxkey.web.HttpResponseConstants; import org.maxkey.web.HttpResponseConstants;
@ -109,11 +108,8 @@ public class Cas30AuthorizeEndpoint extends CasBaseAuthorizeEndpoint{
_logger.error("setProperty error . ", e); _logger.error("setProperty error . ", e);
} }
UserInfo userInfo = (UserInfo) userInfoService.findByUsername(authentication.getUsername());
AbstractAuthorizeAdapter adapter =(AbstractAuthorizeAdapter)samlAdapter; AbstractAuthorizeAdapter adapter =(AbstractAuthorizeAdapter)samlAdapter;
adapter.setAuthentication(authentication); adapter.setPrincipal(authentication);
adapter.setUserInfo(userInfo);
adapter.setApp(storedTicket.getCasDetails()); adapter.setApp(storedTicket.getCasDetails());
adapter.generateInfo(); adapter.generateInfo();
} }
@ -190,11 +186,8 @@ public class Cas30AuthorizeEndpoint extends CasBaseAuthorizeEndpoint{
_logger.error("setProperty error . ", e); _logger.error("setProperty error . ", e);
} }
UserInfo userInfo = (UserInfo) userInfoService.findByUsername(authentication.getUsername());
AbstractAuthorizeAdapter adapter =(AbstractAuthorizeAdapter)samlAdapter; AbstractAuthorizeAdapter adapter =(AbstractAuthorizeAdapter)samlAdapter;
adapter.setAuthentication(authentication); adapter.setPrincipal(authentication);
adapter.setUserInfo(userInfo);
adapter.setApp(storedTicket.getCasDetails()); adapter.setApp(storedTicket.getCasDetails());
adapter.generateInfo(); adapter.generateInfo();
} }

View File

@ -149,7 +149,7 @@ public class CasAuthorizeEndpoint extends CasBaseAuthorizeEndpoint{
} }
if(casDetails.getLogoutType()==LogoutType.BACK_CHANNEL) { if(casDetails.getLogoutType()==LogoutType.BACK_CHANNEL) {
String onlineTicketId = AuthorizationUtils.getPrincipal().getOnlineTicket().getTicketId(); String onlineTicketId = AuthorizationUtils.getPrincipal().getOnlineTicket().getFormattedTicketId();
OnlineTicket onlineTicket = onlineTicketService.get(onlineTicketId); OnlineTicket onlineTicket = onlineTicketService.get(onlineTicketId);
//set cas ticket as OnlineTicketId //set cas ticket as OnlineTicketId
casDetails.setOnlineTicket(ticket); casDetails.setOnlineTicket(ticket);

View File

@ -1,5 +1,5 @@
/* /*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top] * Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -75,7 +75,7 @@ public class CasDefaultAdapter extends AbstractAuthorizeAdapter {
serviceResponseBuilder.setAttribute("departmentId", userInfo.getDepartmentId()); serviceResponseBuilder.setAttribute("departmentId", userInfo.getDepartmentId());
serviceResponseBuilder.setAttribute("workRegion",base64Attr(userInfo.getWorkRegion())); serviceResponseBuilder.setAttribute("workRegion",base64Attr(userInfo.getWorkRegion()));
serviceResponseBuilder.setAttribute("institution", userInfo.getInstId()); serviceResponseBuilder.setAttribute("institution", userInfo.getInstId());
serviceResponseBuilder.setAttribute(WebConstants.ONLINE_TICKET_NAME,authentication.getOnlineTicket().getTicketId()); serviceResponseBuilder.setAttribute(WebConstants.ONLINE_TICKET_NAME,principal.getOnlineTicket().getFormattedTicketId());
return serviceResponseBuilder; return serviceResponseBuilder;
} }

View File

@ -67,8 +67,7 @@ public class ExtendApiAuthorizeEndpoint extends AuthorizeBaseEndpoint{
return generateInitCredentialModelAndView(id,"/authorize/api/"+id); return generateInitCredentialModelAndView(id,"/authorize/api/"+id);
} }
adapter.setAuthentication(AuthorizationUtils.getPrincipal()); adapter.setPrincipal(AuthorizationUtils.getPrincipal());
adapter.setUserInfo(currentUser);
adapter.setApp(apps); adapter.setApp(apps);
adapter.setAccount(account); adapter.setAccount(account);

View File

@ -90,8 +90,7 @@ public class FormBasedAuthorizeEndpoint extends AuthorizeBaseEndpoint{
FormBasedDefaultAdapter formBasedDefaultAdapter =new FormBasedDefaultAdapter(); FormBasedDefaultAdapter formBasedDefaultAdapter =new FormBasedDefaultAdapter();
adapter =(AbstractAuthorizeAdapter)formBasedDefaultAdapter; adapter =(AbstractAuthorizeAdapter)formBasedDefaultAdapter;
} }
adapter.setAuthentication(AuthorizationUtils.getPrincipal()); adapter.setPrincipal(AuthorizationUtils.getPrincipal());
adapter.setUserInfo(currentUser);
adapter.setApp(formBasedDetails); adapter.setApp(formBasedDetails);
adapter.setAccount(account); adapter.setAccount(account);

View File

@ -82,7 +82,7 @@ public class JwtAdapter extends AbstractAuthorizeAdapter {
.claim("user_id", userInfo.getId()) .claim("user_id", userInfo.getId())
.claim("external_id", userInfo.getId()) .claim("external_id", userInfo.getId())
.claim("locale", userInfo.getLocale()) .claim("locale", userInfo.getLocale())
.claim(WebConstants.ONLINE_TICKET_NAME, authentication.getOnlineTicket().getTicketId()) .claim(WebConstants.ONLINE_TICKET_NAME, principal.getOnlineTicket().getFormattedTicketId())
.claim("kid", jwtDetails.getId()+ "_sig") .claim("kid", jwtDetails.getId()+ "_sig")
.claim("institution", userInfo.getInstId()) .claim("institution", userInfo.getInstId())
.build(); .build();

View File

@ -101,8 +101,7 @@ public class JwtAuthorizeEndpoint extends AuthorizeBaseEndpoint{
adapter = (AbstractAuthorizeAdapter)jwtAdapter; adapter = (AbstractAuthorizeAdapter)jwtAdapter;
} }
adapter.setAuthentication(AuthorizationUtils.getPrincipal()); adapter.setPrincipal(AuthorizationUtils.getPrincipal());
adapter.setUserInfo(currentUser);
adapter.generateInfo(); adapter.generateInfo();
//sign //sign

View File

@ -47,25 +47,25 @@ public class OAuth2UserDetailsService implements UserDetailsService {
String onlineTickitId = WebConstants.ONLINE_TICKET_PREFIX + "-" + java.util.UUID.randomUUID().toString().toLowerCase(); String onlineTickitId = WebConstants.ONLINE_TICKET_PREFIX + "-" + java.util.UUID.randomUUID().toString().toLowerCase();
SigninPrincipal signinPrincipal = new SigninPrincipal(userInfo); SigninPrincipal principal = new SigninPrincipal(userInfo);
OnlineTicket onlineTicket = new OnlineTicket(onlineTickitId); OnlineTicket onlineTicket = new OnlineTicket(onlineTickitId);
//set OnlineTicket //set OnlineTicket
signinPrincipal.setOnlineTicket(onlineTicket); principal.setOnlineTicket(onlineTicket);
ArrayList<GrantedAuthority> grantedAuthoritys = loginRepository.grantAuthority(userInfo); ArrayList<GrantedAuthority> grantedAuthoritys = loginRepository.grantAuthority(userInfo);
signinPrincipal.setAuthenticated(true); principal.setAuthenticated(true);
for(GrantedAuthority administratorsAuthority : AbstractAuthenticationProvider.grantedAdministratorsAuthoritys) { for(GrantedAuthority administratorsAuthority : AbstractAuthenticationProvider.grantedAdministratorsAuthoritys) {
if(grantedAuthoritys.contains(administratorsAuthority)) { if(grantedAuthoritys.contains(administratorsAuthority)) {
signinPrincipal.setRoleAdministrators(true); principal.setRoleAdministrators(true);
_logger.trace("ROLE ADMINISTRATORS Authentication ."); _logger.trace("ROLE ADMINISTRATORS Authentication .");
} }
} }
_logger.debug("Granted Authority " + grantedAuthoritys); _logger.debug("Granted Authority " + grantedAuthoritys);
signinPrincipal.setGrantedAuthorityApps(grantedAuthoritys); principal.setGrantedAuthorityApps(grantedAuthoritys);
return signinPrincipal; return principal;
} }
public void setLoginRepository(LoginRepository loginRepository) { public void setLoginRepository(LoginRepository loginRepository) {

View File

@ -1,5 +1,5 @@
/* /*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top] * Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.

View File

@ -1,5 +1,5 @@
/* /*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top] * Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -66,7 +66,7 @@ public class OAuthDefaultUserInfoAdapter extends AbstractAuthorizeAdapter {
beanMap.put("state", userInfo.getWorkRegion()); beanMap.put("state", userInfo.getWorkRegion());
beanMap.put("gender", userInfo.getGender()); beanMap.put("gender", userInfo.getGender());
beanMap.put("institution", userInfo.getInstId()); beanMap.put("institution", userInfo.getInstId());
beanMap.put(WebConstants.ONLINE_TICKET_NAME, authentication.getOnlineTicket().getTicketId()); beanMap.put(WebConstants.ONLINE_TICKET_NAME, principal.getOnlineTicket().getFormattedTicketId());
String info= JsonUtils.object2Json(beanMap); String info= JsonUtils.object2Json(beanMap);

View File

@ -93,18 +93,14 @@ public class UserInfoEndpoint {
httpResponseAdapter.write(response,JsonUtils.gson2Json(accessTokenFormatError(access_token)),"json"); httpResponseAdapter.write(response,JsonUtils.gson2Json(accessTokenFormatError(access_token)),"json");
} }
String principal="";
OAuth2Authentication oAuth2Authentication =null; OAuth2Authentication oAuth2Authentication =null;
try{ try{
oAuth2Authentication = oauth20tokenServices.loadAuthentication(access_token); oAuth2Authentication = oauth20tokenServices.loadAuthentication(access_token);
principal=((SigninPrincipal)oAuth2Authentication.getUserAuthentication().getPrincipal()).getUsername();
String client_id= oAuth2Authentication.getOAuth2Request().getClientId(); String client_id= oAuth2Authentication.getOAuth2Request().getClientId();
ClientDetails clientDetails = ClientDetails clientDetails =
clientDetailsService.loadClientByClientId(client_id,true); clientDetailsService.loadClientByClientId(client_id,true);
UserInfo userInfo=queryUserInfo(principal);
Apps app = appsService.get(client_id); Apps app = appsService.get(client_id);
AbstractAuthorizeAdapter adapter; AbstractAuthorizeAdapter adapter;
@ -118,8 +114,7 @@ public class UserInfoEndpoint {
}else{ }else{
adapter =(AbstractAuthorizeAdapter)new OAuthDefaultUserInfoAdapter(clientDetails); adapter =(AbstractAuthorizeAdapter)new OAuthDefaultUserInfoAdapter(clientDetails);
} }
adapter.setAuthentication((SigninPrincipal)oAuth2Authentication.getUserAuthentication().getPrincipal()); adapter.setPrincipal((SigninPrincipal)oAuth2Authentication.getUserAuthentication().getPrincipal());
adapter.setUserInfo(userInfo);
adapter.setApp(app); adapter.setApp(app);
Object jsonData = adapter.generateInfo(); Object jsonData = adapter.generateInfo();

View File

@ -134,7 +134,7 @@ public class UserInfoOIDCEndpoint {
jwtClaimsSetBuilder.claim("sub", subject); jwtClaimsSetBuilder.claim("sub", subject);
jwtClaimsSetBuilder.claim("institution", userInfo.getInstId()); jwtClaimsSetBuilder.claim("institution", userInfo.getInstId());
jwtClaimsSetBuilder.claim(WebConstants.ONLINE_TICKET_NAME, authentication.getOnlineTicket().getTicketId()); jwtClaimsSetBuilder.claim(WebConstants.ONLINE_TICKET_NAME, authentication.getOnlineTicket().getFormattedTicketId());
if(scopes.contains("profile")){ if(scopes.contains("profile")){
jwtClaimsSetBuilder.claim("userId", userInfo.getId()); jwtClaimsSetBuilder.claim("userId", userInfo.getId());

View File

@ -1,5 +1,5 @@
/* /*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top] * Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -78,7 +78,7 @@ public class AssertionEndpoint {
logger.debug("AuthnRequestInfo: {}", authnRequestInfo); logger.debug("AuthnRequestInfo: {}", authnRequestInfo);
HashMap <String,String>attributeMap=new HashMap<String,String>(); HashMap <String,String>attributeMap=new HashMap<String,String>();
attributeMap.put(WebConstants.ONLINE_TICKET_NAME, attributeMap.put(WebConstants.ONLINE_TICKET_NAME,
AuthorizationUtils.getPrincipal().getOnlineTicket().getTicketId()); AuthorizationUtils.getPrincipal().getOnlineTicket().getFormattedTicketId());
//saml20Details //saml20Details
Response authResponse = authnResponseGenerator.generateAuthnResponse( Response authResponse = authnResponseGenerator.generateAuthnResponse(

View File

@ -87,8 +87,7 @@ public class TokenBasedAuthorizeEndpoint extends AuthorizeBaseEndpoint{
}else{ }else{
adapter =(AbstractAuthorizeAdapter)new TokenBasedDefaultAdapter(); adapter =(AbstractAuthorizeAdapter)new TokenBasedDefaultAdapter();
} }
adapter.setAuthentication(AuthorizationUtils.getPrincipal()); adapter.setPrincipal(AuthorizationUtils.getPrincipal());
adapter.setUserInfo(currentUser);
adapter.setApp(tokenBasedDetails); adapter.setApp(tokenBasedDetails);
adapter.generateInfo(); adapter.generateInfo();

View File

@ -73,7 +73,7 @@ public class TokenBasedDefaultAdapter extends AbstractAuthorizeAdapter {
} }
beanMap.put("displayName", userInfo.getDisplayName()); beanMap.put("displayName", userInfo.getDisplayName());
beanMap.put(WebConstants.ONLINE_TICKET_NAME, authentication.getOnlineTicket().getTicketId()); beanMap.put(WebConstants.ONLINE_TICKET_NAME, principal.getOnlineTicket().getFormattedTicketId());
/* /*
* use UTC date time format * use UTC date time format

View File

@ -1,5 +1,5 @@
/* /*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top] * Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.

View File

@ -33,7 +33,6 @@ import org.maxkey.web.interceptor.SingleSignOnInterceptor;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@ -49,15 +48,12 @@ public class MaxKeyMvcConfig implements WebMvcConfigurer {
private static final Logger _logger = LoggerFactory.getLogger(MaxKeyMvcConfig.class); private static final Logger _logger = LoggerFactory.getLogger(MaxKeyMvcConfig.class);
@Autowired @Autowired
@Qualifier("applicationConfig")
ApplicationConfig applicationConfig; ApplicationConfig applicationConfig;
@Autowired @Autowired
@Qualifier("authenticationProvider")
AbstractAuthenticationProvider authenticationProvider ; AbstractAuthenticationProvider authenticationProvider ;
@Autowired @Autowired
@Qualifier("kerberosService")
KerberosService kerberosService; KerberosService kerberosService;
@Autowired @Autowired

View File

@ -1,5 +1,5 @@
/* /*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top] * Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -25,8 +25,6 @@ import org.maxkey.authn.online.OnlineTicketService;
import org.maxkey.entity.HistoryLogin; import org.maxkey.entity.HistoryLogin;
import org.maxkey.entity.Message; import org.maxkey.entity.Message;
import org.maxkey.entity.UserInfo; import org.maxkey.entity.UserInfo;
import org.maxkey.persistence.repository.LoginHistoryRepository;
import org.maxkey.persistence.repository.LoginRepository;
import org.maxkey.persistence.service.HistoryLoginService; import org.maxkey.persistence.service.HistoryLoginService;
import org.maxkey.util.DateUtils; import org.maxkey.util.DateUtils;
import org.maxkey.util.StringUtils; import org.maxkey.util.StringUtils;
@ -57,11 +55,6 @@ public class LoginSessionController {
@Autowired @Autowired
HistoryLoginService historyLoginService; HistoryLoginService historyLoginService;
@Autowired
LoginRepository loginRepository;
@Autowired
LoginHistoryRepository loginHistoryRepository;
@Autowired @Autowired
OnlineTicketService onlineTicketService; OnlineTicketService onlineTicketService;
@ -85,8 +78,6 @@ public class LoginSessionController {
).buildResponse(); ).buildResponse();
} }
@ResponseBody @ResponseBody
@RequestMapping(value="/terminate") @RequestMapping(value="/terminate")
public ResponseEntity<?> terminate(@RequestParam("ids") String ids,@CurrentUser UserInfo currentUser) { public ResponseEntity<?> terminate(@RequestParam("ids") String ids,@CurrentUser UserInfo currentUser) {
@ -98,10 +89,11 @@ public class LoginSessionController {
if(currentUser.getOnlineTicket().contains(sessionId)) { if(currentUser.getOnlineTicket().contains(sessionId)) {
continue;//skip current session continue;//skip current session
} }
String lastLogoffTime = DateUtils.formatDateTime(new Date());
loginRepository.updateLastLogoff(currentUser); onlineTicketService.terminate(
loginHistoryRepository.logoff(lastLogoffTime, sessionId); sessionId,
onlineTicketService.remove("OT-" + sessionId); currentUser.getId(),
currentUser.getUsername());
} }
isTerminated = true; isTerminated = true;
}catch(Exception e) { }catch(Exception e) {

View File

@ -1 +1,18 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.web.access.contorller; package org.maxkey.web.access.contorller;

View File

@ -1,5 +1,5 @@
/* /*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top] * Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.

View File

@ -1,5 +1,5 @@
/* /*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top] * Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -19,106 +19,42 @@ package org.maxkey.web.endpoint;
import java.util.Iterator; import java.util.Iterator;
import java.util.Set; import java.util.Set;
import java.util.UUID;
import java.util.Map.Entry; import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest; import org.maxkey.authn.annotation.CurrentUser;
import javax.servlet.http.HttpServletResponse;
import org.maxkey.authn.online.OnlineTicket; import org.maxkey.authn.online.OnlineTicket;
import org.maxkey.authn.online.OnlineTicketService; import org.maxkey.authn.online.OnlineTicketService;
import org.maxkey.authn.realm.AbstractAuthenticationRealm;
import org.maxkey.authn.web.AuthorizationUtils;
import org.maxkey.authz.singlelogout.SamlSingleLogout; import org.maxkey.authz.singlelogout.SamlSingleLogout;
import org.maxkey.authz.singlelogout.DefaultSingleLogout; import org.maxkey.authz.singlelogout.DefaultSingleLogout;
import org.maxkey.authz.singlelogout.LogoutType; import org.maxkey.authz.singlelogout.LogoutType;
import org.maxkey.authz.singlelogout.SingleLogout; import org.maxkey.authz.singlelogout.SingleLogout;
import org.maxkey.configuration.ApplicationConfig;
import org.maxkey.constants.ConstsProtocols; import org.maxkey.constants.ConstsProtocols;
import org.maxkey.entity.Message;
import org.maxkey.entity.UserInfo;
import org.maxkey.entity.apps.Apps; import org.maxkey.entity.apps.Apps;
import org.maxkey.web.WebConstants;
import org.maxkey.web.WebContext;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.MediaType;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.http.ResponseEntity;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
@Tag(name = "1-3-单点注销接口文档模块") @Tag(name = "1-3-单点注销接口文档模块")
@Controller @Controller
public class LogoutEndpoint { public class LogoutEndpoint {
private static Logger _logger = LoggerFactory.getLogger(LogoutEndpoint.class); private static Logger _logger = LoggerFactory.getLogger(LogoutEndpoint.class);
public static final String RE_LOGIN_URL = "reLoginUrl";
@Autowired
@Qualifier("authenticationRealm")
AbstractAuthenticationRealm authenticationRealm;
@Autowired
ApplicationConfig applicationConfig;
@Autowired @Autowired
protected OnlineTicketService onlineTicketService; protected OnlineTicketService onlineTicketService;
@Operation(summary = "单点注销接口", description = "reLoginUrl跳转地址",method="GET") @Operation(summary = "单点注销接口", description = "reLoginUrl跳转地址",method="GET")
@RequestMapping(value={"/logout"}) @RequestMapping(value={"/logout"}, produces = {MediaType.APPLICATION_JSON_VALUE})
public ModelAndView logout( public ResponseEntity<?> logout(@CurrentUser UserInfo currentUser){
HttpServletRequest request,
HttpServletResponse response,
@RequestParam(value=RE_LOGIN_URL,required=false) String reLoginUrl){
return logoutModelAndView(request,response,"loggedout",reLoginUrl);
}
@Operation(summary = "登录超时接口", description = "",method="GET")
@RequestMapping(value={"/timeout"})
public ModelAndView timeout(HttpServletRequest request, HttpServletResponse response){
return logoutModelAndView(request,response,"timeout",null);
}
private ModelAndView logoutModelAndView(
HttpServletRequest request,
HttpServletResponse response,
String viewName,
String reLoginUrl){
ModelAndView modelAndView = new ModelAndView();
authenticationRealm.logout(response);
if(reLoginUrl==null ||reLoginUrl.equals("")){
SavedRequest firstSavedRequest = (SavedRequest)WebContext.getAttribute(WebConstants.FIRST_SAVED_REQUEST_PARAMETER);
reLoginUrl="/login";
if(firstSavedRequest!=null){
reLoginUrl= firstSavedRequest.getRedirectUrl();
WebContext.removeAttribute(WebConstants.FIRST_SAVED_REQUEST_PARAMETER);
}
}
//not start with http or https
if(reLoginUrl!=null && !reLoginUrl.toLowerCase().startsWith("http")) {
if(reLoginUrl.startsWith("/")) {
reLoginUrl=request.getContextPath()+reLoginUrl;
}else {
reLoginUrl=request.getContextPath()+"/"+reLoginUrl;
}
}
_logger.debug("re Login URL : "+ reLoginUrl);
modelAndView.addObject("reloginUrl",reLoginUrl);
//if logined in have onlineTicket ,need remove or logout back //if logined in have onlineTicket ,need remove or logout back
if(AuthorizationUtils.getAuthentication() != null) { String onlineTicketId = currentUser.getOnlineTicket();
String onlineTicketId = (AuthorizationUtils.getPrincipal()).getOnlineTicket().getTicketId();
OnlineTicket onlineTicket = onlineTicketService.get(onlineTicketId); OnlineTicket onlineTicket = onlineTicketService.get(onlineTicketId);
if(onlineTicket != null) { if(onlineTicket != null) {
Set<Entry<String, Apps>> entrySet = onlineTicket.getAuthorizedApps().entrySet(); Set<Entry<String, Apps>> entrySet = onlineTicket.getAuthorizedApps().entrySet();
@ -137,23 +73,12 @@ public class LogoutEndpoint {
singleLogout.sendRequest(onlineTicket.getAuthentication(), mapEntry.getValue()); singleLogout.sendRequest(onlineTicket.getAuthentication(), mapEntry.getValue());
} }
} }
onlineTicketService.remove(onlineTicketId);
}
}
//remove ONLINE_TICKET cookie
WebContext.expiryCookie(
WebContext.getResponse(),
this.applicationConfig.getBaseDomainName(),
WebConstants.ONLINE_TICKET_NAME,
UUID.randomUUID().toString()
);
request.getSession().invalidate();
//for(String removeAttribute : WebContext.logoutAttributeNameList) {
// request.getSession().removeAttribute(removeAttribute);
//}
SecurityContextHolder.clearContext();
modelAndView.setViewName(viewName); onlineTicketService.terminate(
return modelAndView; onlineTicketId,
currentUser.getId(),
currentUser.getUsername());
}
return new Message<String>().buildResponse();
} }
} }

View File

@ -32,8 +32,6 @@ import org.maxkey.web.WebContext;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.web.servlet.AsyncHandlerInterceptor; import org.springframework.web.servlet.AsyncHandlerInterceptor;
@ -47,7 +45,6 @@ public class HistorySignOnAppInterceptor implements AsyncHandlerInterceptor {
HistoryLoginAppsService historyLoginAppsService; HistoryLoginAppsService historyLoginAppsService;
@Autowired @Autowired
@Qualifier("appsService")
protected AppsService appsService; protected AppsService appsService;
/** /**
@ -59,10 +56,9 @@ public class HistorySignOnAppInterceptor implements AsyncHandlerInterceptor {
throws Exception { throws Exception {
_logger.debug("preHandle"); _logger.debug("preHandle");
final Apps app = (Apps)WebContext.getAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP); final Apps app = (Apps)WebContext.getAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP);
Authentication authentication = AuthorizationUtils.getAuthentication(); SigninPrincipal principal = AuthorizationUtils.getPrincipal();
if(authentication.getPrincipal() instanceof SigninPrincipal) { if(principal != null) {
SigninPrincipal signinPrincipal = (SigninPrincipal)authentication.getPrincipal() ; if(principal.getGrantedAuthorityApps().contains(new SimpleGrantedAuthority(app.getId()))) {
if(signinPrincipal.getGrantedAuthorityApps().contains(new SimpleGrantedAuthority(app.getId()))) {
_logger.trace("preHandle have authority access " + app); _logger.trace("preHandle have authority access " + app);
return true; return true;
} }
@ -85,12 +81,10 @@ public class HistorySignOnAppInterceptor implements AsyncHandlerInterceptor {
final Apps app = (Apps)WebContext.getAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP); final Apps app = (Apps)WebContext.getAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP);
Authentication authentication = AuthorizationUtils.getAuthentication(); SigninPrincipal principal = AuthorizationUtils.getPrincipal();
if((authentication != null) if(principal != null) {
&& (authentication.getPrincipal() instanceof SigninPrincipal)) { final UserInfo userInfo = principal.getUserInfo();
SigninPrincipal signinPrincipal = AuthorizationUtils.getPrincipal(); String sessionId = principal.getOnlineTicket().getFormattedTicketId().substring(3);
final UserInfo userInfo = signinPrincipal.getUserInfo();
String sessionId = signinPrincipal.getOnlineTicket().getTicketId().substring(3);
_logger.debug("sessionId : " + sessionId + " ,appId : " + app.getId()); _logger.debug("sessionId : " + sessionId + " ,appId : " + app.getId());
HistoryLoginApps historyLoginApps = new HistoryLoginApps(); HistoryLoginApps historyLoginApps = new HistoryLoginApps();
historyLoginApps.setAppId(app.getId()); historyLoginApps.setAppId(app.getId());

View File

@ -1,5 +1,5 @@
/* /*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top] * Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.

View File

@ -1,5 +1,5 @@
/* /*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top] * Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -19,6 +19,8 @@ package org.maxkey;
import org.maxkey.jobs.AccountsStrategyJob; import org.maxkey.jobs.AccountsStrategyJob;
import org.maxkey.jobs.DynamicGroupsJob; import org.maxkey.jobs.DynamicGroupsJob;
import org.maxkey.persistence.repository.LoginHistoryRepository;
import org.maxkey.persistence.repository.LoginRepository;
import org.maxkey.persistence.service.AccountsService; import org.maxkey.persistence.service.AccountsService;
import org.maxkey.persistence.service.GroupsService; import org.maxkey.persistence.service.GroupsService;
import org.opensaml.xml.ConfigurationException; import org.opensaml.xml.ConfigurationException;
@ -134,6 +136,14 @@ public class MaxKeyMgtJobs implements InitializingBean {
scheduler.scheduleJob(jobDetail,cronTrigger); scheduler.scheduleJob(jobDetail,cronTrigger);
} }
public String SessionListenerJob(
SchedulerFactoryBean schedulerFactoryBean,
LoginRepository loginRepository,
LoginHistoryRepository loginHistoryRepository) {
return "sessionListenerJob";
}
@Override @Override
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() throws Exception {

View File

@ -1,5 +1,5 @@
/* /*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top] * Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -98,6 +98,8 @@ public class MaxKeyMgtMvcConfig implements WebMvcConfigurer {
authenticationProvider,jwtLoginService,applicationConfig,true)) authenticationProvider,jwtLoginService,applicationConfig,true))
.addPathPatterns("/login"); .addPathPatterns("/login");
permissionInterceptor.setMgmt(true);
registry.addInterceptor(permissionInterceptor) registry.addInterceptor(permissionInterceptor)
.addPathPatterns("/dashboard/**") .addPathPatterns("/dashboard/**")
.addPathPatterns("/orgs/**") .addPathPatterns("/orgs/**")

View File

@ -1,5 +1,5 @@
/* /*
* Copyright [2021] [MaxKey of copyright http://www.maxkey.top] * Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.

View File

@ -1,5 +1,5 @@
/* /*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top] * Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.

View File

@ -0,0 +1,38 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.jobs;
import java.io.Serializable;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OnlineTicketListenerJob implements Job , Serializable {
final static Logger _logger = LoggerFactory.getLogger(OnlineTicketListenerJob.class);
private static final long serialVersionUID = 4782358765969474833L;
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
// TODO Auto-generated method stub
}
}

View File

@ -1,5 +1,5 @@
/* /*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top] * Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -97,10 +97,7 @@ public class LoginSessionController {
if(currentUser.getOnlineTicket().contains(sessionId)) { if(currentUser.getOnlineTicket().contains(sessionId)) {
continue;//skip current session continue;//skip current session
} }
String lastLogoffTime = DateUtils.formatDateTime(new Date()); onlineTicketService.terminate(sessionId,currentUser.getId(),currentUser.getUsername());
loginRepository.updateLastLogoff(currentUser);
loginHistoryRepository.logoff(lastLogoffTime, sessionId);
onlineTicketService.remove("OT-" + sessionId);
} }
isTerminated = true; isTerminated = true;
}catch(Exception e) { }catch(Exception e) {

View File

@ -1 +1,18 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.web.access.contorller; package org.maxkey.web.access.contorller;

View File

@ -1 +1,18 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.web.config.contorller; package org.maxkey.web.config.contorller;

View File

@ -1,5 +1,5 @@
/* /*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top] * Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -17,62 +17,29 @@
package org.maxkey.web.contorller; package org.maxkey.web.contorller;
import javax.servlet.http.HttpServletRequest; import org.maxkey.authn.annotation.CurrentUser;
import javax.servlet.http.HttpServletResponse; import org.maxkey.authn.online.OnlineTicketService;
import org.maxkey.entity.Message;
import org.maxkey.authn.realm.AbstractAuthenticationRealm; import org.maxkey.entity.UserInfo;
import org.maxkey.web.WebConstants;
import org.maxkey.web.WebContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.MediaType;
import org.springframework.security.web.savedrequest.SavedRequest; import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
@Controller @Controller
public class LogoutEndpoint { public class LogoutEndpoint {
private static Logger _logger = LoggerFactory.getLogger(LogoutEndpoint.class);
public static final String RE_LOGIN_URL = "reLoginUrl";
@Autowired @Autowired
@Qualifier("authenticationRealm") protected OnlineTicketService onlineTicketService;
AbstractAuthenticationRealm authenticationRealm;
@RequestMapping(value={"/logout"}) @RequestMapping(value={"/logout"}, produces = {MediaType.APPLICATION_JSON_VALUE})
public ModelAndView logout( HttpServletRequest request, public ResponseEntity<?> logout(@CurrentUser UserInfo currentUser){
HttpServletResponse response, onlineTicketService.terminate(
@RequestParam(value=RE_LOGIN_URL,required=false) String reLoginUrl){ currentUser.getOnlineTicket(),
ModelAndView modelAndView = new ModelAndView(); currentUser.getId(),
authenticationRealm.logout(response); currentUser.getUsername());
SavedRequest firstSavedRequest = (SavedRequest)WebContext.getAttribute(WebConstants.FIRST_SAVED_REQUEST_PARAMETER); return new Message<String>().buildResponse();
if(reLoginUrl==null ||reLoginUrl.equals("")) {
reLoginUrl="/login";
}
if(firstSavedRequest!=null){
reLoginUrl= firstSavedRequest.getRedirectUrl();
}
if(reLoginUrl!=null && !reLoginUrl.toLowerCase().startsWith("http")) {
if(reLoginUrl.startsWith("/")) {
reLoginUrl=request.getContextPath()+reLoginUrl;
}else {
reLoginUrl=request.getContextPath()+"/"+reLoginUrl;
}
}
_logger.debug("re Login URL : "+ reLoginUrl);
modelAndView.addObject("reloginUrl",reLoginUrl);
request.getSession().invalidate();
modelAndView.setViewName("loggedout");
return modelAndView;
} }
} }

View File

@ -1 +1,18 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed 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.maxkey.web.permissions.contorller; package org.maxkey.web.permissions.contorller;