This commit is contained in:
MaxKey
2022-04-20 17:06:18 +08:00
parent d9af91de4a
commit 586e473e48
16 changed files with 356 additions and 464 deletions

View File

@@ -35,7 +35,6 @@ import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
/**
@@ -71,59 +70,15 @@ public abstract class AbstractAuthenticationProvider {
protected abstract String getProviderName();
protected abstract Authentication doInternalAuthenticate(LoginCredential authentication);
public abstract Authentication authenticate(LoginCredential authentication);
public abstract Authentication authentication(LoginCredential loginCredential,boolean isTrusted);
public abstract Authentication authentication(LoginCredential loginCredential,boolean isTrusted);
@SuppressWarnings("rawtypes")
public boolean supports(Class authentication) {
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
}
/**
* authenticate .
*
*/
public Authentication authenticate(LoginCredential loginCredential)
throws AuthenticationException {
_logger.debug("Trying to authenticate user '{}' via {}",
loginCredential.getPrincipal(), getProviderName());
// 登录SESSION
_logger.debug("Login Session {}.", WebContext.getSession().getId());
Authentication authentication = null;
try {
authentication = doInternalAuthenticate(loginCredential);
} catch (AuthenticationException e) {
_logger.error("Failed to authenticate user {} via {}: {}",
new Object[] { loginCredential.getPrincipal(),
getProviderName(),
e.getMessage() });
WebContext.setAttribute(
WebConstants.LOGIN_ERROR_SESSION_MESSAGE, e.getMessage());
} catch (Exception e) {
_logger.error("Login error Unexpected exception in {} authentication:\n{}" ,
getProviderName(), e.getMessage());
}
if (authentication== null || !authentication.isAuthenticated()) {
return authentication;
}
// user authenticated
_logger.debug("'{}' authenticated successfully by {}.",
authentication.getPrincipal(), getProviderName());
changeSession(authentication);
authenticationRealm.insertLoginHistory(((SigninPrincipal) authentication.getPrincipal()).getUserInfo(),
ConstsLoginType.LOCAL,
"",
"xe00000004",
WebConstants.LOGIN_RESULT.SUCCESS);
return authentication;
}
protected void changeSession(Authentication authentication) {
HashMap<String,Object> sessionAttributeMap = new HashMap<String,Object>();

View File

@@ -24,6 +24,7 @@ import org.maxkey.authn.online.OnlineTicketService;
import org.maxkey.authn.realm.AbstractAuthenticationRealm;
import org.maxkey.authn.web.AuthorizationUtils;
import org.maxkey.configuration.ApplicationConfig;
import org.maxkey.constants.ConstsLoginType;
import org.maxkey.entity.Institutions;
import org.maxkey.entity.UserInfo;
import org.maxkey.password.onetimepwd.AbstractOtpAuthn;
@@ -35,6 +36,7 @@ import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
@@ -71,47 +73,73 @@ public class RealmAuthenticationProvider extends AbstractAuthenticationProvider
this.onlineTicketServices = onlineTicketServices;
}
@Override
protected Authentication doInternalAuthenticate(LoginCredential loginCredential) {
_logger.debug("authentication " + loginCredential);
//sessionValid(loginCredential.getSessionId());
//jwtTokenValid(j_jwtToken);
authTypeValid(loginCredential.getAuthType());
Institutions inst = (Institutions)WebContext.getAttribute(WebConstants.CURRENT_INST);
if(inst.getCaptchaSupport().equalsIgnoreCase("YES")) {
captchaValid(loginCredential.getCaptcha(),loginCredential.getAuthType());
@Override
public Authentication authenticate(LoginCredential loginCredential) {
UsernamePasswordAuthenticationToken authenticationToken = null;
_logger.debug("Trying to authenticate user '{}' via {}",
loginCredential.getPrincipal(), getProviderName());
try {
_logger.debug("authentication " + loginCredential);
//sessionValid(loginCredential.getSessionId());
//jwtTokenValid(j_jwtToken);
authTypeValid(loginCredential.getAuthType());
Institutions inst = (Institutions)WebContext.getAttribute(WebConstants.CURRENT_INST);
if(inst.getCaptchaSupport().equalsIgnoreCase("YES")) {
captchaValid(loginCredential.getCaptcha(),loginCredential.getAuthType());
}
emptyPasswordValid(loginCredential.getPassword());
UserInfo userInfo = null;
emptyUsernameValid(loginCredential.getUsername());
userInfo = loadUserInfo(loginCredential.getUsername(),loginCredential.getPassword());
statusValid(loginCredential , userInfo);
//mfa
tftcaptchaValid(loginCredential.getOtpCaptcha(),loginCredential.getAuthType(),userInfo);
//Validate PasswordPolicy
authenticationRealm.getPasswordPolicyValidator().passwordPolicyValid(userInfo);
if(loginCredential.getAuthType().equalsIgnoreCase(AuthType.MOBILE)) {
mobilecaptchaValid(loginCredential.getPassword(),loginCredential.getAuthType(),userInfo);
}else {
//Match password
authenticationRealm.passwordMatches(userInfo, loginCredential.getPassword());
}
//apply PasswordSetType and resetBadPasswordCount
authenticationRealm.getPasswordPolicyValidator().applyPasswordPolicy(userInfo);
authenticationToken = createOnlineSession(loginCredential,userInfo);
// user authenticated
_logger.debug("'{}' authenticated successfully by {}.",
loginCredential.getPrincipal(), getProviderName());
changeSession(authenticationToken);
authenticationRealm.insertLoginHistory(userInfo,
ConstsLoginType.LOCAL,
"",
"xe00000004",
WebConstants.LOGIN_RESULT.SUCCESS);
} catch (AuthenticationException e) {
_logger.error("Failed to authenticate user {} via {}: {}",
new Object[] { loginCredential.getPrincipal(),
getProviderName(),
e.getMessage() });
WebContext.setAttribute(
WebConstants.LOGIN_ERROR_SESSION_MESSAGE, e.getMessage());
} catch (Exception e) {
_logger.error("Login error Unexpected exception in {} authentication:\n{}" ,
getProviderName(), e.getMessage());
}
emptyPasswordValid(loginCredential.getPassword());
UserInfo userInfo = null;
emptyUsernameValid(loginCredential.getUsername());
userInfo = loadUserInfo(loginCredential.getUsername(),loginCredential.getPassword());
statusValid(loginCredential , userInfo);
//mfa
tftcaptchaValid(loginCredential.getOtpCaptcha(),loginCredential.getAuthType(),userInfo);
//Validate PasswordPolicy
authenticationRealm.getPasswordPolicyValidator().passwordPolicyValid(userInfo);
if(loginCredential.getAuthType().equalsIgnoreCase(AuthType.MOBILE)) {
mobilecaptchaValid(loginCredential.getPassword(),loginCredential.getAuthType(),userInfo);
}else {
//Match password
authenticationRealm.passwordMatches(userInfo, loginCredential.getPassword());
}
//apply PasswordSetType and resetBadPasswordCount
authenticationRealm.getPasswordPolicyValidator().applyPasswordPolicy(userInfo);
UsernamePasswordAuthenticationToken authenticationToken = createOnlineSession(loginCredential,userInfo);
return authenticationToken;
}

View File

@@ -58,12 +58,22 @@ public class AuthJwtService {
this.hmac512Service = new HMAC512Service(authJwkConfig.getSecret());
}
public AuthJwt generateAuthJwt(Authentication authentication) {
return new AuthJwt(generateToken(authentication), authentication);
/**
* create AuthJwt use Authentication JWT
* @param authentication
* @return AuthJwt
*/
public AuthJwt genAuthJwt(Authentication authentication) {
return new AuthJwt(genJwt(authentication), authentication);
}
public String generateToken(Authentication authentication) {
String token = "";
/**
* JWT with Authentication
* @param authentication
* @return
*/
public String genJwt(Authentication authentication) {
SigninPrincipal principal = ((SigninPrincipal)authentication.getPrincipal());
UserInfo userInfo = principal.getUserInfo();
DateTime currentDateTime = DateTime.now();
@@ -75,7 +85,7 @@ public class AuthJwtService {
JWTClaimsSet jwtClaims =new JWTClaimsSet.Builder()
.issuer(authJwkConfig.getIssuer())
.subject(subject)
.jwtID(principal.getOnlineTicket().getFormattedTicketId())
.jwtID(principal.getOnlineTicket().getTicketId())
.issueTime(currentDateTime.toDate())
.expirationTime(expirationTime)
.claim("locale", userInfo.getLocale())
@@ -83,15 +93,54 @@ public class AuthJwtService {
.claim("institution", userInfo.getInstId())
.build();
return signedJWT(jwtClaims);
}
/**
* JWT with subject
* @param subject subject
* @return
*/
public String genJwt(String subject) {
DateTime currentDateTime = DateTime.now();
Date expirationTime = currentDateTime.plusSeconds(authJwkConfig.getExpires()).toDate();
_logger.debug("expiration Time : {}" , expirationTime);
_logger.trace("jwt subject : {}" , subject);
JWTClaimsSet jwtClaims =new JWTClaimsSet.Builder()
.issuer(authJwkConfig.getIssuer())
.subject(subject)
.jwtID(WebContext.genId())
.issueTime(currentDateTime.toDate())
.expirationTime(expirationTime)
.build();
return signedJWT(jwtClaims);
}
/**
* Random JWT
* @return
*/
public String genJwt() {
DateTime currentDateTime = DateTime.now();
Date expirationTime = currentDateTime.plusSeconds(authJwkConfig.getExpires()).toDate();
_logger.debug("expiration Time : {}" , expirationTime);
JWTClaimsSet jwtClaims =new JWTClaimsSet.Builder()
.jwtID(WebContext.genId())
.expirationTime(expirationTime)
.build();
return signedJWT(jwtClaims);
}
public String signedJWT(JWTClaimsSet jwtClaims) {
_logger.trace("jwt Claims : {}" , jwtClaims);
SignedJWT jwtToken = new SignedJWT(
new JWSHeader(JWSAlgorithm.HS512),
jwtClaims);
token = hmac512Service.sign(jwtToken.getPayload());
return token ;
new JWSHeader(JWSAlgorithm.HS512),
jwtClaims);
return hmac512Service.sign(jwtToken.getPayload());
}
public boolean validateJwtToken(String authToken) {
@@ -114,7 +163,7 @@ public class AuthJwtService {
congressService.store(
congress,
new AuthJwt(
generateToken(authentication),
genJwt(authentication),
authentication)
);
return congress;