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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -15,7 +15,7 @@
*/ */
package org.maxkey.authn.online; package org.maxkey.authn.session;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
@ -32,8 +32,8 @@ import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.RowMapper;
public class AbstractOnlineTicketService implements OnlineTicketService{ public class AbstractSessionService implements SessionService{
private static Logger _logger = LoggerFactory.getLogger(AbstractOnlineTicketService.class); private static Logger _logger = LoggerFactory.getLogger(AbstractSessionService.class);
protected JdbcTemplate jdbcTemplate; protected JdbcTemplate jdbcTemplate;
@ -93,17 +93,17 @@ public class AbstractOnlineTicketService implements OnlineTicketService{
} }
@Override @Override
public void store(String ticketId, OnlineTicket ticket) { public void store(String ticketId, Session ticket) {
} }
@Override @Override
public OnlineTicket remove(String ticket) { public Session remove(String ticket) {
return null; return null;
} }
@Override @Override
public OnlineTicket get(String ticketId) { public Session get(String ticketId) {
return null; 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.Duration;
import java.time.LocalTime; import java.time.LocalTime;
@ -29,41 +29,41 @@ import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine; import com.github.benmanes.caffeine.cache.Caffeine;
public class InMemoryOnlineTicketService extends AbstractOnlineTicketService{ public class InMemorySessionService extends AbstractSessionService{
private static final Logger _logger = LoggerFactory.getLogger(InMemoryOnlineTicketService.class); private static final Logger _logger = LoggerFactory.getLogger(InMemorySessionService.class);
protected static Cache<String, OnlineTicket> onlineTicketStore = protected static Cache<String, Session> sessionStore =
Caffeine.newBuilder() Caffeine.newBuilder()
.expireAfterWrite(30, TimeUnit.MINUTES) .expireAfterWrite(30, TimeUnit.MINUTES)
.maximumSize(200000) .maximumSize(200000)
.build(); .build();
public InMemoryOnlineTicketService(JdbcTemplate jdbcTemplate) { public InMemorySessionService(JdbcTemplate jdbcTemplate) {
super(); super();
this.jdbcTemplate = jdbcTemplate; this.jdbcTemplate = jdbcTemplate;
} }
@Override @Override
public void store(String ticketId, OnlineTicket ticket) { public void store(String sessionId, Session session) {
onlineTicketStore.put(ticketId, ticket); sessionStore.put(sessionId, session);
} }
@Override @Override
public OnlineTicket remove(String ticketId) { public Session remove(String sessionId) {
OnlineTicket ticket=onlineTicketStore.getIfPresent(ticketId); Session session = sessionStore.getIfPresent(sessionId);
onlineTicketStore.invalidate(ticketId); sessionStore.invalidate(sessionId);
return ticket; return session;
} }
@Override @Override
public OnlineTicket get(String ticketId) { public Session get(String sessionId) {
OnlineTicket ticket=onlineTicketStore.getIfPresent(ticketId); Session session = sessionStore.getIfPresent(sessionId);
return ticket; return session;
} }
@Override @Override
public void setValiditySeconds(int validitySeconds) { public void setValiditySeconds(int validitySeconds) {
onlineTicketStore = sessionStore =
Caffeine.newBuilder() Caffeine.newBuilder()
.expireAfterWrite(validitySeconds/60, TimeUnit.MINUTES) .expireAfterWrite(validitySeconds/60, TimeUnit.MINUTES)
.maximumSize(200000) .maximumSize(200000)
@ -72,24 +72,24 @@ public class InMemoryOnlineTicketService extends AbstractOnlineTicketService{
} }
@Override @Override
public void refresh(String ticketId,LocalTime refreshTime) { public void refresh(String sessionId,LocalTime refreshTime) {
OnlineTicket onlineTicket = get(ticketId); Session session = get(sessionId);
onlineTicket.setTicketTime(refreshTime); session.setLastAccessTime(refreshTime);
store(ticketId , onlineTicket); store(sessionId , session);
} }
@Override @Override
public void refresh(String ticketId) { public void refresh(String sessionId) {
OnlineTicket onlineTicket = get(ticketId); Session session = get(sessionId);
LocalTime currentTime = LocalTime.now(); LocalTime currentTime = LocalTime.now();
Duration duration = Duration.between(currentTime, onlineTicket.getTicketTime()); Duration duration = Duration.between(currentTime, session.getLastAccessTime());
_logger.trace("OnlineTicket duration " + duration.getSeconds()); _logger.trace("OnlineTicket duration " + duration.getSeconds());
if(duration.getSeconds() > OnlineTicket.MAX_EXPIRY_DURATION) { if(duration.getSeconds() > Session.MAX_EXPIRY_DURATION) {
onlineTicket.setTicketTime(currentTime); session.setLastAccessTime(currentTime);
refresh(ticketId,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.Duration;
import java.time.LocalTime; import java.time.LocalTime;
@ -27,18 +27,18 @@ import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.JdbcTemplate;
public class RedisOnlineTicketService extends AbstractOnlineTicketService { public class RedisSessionService extends AbstractSessionService {
private static final Logger _logger = LoggerFactory.getLogger(RedisOnlineTicketService.class); private static final Logger _logger = LoggerFactory.getLogger(RedisSessionService.class);
protected int serviceTicketValiditySeconds = 60 * 30; //default 30 minutes. protected int serviceTicketValiditySeconds = 60 * 30; //default 30 minutes.
RedisConnectionFactory connectionFactory; RedisConnectionFactory connectionFactory;
public static String PREFIX="REDIS_ONLINE_TICKET_"; public static String PREFIX="REDIS_SESSION_";
/** /**
* @param connectionFactory * @param connectionFactory
*/ */
public RedisOnlineTicketService( public RedisSessionService(
RedisConnectionFactory connectionFactory, RedisConnectionFactory connectionFactory,
JdbcTemplate jdbcTemplate) { JdbcTemplate jdbcTemplate) {
super(); super();
@ -49,7 +49,7 @@ public class RedisOnlineTicketService extends AbstractOnlineTicketService {
/** /**
* *
*/ */
public RedisOnlineTicketService() { public RedisSessionService() {
} }
@ -58,27 +58,27 @@ public class RedisOnlineTicketService extends AbstractOnlineTicketService {
} }
@Override @Override
public void store(String ticketId, OnlineTicket ticket) { public void store(String ticketId, Session ticket) {
RedisConnection conn=connectionFactory.getConnection(); RedisConnection conn=connectionFactory.getConnection();
conn.setexObject(PREFIX+ticketId, serviceTicketValiditySeconds, ticket); conn.setexObject(PREFIX+ticketId, serviceTicketValiditySeconds, ticket);
conn.close(); conn.close();
} }
@Override @Override
public OnlineTicket remove(String ticketId) { public Session remove(String ticketId) {
RedisConnection conn=connectionFactory.getConnection(); RedisConnection conn=connectionFactory.getConnection();
OnlineTicket ticket = conn.getObject(PREFIX+ticketId); Session ticket = conn.getObject(PREFIX+ticketId);
conn.delete(PREFIX+ticketId); conn.delete(PREFIX+ticketId);
conn.close(); conn.close();
return ticket; return ticket;
} }
@Override @Override
public OnlineTicket get(String ticketId) { public Session get(String ticketId) {
RedisConnection conn=connectionFactory.getConnection(); RedisConnection conn=connectionFactory.getConnection();
OnlineTicket ticket = conn.getObject(PREFIX+ticketId); Session session = conn.getObject(PREFIX+ticketId);
conn.close(); conn.close();
return ticket; return session;
} }
@Override @Override
@ -88,23 +88,23 @@ public class RedisOnlineTicketService extends AbstractOnlineTicketService {
} }
@Override @Override
public void refresh(String ticketId,LocalTime refreshTime) { public void refresh(String sessionId,LocalTime refreshTime) {
OnlineTicket onlineTicket = get(ticketId); Session session = get(sessionId);
onlineTicket.setTicketTime(refreshTime); session.setLastAccessTime(refreshTime);
store(ticketId , onlineTicket); store(sessionId , session);
} }
@Override @Override
public void refresh(String ticketId) { public void refresh(String ticketId) {
OnlineTicket onlineTicket = get(ticketId); Session session = get(ticketId);
LocalTime currentTime = LocalTime.now(); LocalTime currentTime = LocalTime.now();
Duration duration = Duration.between(currentTime, onlineTicket.getTicketTime()); Duration duration = Duration.between(currentTime, session.getLastAccessTime());
_logger.trace("OnlineTicket duration " + duration.getSeconds()); _logger.trace("OnlineTicket duration " + duration.getSeconds());
if(duration.getSeconds() > OnlineTicket.MAX_EXPIRY_DURATION) { if(duration.getSeconds() > Session.MAX_EXPIRY_DURATION) {
onlineTicket.setTicketTime(currentTime); session.setLastAccessTime(currentTime);
refresh(ticketId,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.io.Serializable;
import java.time.LocalTime; import java.time.LocalTime;
@ -25,58 +25,72 @@ import org.maxkey.entity.apps.Apps;
import org.maxkey.web.WebContext; import org.maxkey.web.WebContext;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
public class OnlineTicket implements Serializable{ public class Session implements Serializable{
private static final long serialVersionUID = 9008067569150338296L; 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 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; public Authentication authentication;
private HashMap<String , Apps> authorizedApps = new HashMap<String , Apps>(); private HashMap<String , Apps> authorizedApps = new HashMap<String , Apps>();
public OnlineTicket() { public Session() {
super(); super();
this.ticketId = WebContext.genId();; this.id = WebContext.genId();;
this.ticketTime = LocalTime.now(); this.startTimestamp = LocalTime.now();
this.lastAccessTime = LocalTime.now();
} }
public OnlineTicket(String ticketId) { public Session(String sessionId) {
super(); super();
this.ticketId = ticketId; this.id = sessionId;
this.ticketTime = LocalTime.now(); this.startTimestamp = LocalTime.now();
this.lastAccessTime = LocalTime.now();
} }
public OnlineTicket(String ticketId,Authentication authentication) { public Session(String sessionId,Authentication authentication) {
super(); super();
this.ticketId = ticketId; this.id = sessionId;
this.authentication = authentication; this.authentication = authentication;
this.ticketTime = LocalTime.now(); this.startTimestamp = LocalTime.now();
this.lastAccessTime = LocalTime.now();
} }
public String getTicketId() { public String getId() {
return ticketId; return id;
} }
public String getFormattedTicketId() { public String getFormattedId() {
return ticketId; return id;
} }
public void setTicketId(String ticketId) { public void setId(String ticketId) {
this.ticketId = ticketId; this.id = ticketId;
} }
public LocalTime getTicketTime() {
return ticketTime; public LocalTime getStartTimestamp() {
return startTimestamp;
} }
public void setTicketTime(LocalTime ticketTime) { public void setStartTimestamp(LocalTime startTimestamp) {
this.ticketTime = ticketTime; this.startTimestamp = startTimestamp;
}
public LocalTime getLastAccessTime() {
return lastAccessTime;
}
public void setLastAccessTime(LocalTime lastAccessTime) {
this.lastAccessTime = lastAccessTime;
} }
public Authentication getAuthentication() { public Authentication getAuthentication() {
@ -102,8 +116,12 @@ public class OnlineTicket implements Serializable{
@Override @Override
public String toString() { public String toString() {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
builder.append("OnlineTicket [ticketId="); builder.append("Session [id=");
builder.append(ticketId); builder.append(id);
builder.append(", startTimestamp=");
builder.append(startTimestamp);
builder.append(", lastAccessTime=");
builder.append(lastAccessTime);
builder.append("]"); builder.append("]");
return builder.toString(); 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.time.LocalTime;
import java.util.List; import java.util.List;
import org.maxkey.entity.HistoryLogin; 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); 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.constants.ConstsPersistence;
import org.maxkey.persistence.redis.RedisConnectionFactory; import org.maxkey.persistence.redis.RedisConnectionFactory;
@ -23,26 +23,26 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.JdbcTemplate;
public class OnlineTicketServiceFactory { public class SessionServiceFactory {
private static final Logger _logger = private static final Logger _logger =
LoggerFactory.getLogger(OnlineTicketServiceFactory.class); LoggerFactory.getLogger(SessionServiceFactory.class);
public OnlineTicketService getService( public SessionService getService(
int persistence, int persistence,
JdbcTemplate jdbcTemplate, JdbcTemplate jdbcTemplate,
RedisConnectionFactory redisConnFactory){ RedisConnectionFactory redisConnFactory){
OnlineTicketService onlineTicketServices = null; SessionService sessionService = null;
if (persistence == ConstsPersistence.INMEMORY) { if (persistence == ConstsPersistence.INMEMORY) {
onlineTicketServices = new InMemoryOnlineTicketService(jdbcTemplate); sessionService = new InMemorySessionService(jdbcTemplate);
_logger.debug("InMemoryOnlineTicketServices"); _logger.debug("InMemorySessionService");
} else if (persistence == ConstsPersistence.JDBC) { } else if (persistence == ConstsPersistence.JDBC) {
_logger.debug("OnlineTicketServices not support "); _logger.debug("JdbcSessionService not support ");
} else if (persistence == ConstsPersistence.REDIS) { } else if (persistence == ConstsPersistence.REDIS) {
onlineTicketServices = new RedisOnlineTicketService(redisConnFactory,jdbcTemplate); sessionService = new RedisSessionService(redisConnFactory,jdbcTemplate);
_logger.debug("RedisOnlineTicketServices"); _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.SigninPrincipal;
import org.maxkey.authn.jwt.AuthJwtService; import org.maxkey.authn.jwt.AuthJwtService;
import org.maxkey.authn.online.OnlineTicket; import org.maxkey.authn.session.Session;
import org.maxkey.authn.online.OnlineTicketService; import org.maxkey.authn.session.SessionService;
import org.maxkey.entity.UserInfo; import org.maxkey.entity.UserInfo;
import org.maxkey.util.AuthorizationHeaderUtils; import org.maxkey.util.AuthorizationHeaderUtils;
import org.maxkey.web.WebConstants; import org.maxkey.web.WebConstants;
@ -42,13 +42,13 @@ public class AuthorizationUtils {
public static void authenticateWithCookie( public static void authenticateWithCookie(
HttpServletRequest request, HttpServletRequest request,
AuthJwtService authJwtService, AuthJwtService authJwtService,
OnlineTicketService onlineTicketService SessionService sessionService
) throws ParseException{ ) throws ParseException{
if(getAuthentication() == null) { if(getAuthentication() == null) {
Cookie authCookie = WebContext.getCookie(request, Authorization_Cookie); Cookie authCookie = WebContext.getCookie(request, Authorization_Cookie);
if(authCookie != null ) { if(authCookie != null ) {
String authorization = authCookie.getValue(); String authorization = authCookie.getValue();
doJwtAuthenticate(authorization,authJwtService,onlineTicketService); doJwtAuthenticate(authorization,authJwtService,sessionService);
_logger.debug("congress automatic authenticated ."); _logger.debug("congress automatic authenticated .");
} }
} }
@ -57,12 +57,12 @@ public class AuthorizationUtils {
public static void authenticate( public static void authenticate(
HttpServletRequest request, HttpServletRequest request,
AuthJwtService authJwtService, AuthJwtService authJwtService,
OnlineTicketService onlineTicketService SessionService sessionService
) throws ParseException{ ) throws ParseException{
if(getAuthentication() == null) { if(getAuthentication() == null) {
String authorization = AuthorizationHeaderUtils.resolveBearer(request); String authorization = AuthorizationHeaderUtils.resolveBearer(request);
if(authorization != null ) { if(authorization != null ) {
doJwtAuthenticate(authorization,authJwtService,onlineTicketService); doJwtAuthenticate(authorization,authJwtService,sessionService);
_logger.debug("Authorization automatic authenticated ."); _logger.debug("Authorization automatic authenticated .");
} }
} }
@ -71,10 +71,10 @@ public class AuthorizationUtils {
public static void doJwtAuthenticate( public static void doJwtAuthenticate(
String authorization, String authorization,
AuthJwtService authJwtService, AuthJwtService authJwtService,
OnlineTicketService onlineTicketService) throws ParseException { SessionService sessionService) throws ParseException {
if(authJwtService.validateJwtToken(authorization)) { if(authJwtService.validateJwtToken(authorization)) {
String ticket = authJwtService.resolveJWTID(authorization); String ticket = authJwtService.resolveJWTID(authorization);
OnlineTicket onlineTicket = onlineTicketService.get(ticket); Session onlineTicket = sessionService.get(ticket);
if(onlineTicket != null) { if(onlineTicket != null) {
setAuthentication(onlineTicket.getAuthentication()); setAuthentication(onlineTicket.getAuthentication());
} }

View File

@ -60,7 +60,7 @@ public class SessionListenerAdapter implements HttpSessionListener {
session.getId(), session.getId(),
principal.getUserInfo().getId(), principal.getUserInfo().getId(),
principal.getUserInfo().getUsername(), 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.SigninPrincipal;
import org.maxkey.authn.jwt.AuthJwtService; 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.authn.web.AuthorizationUtils;
import org.maxkey.configuration.ApplicationConfig; import org.maxkey.configuration.ApplicationConfig;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -44,7 +44,7 @@ public class PermissionInterceptor implements AsyncHandlerInterceptor {
ApplicationConfig applicationConfig; ApplicationConfig applicationConfig;
@Autowired @Autowired
OnlineTicketService onlineTicketService; SessionService sessionService;
@Autowired @Autowired
AuthJwtService authJwtService ; AuthJwtService authJwtService ;
@ -59,7 +59,7 @@ public class PermissionInterceptor implements AsyncHandlerInterceptor {
@Override @Override
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception { public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
_logger.trace("Permission Interceptor ."); _logger.trace("Permission Interceptor .");
AuthorizationUtils.authenticate(request, authJwtService, onlineTicketService); AuthorizationUtils.authenticate(request, authJwtService, sessionService);
SigninPrincipal principal = AuthorizationUtils.getPrincipal(); SigninPrincipal principal = AuthorizationUtils.getPrincipal();
//判断用户是否登录,判断用户是否登录用户 //判断用户是否登录,判断用户是否登录用户
if(principal == null){ 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.CongressService;
import org.maxkey.authn.jwt.InMemoryCongressService; import org.maxkey.authn.jwt.InMemoryCongressService;
import org.maxkey.authn.jwt.RedisCongressService; 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.AuthenticationProviderFactory;
import org.maxkey.authn.provider.MobileAuthenticationProvider; import org.maxkey.authn.provider.MobileAuthenticationProvider;
import org.maxkey.authn.provider.NormalAuthenticationProvider; import org.maxkey.authn.provider.NormalAuthenticationProvider;
import org.maxkey.authn.provider.TrustedAuthenticationProvider; import org.maxkey.authn.provider.TrustedAuthenticationProvider;
import org.maxkey.authn.realm.AbstractAuthenticationRealm; 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.authn.web.SessionListenerAdapter;
import org.maxkey.configuration.ApplicationConfig; import org.maxkey.configuration.ApplicationConfig;
import org.maxkey.configuration.AuthJwkConfig; import org.maxkey.configuration.AuthJwkConfig;
@ -86,14 +86,14 @@ public class AuthenticationAutoConfiguration implements InitializingBean {
public AbstractAuthenticationProvider normalAuthenticationProvider( public AbstractAuthenticationProvider normalAuthenticationProvider(
AbstractAuthenticationRealm authenticationRealm, AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig, ApplicationConfig applicationConfig,
OnlineTicketService onlineTicketServices, SessionService sessionService,
AuthJwtService authJwtService AuthJwtService authJwtService
) { ) {
_logger.debug("init authentication Provider ."); _logger.debug("init authentication Provider .");
return new NormalAuthenticationProvider( return new NormalAuthenticationProvider(
authenticationRealm, authenticationRealm,
applicationConfig, applicationConfig,
onlineTicketServices, sessionService,
authJwtService authJwtService
); );
} }
@ -103,14 +103,14 @@ public class AuthenticationAutoConfiguration implements InitializingBean {
AbstractAuthenticationRealm authenticationRealm, AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig, ApplicationConfig applicationConfig,
OtpAuthnService otpAuthnService, OtpAuthnService otpAuthnService,
OnlineTicketService onlineTicketServices SessionService sessionService
) { ) {
_logger.debug("init Mobile authentication Provider ."); _logger.debug("init Mobile authentication Provider .");
return new MobileAuthenticationProvider( return new MobileAuthenticationProvider(
authenticationRealm, authenticationRealm,
applicationConfig, applicationConfig,
otpAuthnService, otpAuthnService,
onlineTicketServices sessionService
); );
} }
@ -118,13 +118,13 @@ public class AuthenticationAutoConfiguration implements InitializingBean {
public AbstractAuthenticationProvider trustedAuthenticationProvider( public AbstractAuthenticationProvider trustedAuthenticationProvider(
AbstractAuthenticationRealm authenticationRealm, AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig, ApplicationConfig applicationConfig,
OnlineTicketService onlineTicketServices SessionService sessionService
) { ) {
_logger.debug("init Mobile authentication Provider ."); _logger.debug("init Mobile authentication Provider .");
return new TrustedAuthenticationProvider( return new TrustedAuthenticationProvider(
authenticationRealm, authenticationRealm,
applicationConfig, applicationConfig,
onlineTicketServices sessionService
); );
} }
@ -181,18 +181,18 @@ public class AuthenticationAutoConfiguration implements InitializingBean {
} }
@Bean(name = "onlineTicketService") @Bean(name = "sessionService")
public OnlineTicketService onlineTicketService( public SessionService sessionService(
@Value("${maxkey.server.persistence}") int persistence, @Value("${maxkey.server.persistence}") int persistence,
JdbcTemplate jdbcTemplate, JdbcTemplate jdbcTemplate,
RedisConnectionFactory redisConnFactory, RedisConnectionFactory redisConnFactory,
@Value("${server.servlet.session.timeout:1800}") int timeout @Value("${server.servlet.session.timeout:1800}") int timeout
) { ) {
OnlineTicketService onlineTicketService = SessionService sessionService =
new OnlineTicketServiceFactory().getService(persistence, jdbcTemplate, redisConnFactory); new SessionServiceFactory().getService(persistence, jdbcTemplate, redisConnFactory);
onlineTicketService.setValiditySeconds(timeout); sessionService.setValiditySeconds(timeout);
_logger.trace("onlineTicket timeout " + timeout); _logger.trace("onlineTicket timeout " + timeout);
return onlineTicketService; return sessionService;
} }
@Bean(name = "sessionListenerAdapter") @Bean(name = "sessionListenerAdapter")

View File

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

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().getFormattedTicketId()); logoutParameters.put("ticket", ((SigninPrincipal)authentication.getPrincipal()).getSession().getFormattedId());
postMessage(logoutApp.getLogoutUrl(),logoutParameters); postMessage(logoutApp.getLogoutUrl(),logoutParameters);
} }

View File

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

View File

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

View File

@ -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,principal.getOnlineTicket().getFormattedTicketId()); serviceResponseBuilder.setAttribute(WebConstants.ONLINE_TICKET_NAME,principal.getSession().getFormattedId());
return serviceResponseBuilder; return serviceResponseBuilder;
} }

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, principal.getOnlineTicket().getFormattedTicketId()) .claim(WebConstants.ONLINE_TICKET_NAME, principal.getSession().getFormattedId())
.claim("kid", jwtDetails.getId()+ "_sig") .claim("kid", jwtDetails.getId()+ "_sig")
.claim("institution", userInfo.getInstId()) .claim("institution", userInfo.getInstId())
.build(); .build();

View File

@ -16,7 +16,7 @@ import java.util.ArrayList;
import org.maxkey.authn.AbstractAuthenticationProvider; import org.maxkey.authn.AbstractAuthenticationProvider;
import org.maxkey.authn.SigninPrincipal; 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.entity.UserInfo;
import org.maxkey.persistence.repository.LoginRepository; import org.maxkey.persistence.repository.LoginRepository;
import org.maxkey.web.WebConstants; 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(); String onlineTickitId = WebConstants.ONLINE_TICKET_PREFIX + "-" + java.util.UUID.randomUUID().toString().toLowerCase();
SigninPrincipal principal = new SigninPrincipal(userInfo); SigninPrincipal principal = new SigninPrincipal(userInfo);
OnlineTicket onlineTicket = new OnlineTicket(onlineTickitId); Session onlineTicket = new Session(onlineTickitId);
//set OnlineTicket //set OnlineTicket
principal.setOnlineTicket(onlineTicket); principal.setSession(onlineTicket);
ArrayList<GrantedAuthority> grantedAuthoritys = loginRepository.grantAuthority(userInfo); ArrayList<GrantedAuthority> grantedAuthoritys = loginRepository.grantAuthority(userInfo);
principal.setAuthenticated(true); principal.setAuthenticated(true);

View File

@ -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, principal.getOnlineTicket().getFormattedTicketId()); beanMap.put(WebConstants.ONLINE_TICKET_NAME, principal.getSession().getFormattedId());
String info= JsonUtils.object2Json(beanMap); String info= JsonUtils.object2Json(beanMap);

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().getFormattedTicketId()); jwtClaimsSetBuilder.claim(WebConstants.ONLINE_TICKET_NAME, authentication.getSession().getFormattedId());
if(scopes.contains("profile")){ if(scopes.contains("profile")){
jwtClaimsSetBuilder.claim("userId", userInfo.getId()); jwtClaimsSetBuilder.claim("userId", userInfo.getId());

View File

@ -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().getFormattedTicketId()); AuthorizationUtils.getPrincipal().getSession().getFormattedId());
//saml20Details //saml20Details
Response authResponse = authnResponseGenerator.generateAuthnResponse( Response authResponse = authnResponseGenerator.generateAuthnResponse(

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, principal.getOnlineTicket().getFormattedTicketId()); beanMap.put(WebConstants.ONLINE_TICKET_NAME, principal.getSession().getFormattedId());
/* /*
* use UTC date time format * use UTC date time format

View File

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

View File

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

View File

@ -84,7 +84,7 @@ public class HistorySignOnAppInterceptor implements AsyncHandlerInterceptor {
SigninPrincipal principal = AuthorizationUtils.getPrincipal(); SigninPrincipal principal = AuthorizationUtils.getPrincipal();
if(principal != null && app !=null) { if(principal != null && app !=null) {
final UserInfo userInfo = principal.getUserInfo(); final UserInfo userInfo = principal.getUserInfo();
String sessionId = principal.getOnlineTicket().getTicketId(); String sessionId = principal.getSession().getId();
_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

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

View File

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

View File

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

View File

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

View File

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