This commit is contained in:
MaxKey 2022-04-26 17:41:04 +08:00
parent 946b346282
commit e51a3a25ba
37 changed files with 236 additions and 218 deletions

View File

@ -20,9 +20,9 @@ package org.maxkey.authn;
import java.util.ArrayList;
import org.maxkey.authn.jwt.AuthJwtService;
import org.maxkey.authn.online.OnlineTicket;
import org.maxkey.authn.online.OnlineTicketService;
import org.maxkey.authn.realm.AbstractAuthenticationRealm;
import org.maxkey.authn.session.Session;
import org.maxkey.authn.session.SessionService;
import org.maxkey.authn.web.AuthorizationUtils;
import org.maxkey.configuration.ApplicationConfig;
import org.maxkey.constants.ConstsLoginType;
@ -67,7 +67,7 @@ public abstract class AbstractAuthenticationProvider {
protected OtpAuthnService otpAuthnService;
protected OnlineTicketService onlineTicketServices;
protected SessionService sessionService;
protected AuthJwtService authJwtService;
@ -102,13 +102,13 @@ public abstract class AbstractAuthenticationProvider {
*/
public UsernamePasswordAuthenticationToken createOnlineTicket(LoginCredential credential,UserInfo userInfo) {
//Online Tickit
OnlineTicket onlineTicket = new OnlineTicket();
Session onlineTicket = new Session();
userInfo.setOnlineTicket(onlineTicket.getTicketId());
userInfo.setOnlineTicket(onlineTicket.getId());
SigninPrincipal principal = new SigninPrincipal(userInfo);
//set OnlineTicket
principal.setOnlineTicket(onlineTicket);
principal.setSession(onlineTicket);
ArrayList<GrantedAuthority> grantedAuthoritys = authenticationRealm.grantAuthority(userInfo);
principal.setAuthenticated(true);
@ -134,8 +134,8 @@ public abstract class AbstractAuthenticationProvider {
onlineTicket.setAuthentication(authenticationToken);
//store onlineTicket
this.onlineTicketServices.store(onlineTicket.getTicketId(), onlineTicket);
//store session
this.sessionService.store(onlineTicket.getId(), onlineTicket);
/*
* put Authentication to current session context

View File

@ -20,7 +20,7 @@ package org.maxkey.authn;
import java.util.ArrayList;
import java.util.Collection;
import org.maxkey.authn.online.OnlineTicket;
import org.maxkey.authn.session.Session;
import org.maxkey.entity.UserInfo;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
@ -32,7 +32,7 @@ public class SigninPrincipal implements UserDetails {
UserDetails userDetails;
OnlineTicket onlineTicket;
Session session;
ArrayList<GrantedAuthority> grantedAuthority;
ArrayList<GrantedAuthority> grantedAuthorityApps;
boolean authenticated;
@ -109,12 +109,12 @@ public class SigninPrincipal implements UserDetails {
this.grantedAuthority = grantedAuthority;
}
public OnlineTicket getOnlineTicket() {
return onlineTicket;
public Session getSession() {
return session;
}
public void setOnlineTicket(OnlineTicket onlineTicket) {
this.onlineTicket = onlineTicket;
public void setSession(Session session) {
this.session = session;
}
public boolean isRoleAdministrators() {
@ -178,7 +178,7 @@ public class SigninPrincipal implements UserDetails {
builder.append("SigninPrincipal [userInfo=");
builder.append(userInfo);
builder.append(", onlineTicket=");
builder.append(onlineTicket);
builder.append(session);
builder.append(", grantedAuthority=");
builder.append(grantedAuthority);
builder.append(", authenticated=");

View File

@ -60,7 +60,7 @@ public class AuthJwt implements Serializable {
SigninPrincipal principal = ((SigninPrincipal)authentication.getPrincipal());
this.token = token;
this.ticket = principal.getOnlineTicket().getTicketId();
this.ticket = principal.getSession().getId();
this.id = principal.getUserInfo().getId();
this.username = principal.getUserInfo().getUsername();

View File

@ -97,7 +97,7 @@ public class AuthJwtService {
JWTClaimsSet jwtClaims =new JWTClaimsSet.Builder()
.issuer(authJwkConfig.getIssuer())
.subject(subject)
.jwtID(principal.getOnlineTicket().getTicketId())
.jwtID(principal.getSession().getId())
.issueTime(currentDateTime.toDate())
.expirationTime(expirationTime)
.claim("locale", userInfo.getLocale())

View File

@ -20,8 +20,8 @@ package org.maxkey.authn.provider;
import org.maxkey.authn.AbstractAuthenticationProvider;
import org.maxkey.authn.LoginCredential;
import org.maxkey.authn.jwt.AuthJwtService;
import org.maxkey.authn.online.OnlineTicketService;
import org.maxkey.authn.realm.AbstractAuthenticationRealm;
import org.maxkey.authn.session.SessionService;
import org.maxkey.configuration.ApplicationConfig;
import org.maxkey.constants.ConstsLoginType;
import org.maxkey.entity.Institutions;
@ -57,11 +57,11 @@ public class MfaAuthenticationProvider extends AbstractAuthenticationProvider {
public MfaAuthenticationProvider(
AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig,
OnlineTicketService onlineTicketServices,
SessionService sessionService,
AuthJwtService authJwtService) {
this.authenticationRealm = authenticationRealm;
this.applicationConfig = applicationConfig;
this.onlineTicketServices = onlineTicketServices;
this.sessionService = sessionService;
this.authJwtService = authJwtService;
}

View File

@ -19,8 +19,8 @@ package org.maxkey.authn.provider;
import org.maxkey.authn.AbstractAuthenticationProvider;
import org.maxkey.authn.LoginCredential;
import org.maxkey.authn.online.OnlineTicketService;
import org.maxkey.authn.realm.AbstractAuthenticationRealm;
import org.maxkey.authn.session.SessionService;
import org.maxkey.configuration.ApplicationConfig;
import org.maxkey.constants.ConstsLoginType;
import org.maxkey.entity.UserInfo;
@ -60,11 +60,11 @@ public class MobileAuthenticationProvider extends AbstractAuthenticationProvider
AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig,
OtpAuthnService otpAuthnService,
OnlineTicketService onlineTicketServices) {
SessionService sessionService) {
this.authenticationRealm = authenticationRealm;
this.applicationConfig = applicationConfig;
this.otpAuthnService = otpAuthnService;
this.onlineTicketServices = onlineTicketServices;
this.sessionService = sessionService;
}
@Override

View File

@ -21,8 +21,8 @@ import java.text.ParseException;
import org.maxkey.authn.AbstractAuthenticationProvider;
import org.maxkey.authn.LoginCredential;
import org.maxkey.authn.jwt.AuthJwtService;
import org.maxkey.authn.online.OnlineTicketService;
import org.maxkey.authn.realm.AbstractAuthenticationRealm;
import org.maxkey.authn.session.SessionService;
import org.maxkey.configuration.ApplicationConfig;
import org.maxkey.constants.ConstsLoginType;
import org.maxkey.entity.Institutions;
@ -57,11 +57,11 @@ public class NormalAuthenticationProvider extends AbstractAuthenticationProvider
public NormalAuthenticationProvider(
AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig,
OnlineTicketService onlineTicketServices,
SessionService sessionService,
AuthJwtService authJwtService) {
this.authenticationRealm = authenticationRealm;
this.applicationConfig = applicationConfig;
this.onlineTicketServices = onlineTicketServices;
this.sessionService = sessionService;
this.authJwtService = authJwtService;
}

View File

@ -19,8 +19,8 @@ package org.maxkey.authn.provider;
import org.maxkey.authn.AbstractAuthenticationProvider;
import org.maxkey.authn.LoginCredential;
import org.maxkey.authn.online.OnlineTicketService;
import org.maxkey.authn.realm.AbstractAuthenticationRealm;
import org.maxkey.authn.session.SessionService;
import org.maxkey.configuration.ApplicationConfig;
import org.maxkey.entity.UserInfo;
import org.maxkey.web.WebContext;
@ -49,10 +49,10 @@ public class TrustedAuthenticationProvider extends AbstractAuthenticationProvide
public TrustedAuthenticationProvider(
AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig,
OnlineTicketService onlineTicketServices) {
SessionService sessionService) {
this.authenticationRealm = authenticationRealm;
this.applicationConfig = applicationConfig;
this.onlineTicketServices = onlineTicketServices;
this.sessionService = sessionService;
}
@Override

View File

@ -15,7 +15,7 @@
*/
package org.maxkey.authn.online;
package org.maxkey.authn.session;
import java.sql.ResultSet;
import java.sql.SQLException;
@ -32,8 +32,8 @@ 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);
public class AbstractSessionService implements SessionService{
private static Logger _logger = LoggerFactory.getLogger(AbstractSessionService.class);
protected JdbcTemplate jdbcTemplate;
@ -93,17 +93,17 @@ public class AbstractOnlineTicketService implements OnlineTicketService{
}
@Override
public void store(String ticketId, OnlineTicket ticket) {
public void store(String ticketId, Session ticket) {
}
@Override
public OnlineTicket remove(String ticket) {
public Session remove(String ticket) {
return null;
}
@Override
public OnlineTicket get(String ticketId) {
public Session get(String ticketId) {
return null;
}

View File

@ -15,7 +15,7 @@
*/
package org.maxkey.authn.online;
package org.maxkey.authn.session;
import java.time.Duration;
import java.time.LocalTime;
@ -29,41 +29,41 @@ import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
public class InMemoryOnlineTicketService extends AbstractOnlineTicketService{
private static final Logger _logger = LoggerFactory.getLogger(InMemoryOnlineTicketService.class);
public class InMemorySessionService extends AbstractSessionService{
private static final Logger _logger = LoggerFactory.getLogger(InMemorySessionService.class);
protected static Cache<String, OnlineTicket> onlineTicketStore =
protected static Cache<String, Session> sessionStore =
Caffeine.newBuilder()
.expireAfterWrite(30, TimeUnit.MINUTES)
.maximumSize(200000)
.build();
public InMemoryOnlineTicketService(JdbcTemplate jdbcTemplate) {
public InMemorySessionService(JdbcTemplate jdbcTemplate) {
super();
this.jdbcTemplate = jdbcTemplate;
}
@Override
public void store(String ticketId, OnlineTicket ticket) {
onlineTicketStore.put(ticketId, ticket);
public void store(String sessionId, Session session) {
sessionStore.put(sessionId, session);
}
@Override
public OnlineTicket remove(String ticketId) {
OnlineTicket ticket=onlineTicketStore.getIfPresent(ticketId);
onlineTicketStore.invalidate(ticketId);
return ticket;
public Session remove(String sessionId) {
Session session = sessionStore.getIfPresent(sessionId);
sessionStore.invalidate(sessionId);
return session;
}
@Override
public OnlineTicket get(String ticketId) {
OnlineTicket ticket=onlineTicketStore.getIfPresent(ticketId);
return ticket;
public Session get(String sessionId) {
Session session = sessionStore.getIfPresent(sessionId);
return session;
}
@Override
public void setValiditySeconds(int validitySeconds) {
onlineTicketStore =
sessionStore =
Caffeine.newBuilder()
.expireAfterWrite(validitySeconds/60, TimeUnit.MINUTES)
.maximumSize(200000)
@ -72,24 +72,24 @@ public class InMemoryOnlineTicketService extends AbstractOnlineTicketService{
}
@Override
public void refresh(String ticketId,LocalTime refreshTime) {
OnlineTicket onlineTicket = get(ticketId);
onlineTicket.setTicketTime(refreshTime);
store(ticketId , onlineTicket);
public void refresh(String sessionId,LocalTime refreshTime) {
Session session = get(sessionId);
session.setLastAccessTime(refreshTime);
store(sessionId , session);
}
@Override
public void refresh(String ticketId) {
OnlineTicket onlineTicket = get(ticketId);
public void refresh(String sessionId) {
Session session = get(sessionId);
LocalTime currentTime = LocalTime.now();
Duration duration = Duration.between(currentTime, onlineTicket.getTicketTime());
Duration duration = Duration.between(currentTime, session.getLastAccessTime());
_logger.trace("OnlineTicket duration " + duration.getSeconds());
if(duration.getSeconds() > OnlineTicket.MAX_EXPIRY_DURATION) {
onlineTicket.setTicketTime(currentTime);
refresh(ticketId,currentTime);
if(duration.getSeconds() > Session.MAX_EXPIRY_DURATION) {
session.setLastAccessTime(currentTime);
refresh(sessionId,currentTime);
}
}

View File

@ -15,7 +15,7 @@
*/
package org.maxkey.authn.online;
package org.maxkey.authn.session;
import java.time.Duration;
import java.time.LocalTime;
@ -27,18 +27,18 @@ import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
public class RedisOnlineTicketService extends AbstractOnlineTicketService {
private static final Logger _logger = LoggerFactory.getLogger(RedisOnlineTicketService.class);
public class RedisSessionService extends AbstractSessionService {
private static final Logger _logger = LoggerFactory.getLogger(RedisSessionService.class);
protected int serviceTicketValiditySeconds = 60 * 30; //default 30 minutes.
RedisConnectionFactory connectionFactory;
public static String PREFIX="REDIS_ONLINE_TICKET_";
public static String PREFIX="REDIS_SESSION_";
/**
* @param connectionFactory
*/
public RedisOnlineTicketService(
public RedisSessionService(
RedisConnectionFactory connectionFactory,
JdbcTemplate jdbcTemplate) {
super();
@ -49,7 +49,7 @@ public class RedisOnlineTicketService extends AbstractOnlineTicketService {
/**
*
*/
public RedisOnlineTicketService() {
public RedisSessionService() {
}
@ -58,27 +58,27 @@ public class RedisOnlineTicketService extends AbstractOnlineTicketService {
}
@Override
public void store(String ticketId, OnlineTicket ticket) {
public void store(String ticketId, Session ticket) {
RedisConnection conn=connectionFactory.getConnection();
conn.setexObject(PREFIX+ticketId, serviceTicketValiditySeconds, ticket);
conn.close();
}
@Override
public OnlineTicket remove(String ticketId) {
public Session remove(String ticketId) {
RedisConnection conn=connectionFactory.getConnection();
OnlineTicket ticket = conn.getObject(PREFIX+ticketId);
Session ticket = conn.getObject(PREFIX+ticketId);
conn.delete(PREFIX+ticketId);
conn.close();
return ticket;
}
@Override
public OnlineTicket get(String ticketId) {
public Session get(String ticketId) {
RedisConnection conn=connectionFactory.getConnection();
OnlineTicket ticket = conn.getObject(PREFIX+ticketId);
Session session = conn.getObject(PREFIX+ticketId);
conn.close();
return ticket;
return session;
}
@Override
@ -88,23 +88,23 @@ public class RedisOnlineTicketService extends AbstractOnlineTicketService {
}
@Override
public void refresh(String ticketId,LocalTime refreshTime) {
OnlineTicket onlineTicket = get(ticketId);
onlineTicket.setTicketTime(refreshTime);
store(ticketId , onlineTicket);
public void refresh(String sessionId,LocalTime refreshTime) {
Session session = get(sessionId);
session.setLastAccessTime(refreshTime);
store(sessionId , session);
}
@Override
public void refresh(String ticketId) {
OnlineTicket onlineTicket = get(ticketId);
Session session = get(ticketId);
LocalTime currentTime = LocalTime.now();
Duration duration = Duration.between(currentTime, onlineTicket.getTicketTime());
Duration duration = Duration.between(currentTime, session.getLastAccessTime());
_logger.trace("OnlineTicket duration " + duration.getSeconds());
if(duration.getSeconds() > OnlineTicket.MAX_EXPIRY_DURATION) {
onlineTicket.setTicketTime(currentTime);
if(duration.getSeconds() > Session.MAX_EXPIRY_DURATION) {
session.setLastAccessTime(currentTime);
refresh(ticketId,currentTime);
}
}

View File

@ -15,7 +15,7 @@
*/
package org.maxkey.authn.online;
package org.maxkey.authn.session;
import java.io.Serializable;
import java.time.LocalTime;
@ -25,61 +25,75 @@ import org.maxkey.entity.apps.Apps;
import org.maxkey.web.WebContext;
import org.springframework.security.core.Authentication;
public class OnlineTicket implements Serializable{
public class Session implements Serializable{
private static final long serialVersionUID = 9008067569150338296L;
public static final String ONLINE_TICKET_PREFIX = "OT";
public static final String SESSION_PREFIX = "OT";
public static final int MAX_EXPIRY_DURATION = 60 * 10; //default 10 minutes.
public String ticketId;
public String id;
public LocalTime ticketTime;
public LocalTime startTimestamp;
public LocalTime lastAccessTime;
public Authentication authentication;
private HashMap<String , Apps> authorizedApps = new HashMap<String , Apps>();
public OnlineTicket() {
public Session() {
super();
this.ticketId = WebContext.genId();;
this.ticketTime = LocalTime.now();
this.id = WebContext.genId();;
this.startTimestamp = LocalTime.now();
this.lastAccessTime = LocalTime.now();
}
public OnlineTicket(String ticketId) {
public Session(String sessionId) {
super();
this.ticketId = ticketId;
this.ticketTime = LocalTime.now();
this.id = sessionId;
this.startTimestamp = LocalTime.now();
this.lastAccessTime = LocalTime.now();
}
public OnlineTicket(String ticketId,Authentication authentication) {
public Session(String sessionId,Authentication authentication) {
super();
this.ticketId = ticketId;
this.id = sessionId;
this.authentication = authentication;
this.ticketTime = LocalTime.now();
this.startTimestamp = LocalTime.now();
this.lastAccessTime = LocalTime.now();
}
public String getTicketId() {
return ticketId;
public String getId() {
return id;
}
public String getFormattedTicketId() {
return ticketId;
public String getFormattedId() {
return id;
}
public void setTicketId(String ticketId) {
this.ticketId = ticketId;
public void setId(String ticketId) {
this.id = ticketId;
}
public LocalTime getTicketTime() {
return ticketTime;
}
public void setTicketTime(LocalTime ticketTime) {
this.ticketTime = ticketTime;
}
public LocalTime getStartTimestamp() {
return startTimestamp;
}
public Authentication getAuthentication() {
public void setStartTimestamp(LocalTime startTimestamp) {
this.startTimestamp = startTimestamp;
}
public LocalTime getLastAccessTime() {
return lastAccessTime;
}
public void setLastAccessTime(LocalTime lastAccessTime) {
this.lastAccessTime = lastAccessTime;
}
public Authentication getAuthentication() {
return authentication;
}
@ -100,13 +114,17 @@ public class OnlineTicket implements Serializable{
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("OnlineTicket [ticketId=");
builder.append(ticketId);
builder.append("]");
return builder.toString();
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Session [id=");
builder.append(id);
builder.append(", startTimestamp=");
builder.append(startTimestamp);
builder.append(", lastAccessTime=");
builder.append(lastAccessTime);
builder.append("]");
return builder.toString();
}
}

View File

@ -15,20 +15,20 @@
*/
package org.maxkey.authn.online;
package org.maxkey.authn.session;
import java.time.LocalTime;
import java.util.List;
import org.maxkey.entity.HistoryLogin;
public interface OnlineTicketService {
public interface SessionService {
public void store(String ticketId, OnlineTicket ticket);
public void store(String ticketId, Session ticket);
public OnlineTicket remove(String ticket);
public Session remove(String ticket);
public OnlineTicket get(String ticketId);
public Session get(String ticketId);
public void refresh(String ticketId ,LocalTime refreshTime);

View File

@ -15,7 +15,7 @@
*/
package org.maxkey.authn.online;
package org.maxkey.authn.session;
import org.maxkey.constants.ConstsPersistence;
import org.maxkey.persistence.redis.RedisConnectionFactory;
@ -23,26 +23,26 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
public class OnlineTicketServiceFactory {
public class SessionServiceFactory {
private static final Logger _logger =
LoggerFactory.getLogger(OnlineTicketServiceFactory.class);
LoggerFactory.getLogger(SessionServiceFactory.class);
public OnlineTicketService getService(
public SessionService getService(
int persistence,
JdbcTemplate jdbcTemplate,
RedisConnectionFactory redisConnFactory){
OnlineTicketService onlineTicketServices = null;
SessionService sessionService = null;
if (persistence == ConstsPersistence.INMEMORY) {
onlineTicketServices = new InMemoryOnlineTicketService(jdbcTemplate);
_logger.debug("InMemoryOnlineTicketServices");
sessionService = new InMemorySessionService(jdbcTemplate);
_logger.debug("InMemorySessionService");
} else if (persistence == ConstsPersistence.JDBC) {
_logger.debug("OnlineTicketServices not support ");
_logger.debug("JdbcSessionService not support ");
} else if (persistence == ConstsPersistence.REDIS) {
onlineTicketServices = new RedisOnlineTicketService(redisConnFactory,jdbcTemplate);
_logger.debug("RedisOnlineTicketServices");
sessionService = new RedisSessionService(redisConnFactory,jdbcTemplate);
_logger.debug("RedisSessionService");
}
return onlineTicketServices;
return sessionService;
}
}

View File

@ -24,8 +24,8 @@ import javax.servlet.http.HttpServletRequest;
import org.maxkey.authn.SigninPrincipal;
import org.maxkey.authn.jwt.AuthJwtService;
import org.maxkey.authn.online.OnlineTicket;
import org.maxkey.authn.online.OnlineTicketService;
import org.maxkey.authn.session.Session;
import org.maxkey.authn.session.SessionService;
import org.maxkey.entity.UserInfo;
import org.maxkey.util.AuthorizationHeaderUtils;
import org.maxkey.web.WebConstants;
@ -42,13 +42,13 @@ public class AuthorizationUtils {
public static void authenticateWithCookie(
HttpServletRequest request,
AuthJwtService authJwtService,
OnlineTicketService onlineTicketService
SessionService sessionService
) throws ParseException{
if(getAuthentication() == null) {
Cookie authCookie = WebContext.getCookie(request, Authorization_Cookie);
if(authCookie != null ) {
String authorization = authCookie.getValue();
doJwtAuthenticate(authorization,authJwtService,onlineTicketService);
doJwtAuthenticate(authorization,authJwtService,sessionService);
_logger.debug("congress automatic authenticated .");
}
}
@ -57,12 +57,12 @@ public class AuthorizationUtils {
public static void authenticate(
HttpServletRequest request,
AuthJwtService authJwtService,
OnlineTicketService onlineTicketService
SessionService sessionService
) throws ParseException{
if(getAuthentication() == null) {
String authorization = AuthorizationHeaderUtils.resolveBearer(request);
if(authorization != null ) {
doJwtAuthenticate(authorization,authJwtService,onlineTicketService);
doJwtAuthenticate(authorization,authJwtService,sessionService);
_logger.debug("Authorization automatic authenticated .");
}
}
@ -71,10 +71,10 @@ public class AuthorizationUtils {
public static void doJwtAuthenticate(
String authorization,
AuthJwtService authJwtService,
OnlineTicketService onlineTicketService) throws ParseException {
SessionService sessionService) throws ParseException {
if(authJwtService.validateJwtToken(authorization)) {
String ticket = authJwtService.resolveJWTID(authorization);
OnlineTicket onlineTicket = onlineTicketService.get(ticket);
Session onlineTicket = sessionService.get(ticket);
if(onlineTicket != null) {
setAuthentication(onlineTicket.getAuthentication());
}

View File

@ -60,7 +60,7 @@ public class SessionListenerAdapter implements HttpSessionListener {
session.getId(),
principal.getUserInfo().getId(),
principal.getUserInfo().getUsername(),
principal.getOnlineTicket().getTicketId());
principal.getSession().getId());
}
}

View File

@ -23,7 +23,7 @@ import javax.servlet.http.HttpServletResponse;
import org.maxkey.authn.SigninPrincipal;
import org.maxkey.authn.jwt.AuthJwtService;
import org.maxkey.authn.online.OnlineTicketService;
import org.maxkey.authn.session.SessionService;
import org.maxkey.authn.web.AuthorizationUtils;
import org.maxkey.configuration.ApplicationConfig;
import org.slf4j.Logger;
@ -44,7 +44,7 @@ public class PermissionInterceptor implements AsyncHandlerInterceptor {
ApplicationConfig applicationConfig;
@Autowired
OnlineTicketService onlineTicketService;
SessionService sessionService;
@Autowired
AuthJwtService authJwtService ;
@ -59,7 +59,7 @@ public class PermissionInterceptor implements AsyncHandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
_logger.trace("Permission Interceptor .");
AuthorizationUtils.authenticate(request, authJwtService, onlineTicketService);
AuthorizationUtils.authenticate(request, authJwtService, sessionService);
SigninPrincipal principal = AuthorizationUtils.getPrincipal();
//判断用户是否登录,判断用户是否登录用户
if(principal == null){

View File

@ -23,13 +23,13 @@ import org.maxkey.authn.jwt.AuthJwtService;
import org.maxkey.authn.jwt.CongressService;
import org.maxkey.authn.jwt.InMemoryCongressService;
import org.maxkey.authn.jwt.RedisCongressService;
import org.maxkey.authn.online.OnlineTicketService;
import org.maxkey.authn.online.OnlineTicketServiceFactory;
import org.maxkey.authn.provider.AuthenticationProviderFactory;
import org.maxkey.authn.provider.MobileAuthenticationProvider;
import org.maxkey.authn.provider.NormalAuthenticationProvider;
import org.maxkey.authn.provider.TrustedAuthenticationProvider;
import org.maxkey.authn.realm.AbstractAuthenticationRealm;
import org.maxkey.authn.session.SessionService;
import org.maxkey.authn.session.SessionServiceFactory;
import org.maxkey.authn.web.SessionListenerAdapter;
import org.maxkey.configuration.ApplicationConfig;
import org.maxkey.configuration.AuthJwkConfig;
@ -86,14 +86,14 @@ public class AuthenticationAutoConfiguration implements InitializingBean {
public AbstractAuthenticationProvider normalAuthenticationProvider(
AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig,
OnlineTicketService onlineTicketServices,
SessionService sessionService,
AuthJwtService authJwtService
) {
_logger.debug("init authentication Provider .");
return new NormalAuthenticationProvider(
authenticationRealm,
applicationConfig,
onlineTicketServices,
sessionService,
authJwtService
);
}
@ -103,14 +103,14 @@ public class AuthenticationAutoConfiguration implements InitializingBean {
AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig,
OtpAuthnService otpAuthnService,
OnlineTicketService onlineTicketServices
SessionService sessionService
) {
_logger.debug("init Mobile authentication Provider .");
return new MobileAuthenticationProvider(
authenticationRealm,
applicationConfig,
otpAuthnService,
onlineTicketServices
sessionService
);
}
@ -118,13 +118,13 @@ public class AuthenticationAutoConfiguration implements InitializingBean {
public AbstractAuthenticationProvider trustedAuthenticationProvider(
AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig,
OnlineTicketService onlineTicketServices
SessionService sessionService
) {
_logger.debug("init Mobile authentication Provider .");
return new TrustedAuthenticationProvider(
authenticationRealm,
applicationConfig,
onlineTicketServices
sessionService
);
}
@ -181,18 +181,18 @@ public class AuthenticationAutoConfiguration implements InitializingBean {
}
@Bean(name = "onlineTicketService")
public OnlineTicketService onlineTicketService(
@Bean(name = "sessionService")
public SessionService sessionService(
@Value("${maxkey.server.persistence}") int persistence,
JdbcTemplate jdbcTemplate,
RedisConnectionFactory redisConnFactory,
@Value("${server.servlet.session.timeout:1800}") int timeout
) {
OnlineTicketService onlineTicketService =
new OnlineTicketServiceFactory().getService(persistence, jdbcTemplate, redisConnFactory);
onlineTicketService.setValiditySeconds(timeout);
SessionService sessionService =
new SessionServiceFactory().getService(persistence, jdbcTemplate, redisConnFactory);
sessionService.setValiditySeconds(timeout);
_logger.trace("onlineTicket timeout " + timeout);
return onlineTicketService;
return sessionService;
}
@Bean(name = "sessionListenerAdapter")

View File

@ -17,8 +17,8 @@
package org.maxkey.authz.endpoint;
import org.maxkey.authn.online.OnlineTicket;
import org.maxkey.authn.online.OnlineTicketService;
import org.maxkey.authn.session.Session;
import org.maxkey.authn.session.SessionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@ -34,14 +34,14 @@ import io.swagger.v3.oas.annotations.tags.Tag;
public class OnlineTicketEndpoint {
@Autowired
protected OnlineTicketService onlineTicketService;
protected SessionService onlineTicketService;
@Operation(summary = "在线ticket验证接口", description = "",method="GET")
@ResponseBody
@RequestMapping(value="/validate")
public String ticketValidate(
@RequestParam(value ="ticket",required = true) String ticket) {
OnlineTicket onlineTicket = onlineTicketService.get(ticket);
return onlineTicket == null ? "" : onlineTicket.getFormattedTicketId();
Session onlineTicket = onlineTicketService.get(ticket);
return onlineTicket == null ? "" : onlineTicket.getFormattedId();
}
}

View File

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

View File

@ -26,7 +26,7 @@ import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.maxkey.authn.online.OnlineTicket;
import org.maxkey.authn.session.Session;
import org.maxkey.authn.web.AuthorizationUtils;
import org.maxkey.authz.cas.endpoint.ticket.CasConstants;
import org.maxkey.authz.cas.endpoint.ticket.ServiceTicketImpl;
@ -149,12 +149,12 @@ public class CasAuthorizeEndpoint extends CasBaseAuthorizeEndpoint{
}
if(casDetails.getLogoutType()==LogoutType.BACK_CHANNEL) {
String onlineTicketId = AuthorizationUtils.getPrincipal().getOnlineTicket().getFormattedTicketId();
OnlineTicket onlineTicket = onlineTicketService.get(onlineTicketId);
String sessionId = AuthorizationUtils.getPrincipal().getSession().getFormattedId();
Session session = sessionService.get(sessionId);
//set cas ticket as OnlineTicketId
casDetails.setOnlineTicket(ticket);
onlineTicket.setAuthorizedApp(casDetails);
onlineTicketService.store(onlineTicketId, onlineTicket);
session.setAuthorizedApp(casDetails);
sessionService.store(sessionId, session);
}
_logger.debug("redirect to CAS Client URL {}" , callbackUrl);

View File

@ -17,7 +17,7 @@
package org.maxkey.authz.cas.endpoint;
import org.maxkey.authn.online.OnlineTicketService;
import org.maxkey.authn.session.SessionService;
import org.maxkey.authz.cas.endpoint.ticket.TicketServices;
import org.maxkey.authz.endpoint.AuthorizeBaseEndpoint;
import org.maxkey.persistence.service.AppsCasDetailsService;
@ -49,7 +49,7 @@ public class CasBaseAuthorizeEndpoint extends AuthorizeBaseEndpoint{
protected TicketServices casTicketGrantingTicketServices;
@Autowired
protected OnlineTicketService onlineTicketService;
protected SessionService sessionService;
@Autowired
@Qualifier("casProxyGrantingTicketServices")

View File

@ -75,7 +75,7 @@ public class CasDefaultAdapter extends AbstractAuthorizeAdapter {
serviceResponseBuilder.setAttribute("departmentId", userInfo.getDepartmentId());
serviceResponseBuilder.setAttribute("workRegion",base64Attr(userInfo.getWorkRegion()));
serviceResponseBuilder.setAttribute("institution", userInfo.getInstId());
serviceResponseBuilder.setAttribute(WebConstants.ONLINE_TICKET_NAME,principal.getOnlineTicket().getFormattedTicketId());
serviceResponseBuilder.setAttribute(WebConstants.ONLINE_TICKET_NAME,principal.getSession().getFormattedId());
return serviceResponseBuilder;
}

View File

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

View File

@ -16,7 +16,7 @@ import java.util.ArrayList;
import org.maxkey.authn.AbstractAuthenticationProvider;
import org.maxkey.authn.SigninPrincipal;
import org.maxkey.authn.online.OnlineTicket;
import org.maxkey.authn.session.Session;
import org.maxkey.entity.UserInfo;
import org.maxkey.persistence.repository.LoginRepository;
import org.maxkey.web.WebConstants;
@ -48,9 +48,9 @@ public class OAuth2UserDetailsService implements UserDetailsService {
String onlineTickitId = WebConstants.ONLINE_TICKET_PREFIX + "-" + java.util.UUID.randomUUID().toString().toLowerCase();
SigninPrincipal principal = new SigninPrincipal(userInfo);
OnlineTicket onlineTicket = new OnlineTicket(onlineTickitId);
Session onlineTicket = new Session(onlineTickitId);
//set OnlineTicket
principal.setOnlineTicket(onlineTicket);
principal.setSession(onlineTicket);
ArrayList<GrantedAuthority> grantedAuthoritys = loginRepository.grantAuthority(userInfo);
principal.setAuthenticated(true);

View File

@ -66,7 +66,7 @@ public class OAuthDefaultUserInfoAdapter extends AbstractAuthorizeAdapter {
beanMap.put("state", userInfo.getWorkRegion());
beanMap.put("gender", userInfo.getGender());
beanMap.put("institution", userInfo.getInstId());
beanMap.put(WebConstants.ONLINE_TICKET_NAME, principal.getOnlineTicket().getFormattedTicketId());
beanMap.put(WebConstants.ONLINE_TICKET_NAME, principal.getSession().getFormattedId());
String info= JsonUtils.object2Json(beanMap);

View File

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

View File

@ -78,7 +78,7 @@ public class AssertionEndpoint {
logger.debug("AuthnRequestInfo: {}", authnRequestInfo);
HashMap <String,String>attributeMap=new HashMap<String,String>();
attributeMap.put(WebConstants.ONLINE_TICKET_NAME,
AuthorizationUtils.getPrincipal().getOnlineTicket().getFormattedTicketId());
AuthorizationUtils.getPrincipal().getSession().getFormattedId());
//saml20Details
Response authResponse = authnResponseGenerator.generateAuthnResponse(

View File

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

View File

@ -21,7 +21,7 @@ import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.mybatis.jpa.persistence.JpaPageResults;
import org.maxkey.authn.annotation.CurrentUser;
import org.maxkey.authn.online.OnlineTicketService;
import org.maxkey.authn.session.SessionService;
import org.maxkey.entity.HistoryLogin;
import org.maxkey.entity.Message;
import org.maxkey.entity.UserInfo;
@ -57,7 +57,7 @@ public class LoginSessionController {
HistoryLoginService historyLoginService;
@Autowired
OnlineTicketService onlineTicketService;
SessionService sessionService;
/**
* 查询登录日志.
@ -90,7 +90,7 @@ public class LoginSessionController {
continue;//skip current session
}
onlineTicketService.terminate(
sessionService.terminate(
sessionId,
currentUser.getId(),
currentUser.getUsername());

View File

@ -22,8 +22,8 @@ import java.util.Set;
import java.util.Map.Entry;
import org.maxkey.authn.annotation.CurrentUser;
import org.maxkey.authn.online.OnlineTicket;
import org.maxkey.authn.online.OnlineTicketService;
import org.maxkey.authn.session.Session;
import org.maxkey.authn.session.SessionService;
import org.maxkey.authz.singlelogout.SamlSingleLogout;
import org.maxkey.authz.singlelogout.DefaultSingleLogout;
import org.maxkey.authz.singlelogout.LogoutType;
@ -48,14 +48,14 @@ public class LogoutEndpoint {
private static Logger _logger = LoggerFactory.getLogger(LogoutEndpoint.class);
@Autowired
protected OnlineTicketService onlineTicketService;
protected SessionService sessionService;
@Operation(summary = "单点注销接口", description = "reLoginUrl跳转地址",method="GET")
@RequestMapping(value={"/logout"}, produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<?> logout(@CurrentUser UserInfo currentUser){
//if logined in have onlineTicket ,need remove or logout back
String onlineTicketId = currentUser.getOnlineTicket();
OnlineTicket onlineTicket = onlineTicketService.get(onlineTicketId);
Session onlineTicket = sessionService.get(onlineTicketId);
if(onlineTicket != null) {
Set<Entry<String, Apps>> entrySet = onlineTicket.getAuthorizedApps().entrySet();
@ -74,7 +74,7 @@ public class LogoutEndpoint {
}
}
onlineTicketService.terminate(
sessionService.terminate(
onlineTicketId,
currentUser.getId(),
currentUser.getUsername());

View File

@ -84,7 +84,7 @@ public class HistorySignOnAppInterceptor implements AsyncHandlerInterceptor {
SigninPrincipal principal = AuthorizationUtils.getPrincipal();
if(principal != null && app !=null) {
final UserInfo userInfo = principal.getUserInfo();
String sessionId = principal.getOnlineTicket().getTicketId();
String sessionId = principal.getSession().getId();
_logger.debug("sessionId : " + sessionId + " ,appId : " + app.getId());
HistoryLoginApps historyLoginApps = new HistoryLoginApps();
historyLoginApps.setAppId(app.getId());

View File

@ -20,7 +20,7 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.maxkey.authn.jwt.AuthJwtService;
import org.maxkey.authn.online.OnlineTicketService;
import org.maxkey.authn.session.SessionService;
import org.maxkey.authn.web.AuthorizationUtils;
import org.maxkey.configuration.ApplicationConfig;
import org.maxkey.crypto.Base64Utils;
@ -39,7 +39,7 @@ public class SingleSignOnInterceptor implements AsyncHandlerInterceptor {
ApplicationConfig applicationConfig;
@Autowired
OnlineTicketService onlineTicketService;
SessionService sessionService;
@Autowired
AuthJwtService authJwtService ;
@ -51,7 +51,7 @@ public class SingleSignOnInterceptor implements AsyncHandlerInterceptor {
_logger.trace("Single Sign On Interceptor");
AuthorizationUtils.authenticateWithCookie(
request,authJwtService,onlineTicketService);
request,authJwtService,sessionService);
if(AuthorizationUtils.isNotAuthenticated()){
String loginUrl = applicationConfig.getFrontendUri() + "/#/passport/login?redirect_uri=%s";

View File

@ -17,10 +17,10 @@
package org.maxkey;
import org.maxkey.authn.online.OnlineTicketService;
import org.maxkey.authn.session.SessionService;
import org.maxkey.jobs.AccountsStrategyJob;
import org.maxkey.jobs.DynamicGroupsJob;
import org.maxkey.jobs.TicketListenerJob;
import org.maxkey.jobs.SessionListenerJob;
import org.maxkey.persistence.service.AccountsService;
import org.maxkey.persistence.service.GroupsService;
import org.quartz.CronScheduleBuilder;
@ -44,22 +44,22 @@ import org.springframework.scheduling.quartz.SchedulerFactoryBean;
public class MaxKeyMgtJobs implements InitializingBean {
private static final Logger _logger = LoggerFactory.getLogger(MaxKeyMgtJobs.class);
@Bean(name = "schedulerTicketListenerJobs")
@Bean(name = "schedulerSessionListenerJobs")
public String ticketListenerJob(
SchedulerFactoryBean schedulerFactoryBean,
OnlineTicketService onlineTicketService) throws SchedulerException {
SessionService sessionService) throws SchedulerException {
JobDataMap jobDataMap = new JobDataMap();
jobDataMap.put("service", onlineTicketService);
jobDataMap.put("service", sessionService);
addJobScheduler(
TicketListenerJob.class,
SessionListenerJob.class,
schedulerFactoryBean,
jobDataMap,
"0 0/10 * * * ?",//10 minutes
"TicketListener"
"SessionListener"
);
return "schedulerTicketListenerJobs";
return "schedulerSessionListenerJobs";
}
@Bean(name = "schedulerDynamicGroupsJobs")

View File

@ -17,7 +17,7 @@ package org.maxkey.jobs;
import java.io.Serializable;
import org.maxkey.authn.online.OnlineTicketService;
import org.maxkey.authn.session.SessionService;
import org.maxkey.entity.HistoryLogin;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
@ -25,12 +25,12 @@ import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TicketListenerJob extends AbstractScheduleJob implements Job , Serializable {
final static Logger _logger = LoggerFactory.getLogger(TicketListenerJob.class);
public class SessionListenerJob extends AbstractScheduleJob implements Job , Serializable {
final static Logger _logger = LoggerFactory.getLogger(SessionListenerJob.class);
private static final long serialVersionUID = 4782358765969474833L;
OnlineTicketService onlineTicketService;
SessionService sessionService;
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
@ -40,13 +40,13 @@ public class TicketListenerJob extends AbstractScheduleJob implements Job , Se
_logger.debug("TicketListener Job is running ... " );
jobStatus = JOBSTATUS.RUNNING;
try {
if(onlineTicketService != null) {
for (HistoryLogin onlineTicket : onlineTicketService.queryOnlineTicket()) {
if(onlineTicketService.get(onlineTicket.getSessionId()) == null) {
onlineTicketService.terminate(
onlineTicket.getSessionId(),
onlineTicket.getUserId(),
onlineTicket.getUsername());
if(sessionService != null) {
for (HistoryLogin onlineSession : sessionService.queryOnlineTicket()) {
if(sessionService.get(onlineSession.getSessionId()) == null) {
sessionService.terminate(
onlineSession.getSessionId(),
onlineSession.getUserId(),
onlineSession.getUsername());
}
}
}
@ -61,9 +61,9 @@ public class TicketListenerJob extends AbstractScheduleJob implements Job , Se
@Override
void init(JobExecutionContext context){
if(onlineTicketService == null) {
onlineTicketService =
(OnlineTicketService) context.getMergedJobDataMap().get("service");
if(sessionService == null) {
sessionService =
(SessionService) context.getMergedJobDataMap().get("service");
}
}
}

View File

@ -21,7 +21,7 @@ import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.mybatis.jpa.persistence.JpaPageResults;
import org.maxkey.authn.annotation.CurrentUser;
import org.maxkey.authn.online.OnlineTicketService;
import org.maxkey.authn.session.SessionService;
import org.maxkey.entity.HistoryLogin;
import org.maxkey.entity.Message;
import org.maxkey.entity.UserInfo;
@ -57,7 +57,7 @@ public class LoginSessionController {
HistoryLoginService historyLoginService;
@Autowired
OnlineTicketService onlineTicketService;
SessionService sessionService;
/**
* 查询登录日志.
@ -90,7 +90,7 @@ public class LoginSessionController {
if(currentUser.getOnlineTicket().contains(sessionId)) {
continue;//skip current session
}
onlineTicketService.terminate(sessionId,currentUser.getId(),currentUser.getUsername());
sessionService.terminate(sessionId,currentUser.getId(),currentUser.getUsername());
}
isTerminated = true;
}catch(Exception e) {

View File

@ -18,7 +18,7 @@
package org.maxkey.web.contorller;
import org.maxkey.authn.annotation.CurrentUser;
import org.maxkey.authn.online.OnlineTicketService;
import org.maxkey.authn.session.SessionService;
import org.maxkey.entity.Message;
import org.maxkey.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
@ -31,11 +31,11 @@ import org.springframework.web.bind.annotation.RequestMapping;
public class LogoutEndpoint {
@Autowired
protected OnlineTicketService onlineTicketService;
protected SessionService sessionService;
@RequestMapping(value={"/logout"}, produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<?> logout(@CurrentUser UserInfo currentUser){
onlineTicketService.terminate(
sessionService.terminate(
currentUser.getOnlineTicket(),
currentUser.getId(),
currentUser.getUsername());