authentication jwt RemeberMe

This commit is contained in:
MaxKey
2021-02-17 13:06:30 +08:00
parent aad4e7e878
commit 5ccb71e64d
13 changed files with 388 additions and 233 deletions

View File

@@ -32,8 +32,6 @@ import org.maxkey.web.WebConstants;
import org.maxkey.web.WebContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.GrantedAuthority;

View File

@@ -0,0 +1,125 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.authn.support.jwt;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.maxkey.authn.AbstractAuthenticationProvider;
import org.maxkey.configuration.ApplicationConfig;
import org.maxkey.constants.ConstantsLoginType;
import org.maxkey.web.WebConstants;
import org.maxkey.web.WebContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import com.nimbusds.jwt.SignedJWT;
public class HttpJwtEntryPoint implements AsyncHandlerInterceptor {
private static final Logger _logger = LoggerFactory.getLogger(HttpJwtEntryPoint.class);
boolean enable;
ApplicationConfig applicationConfig;
AbstractAuthenticationProvider authenticationProvider ;
JwtLoginService jwtLoginService;
@Override
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
boolean isAuthenticated= WebContext.isAuthenticated();
String jwt = request.getParameter(WebConstants.JWT_TOKEN_PARAMETER);
if(!enable || isAuthenticated || jwt == null){
return true;
}
_logger.debug("JWT Login Start ...");
_logger.info("Request url : "+ request.getRequestURL());
_logger.info("Request URI : "+ request.getRequestURI());
_logger.info("Request ContextPath : "+ request.getContextPath());
_logger.info("Request ServletPath : "+ request.getServletPath());
_logger.debug("RequestSessionId : "+ request.getRequestedSessionId());
_logger.debug("isRequestedSessionIdValid : "+ request.isRequestedSessionIdValid());
_logger.debug("getSession : "+ request.getSession(false));
// session not existssession timeoutrecreate new session
if(request.getSession(false) == null) {
_logger.info("recreate new session .");
request.getSession(true);
}
_logger.info("getSession.getId : "+ request.getSession().getId());
//for jwt Login
if(!isAuthenticated){
_logger.debug("jwt : " + jwt);
SignedJWT signedJWT = jwtLoginService.jwtTokenValidation(jwt);
if(signedJWT != null) {
String username =signedJWT.getJWTClaimsSet().getSubject();
authenticationProvider.trustAuthentication(username, ConstantsLoginType.JWT, "", "", "success");
}
}
return true;
}
public HttpJwtEntryPoint() {
super();
}
public HttpJwtEntryPoint (boolean enable) {
super();
this.enable = enable;
}
public HttpJwtEntryPoint(AbstractAuthenticationProvider authenticationProvider, JwtLoginService jwtLoginService,
ApplicationConfig applicationConfig, boolean enable) {
super();
this.authenticationProvider = authenticationProvider;
this.jwtLoginService = jwtLoginService;
this.applicationConfig = applicationConfig;
this.enable = enable;
}
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public void setApplicationConfig(ApplicationConfig applicationConfig) {
this.applicationConfig = applicationConfig;
}
public void setAuthenticationProvider(AbstractAuthenticationProvider authenticationProvider) {
this.authenticationProvider = authenticationProvider;
}
public void setJwtLoginService(JwtLoginService jwtLoginService) {
this.jwtLoginService = jwtLoginService;
}
}

View File

@@ -28,11 +28,8 @@ import com.nimbusds.jwt.PlainJWT;
import com.nimbusds.jwt.SignedJWT;
import java.util.Date;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;
import org.joda.time.DateTime;
import org.maxkey.authn.AbstractAuthenticationProvider;
import org.maxkey.configuration.oidc.OIDCProviderMetadataDetails;
import org.maxkey.constants.ConstantsLoginType;
import org.maxkey.crypto.jwt.signer.service.impl.DefaultJwtSigningAndValidationService;
import org.maxkey.web.WebContext;
import org.slf4j.Logger;
@@ -47,77 +44,14 @@ public class JwtLoginService {
DefaultJwtSigningAndValidationService jwtSignerValidationService;
AbstractAuthenticationProvider authenticationProvider ;
public JwtLoginService(AbstractAuthenticationProvider authenticationProvider,
public JwtLoginService(
OIDCProviderMetadataDetails jwtProviderMetadata,
DefaultJwtSigningAndValidationService jwtSignerValidationService
) {
this.authenticationProvider = authenticationProvider;
this.jwtProviderMetadata = jwtProviderMetadata;
this.jwtSignerValidationService = jwtSignerValidationService;
}
public boolean login(String jwt, HttpServletResponse response) {
_logger.debug("jwt : " + jwt);
String username = null;
SignedJWT signedJWT = null;
boolean loginResult = false;
JWTClaimsSet jwtClaimsSet = null;
try {
RSASSAVerifier rsaSSAVerifier = new RSASSAVerifier(((RSAKey) jwtSignerValidationService.getAllPublicKeys()
.get(jwtSignerValidationService.getDefaultSignerKeyId())).toRSAPublicKey());
signedJWT = SignedJWT.parse(jwt);
if (signedJWT.verify(rsaSSAVerifier)) {
loginResult = true;
} else {
_logger.debug("verify false ");
return false;
}
jwtClaimsSet = signedJWT.getJWTClaimsSet();
_logger.debug("" + signedJWT.getPayload());
_logger.debug("jwtClaimsSet Issuer " + jwtClaimsSet.getIssuer());
_logger.debug("Metadata Issuer " + jwtProviderMetadata.getIssuer());
if (loginResult && jwtClaimsSet.getIssuer().equals(jwtProviderMetadata.getIssuer())) {
loginResult = true;
_logger.debug("Issuer equals ");
} else {
_logger.debug("Issuer not equals ");
return false;
}
_logger.debug("username " + jwtClaimsSet.getSubject());
if (loginResult && jwtClaimsSet.getSubject() != null) {
username = jwtClaimsSet.getSubject();
} else {
return false;
}
DateTime now = new DateTime();
if (loginResult && now.isBefore(jwtClaimsSet.getExpirationTime().getTime())) {
authenticationProvider.trustAuthentication(username, ConstantsLoginType.JWT, "", "", "success");
return true;
}
} catch (java.text.ParseException e) {
// Invalid signed JWT encoding
_logger.error("Invalid signed JWT encoding ");
} catch (JOSEException e) {
// TODO Auto-generated catch block
e.printStackTrace();
_logger.error("JOSEException ");
}
return false;
}
public String buildLoginJwt() {
_logger.debug("buildLoginJwt .");
@@ -144,10 +78,8 @@ public class JwtLoginService {
return tokenString;
}
public boolean jwtTokenValidation(String jwt) {
public SignedJWT jwtTokenValidation(String jwt) {
SignedJWT signedJWT = null;
boolean loginResult = false;
JWTClaimsSet jwtClaimsSet = null;
try {
@@ -156,44 +88,34 @@ public class JwtLoginService {
signedJWT = SignedJWT.parse(jwt);
if (signedJWT.verify(rsaSSAVerifier)) {
loginResult = true;
jwtClaimsSet = signedJWT.getJWTClaimsSet();
_logger.debug("" + signedJWT.getPayload());
_logger.debug("username " + jwtClaimsSet.getSubject());
_logger.debug("jwtClaimsSet Issuer " + jwtClaimsSet.getIssuer());
_logger.debug("Metadata Issuer " + jwtProviderMetadata.getIssuer());
if ( jwtClaimsSet.getIssuer().equals(jwtProviderMetadata.getIssuer())) {
_logger.debug("Issuer equals ");
DateTime now = new DateTime();
if (now.isBefore(jwtClaimsSet.getExpirationTime().getTime())) {
_logger.debug("ExpirationTime Validation " + now.isBefore(jwtClaimsSet.getExpirationTime().getTime()));
return signedJWT;
}
} else {
_logger.debug("Issuer not equals ");
}
} else {
_logger.debug("verify false ");
}
jwtClaimsSet = signedJWT.getJWTClaimsSet();
_logger.debug("" + signedJWT.getPayload());
_logger.debug("username " + jwtClaimsSet.getSubject());
_logger.debug("jwtClaimsSet Issuer " + jwtClaimsSet.getIssuer());
_logger.debug("Metadata Issuer " + jwtProviderMetadata.getIssuer());
if (loginResult && jwtClaimsSet.getIssuer().equals(jwtProviderMetadata.getIssuer())) {
loginResult = true;
_logger.debug("Issuer equals ");
} else {
_logger.debug("Issuer not equals ");
return false;
}
DateTime now = new DateTime();
if (loginResult && now.isBefore(jwtClaimsSet.getExpirationTime().getTime())) {
_logger.debug("ExpirationTime Validation " + now.isBefore(jwtClaimsSet.getExpirationTime().getTime()));
loginResult = true;
} else {
return false;
}
} catch (java.text.ParseException e) {
// Invalid signed JWT encoding
_logger.debug("Invalid signed JWT encoding ");
_logger.error("Invalid signed JWT encoding ",e);
} catch (JOSEException e) {
// TODO Auto-generated catch block
e.printStackTrace();
_logger.debug("JOSEException ");
_logger.error("JOSEException ",e);
}
return loginResult;
return null;
}
@@ -205,8 +127,13 @@ public class JwtLoginService {
this.jwtSignerValidationService = jwtSignerValidationService;
}
public void setAuthenticationProvider(AbstractAuthenticationProvider authenticationProvider) {
this.authenticationProvider = authenticationProvider;
}
public OIDCProviderMetadataDetails getJwtProviderMetadata() {
return jwtProviderMetadata;
}
public DefaultJwtSigningAndValidationService getJwtSignerValidationService() {
return jwtSignerValidationService;
}
}

View File

@@ -22,10 +22,7 @@ import java.util.regex.Pattern;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.joda.time.DateTime;
import org.maxkey.authn.AbstractAuthenticationProvider;
import org.maxkey.configuration.ApplicationConfig;
import org.maxkey.constants.ConstantsLoginType;
import org.maxkey.constants.ConstantsTimeInterval;
import org.maxkey.crypto.Base64Utils;
import org.maxkey.crypto.ReciprocalUtils;
@@ -47,10 +44,6 @@ public abstract class AbstractRemeberMeService {
@Autowired
@Qualifier("applicationConfig")
protected ApplicationConfig applicationConfig;
@Autowired
@Qualifier("authenticationProvider")
AbstractAuthenticationProvider authenticationProvider ;
// follow function is for persist
public abstract void save(RemeberMe remeberMe);
@@ -97,38 +90,6 @@ public abstract class AbstractRemeberMeService {
return true;
}
public boolean login(String remeberMe, HttpServletResponse response) {
_logger.debug("RemeberMe : " + remeberMe);
remeberMe = new String(Base64Utils.base64UrlDecode(remeberMe));
remeberMe = ReciprocalUtils.decoder(remeberMe);
_logger.debug("decoder RemeberMe : " + remeberMe);
RemeberMe remeberMeCookie = new RemeberMe();
remeberMeCookie = (RemeberMe) JsonUtils.json2Object(remeberMe, remeberMeCookie);
_logger.debug("Remeber Me Cookie : " + remeberMeCookie);
RemeberMe storeRemeberMe = read(remeberMeCookie);
if (storeRemeberMe == null) {
return false;
}
DateTime loginDate = new DateTime(storeRemeberMe.getLastLogin());
DateTime expiryDate = loginDate.plusSeconds(getRemeberMeValidity());
DateTime now = new DateTime();
if (now.isBefore(expiryDate)) {
authenticationProvider.trustAuthentication(
storeRemeberMe.getUsername(),
ConstantsLoginType.REMEBER_ME,
"",
"",
"success");
return updateRemeberMe(remeberMeCookie, response);
}
return false;
}
public boolean updateRemeberMe(RemeberMe remeberMe, HttpServletResponse response) {
remeberMe.setAuthKey(WebContext.genId());
remeberMe.setLastLogin(new Date());

View File

@@ -0,0 +1,150 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.authn.support.rememberme;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.joda.time.DateTime;
import org.maxkey.authn.AbstractAuthenticationProvider;
import org.maxkey.configuration.ApplicationConfig;
import org.maxkey.constants.ConstantsLoginType;
import org.maxkey.crypto.Base64Utils;
import org.maxkey.crypto.ReciprocalUtils;
import org.maxkey.util.JsonUtils;
import org.maxkey.web.WebConstants;
import org.maxkey.web.WebContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
public class HttpRemeberMeEntryPoint implements AsyncHandlerInterceptor {
private static final Logger _logger = LoggerFactory.getLogger(HttpRemeberMeEntryPoint.class);
boolean enable;
ApplicationConfig applicationConfig;
AbstractAuthenticationProvider authenticationProvider ;
AbstractRemeberMeService remeberMeService;
@Override
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
boolean isAuthenticated= WebContext.isAuthenticated();
Cookie readRemeberMeCookie = WebContext.readCookieByName(request,WebConstants.REMEBER_ME_COOKIE);
if(!enable || isAuthenticated){
return true;
}
_logger.debug("RemeberMe Login Start ...");
_logger.info("Request url : "+ request.getRequestURL());
_logger.info("Request URI : "+ request.getRequestURI());
_logger.info("Request ContextPath : "+ request.getContextPath());
_logger.info("Request ServletPath : "+ request.getServletPath());
_logger.debug("RequestSessionId : "+ request.getRequestedSessionId());
_logger.debug("isRequestedSessionIdValid : "+ request.isRequestedSessionIdValid());
_logger.debug("getSession : "+ request.getSession(false));
// session not existssession timeoutrecreate new session
if(request.getSession(false) == null) {
_logger.info("recreate new session .");
request.getSession(true);
}
_logger.info("getSession.getId : "+ request.getSession().getId());
if(applicationConfig.getLoginConfig().isRemeberMe()&&readRemeberMeCookie!=null){
_logger.debug("Try RemeberMe login ");
String remeberMe = readRemeberMeCookie.getValue();
_logger.debug("RemeberMe : " + remeberMe);
remeberMe = new String(Base64Utils.base64UrlDecode(remeberMe));
remeberMe = ReciprocalUtils.decoder(remeberMe);
_logger.debug("decoder RemeberMe : " + remeberMe);
RemeberMe remeberMeCookie = new RemeberMe();
remeberMeCookie = (RemeberMe) JsonUtils.json2Object(remeberMe, remeberMeCookie);
_logger.debug("Remeber Me Cookie : " + remeberMeCookie);
RemeberMe storeRemeberMe = remeberMeService.read(remeberMeCookie);
if (storeRemeberMe != null) {
DateTime loginDate = new DateTime(storeRemeberMe.getLastLogin());
DateTime expiryDate = loginDate.plusSeconds(remeberMeService.getRemeberMeValidity());
DateTime now = new DateTime();
if (now.isBefore(expiryDate)) {
authenticationProvider.trustAuthentication(
storeRemeberMe.getUsername(),
ConstantsLoginType.REMEBER_ME,
"",
"",
"success");
remeberMeService.updateRemeberMe(remeberMeCookie, response);
}
}
}
return true;
}
public HttpRemeberMeEntryPoint() {
super();
}
public HttpRemeberMeEntryPoint (boolean enable) {
super();
this.enable = enable;
}
public HttpRemeberMeEntryPoint(
AbstractAuthenticationProvider authenticationProvider, AbstractRemeberMeService remeberMeService,
ApplicationConfig applicationConfig,boolean enable) {
super();
this.enable = enable;
this.applicationConfig = applicationConfig;
this.authenticationProvider = authenticationProvider;
this.remeberMeService = remeberMeService;
}
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public void setApplicationConfig(ApplicationConfig applicationConfig) {
this.applicationConfig = applicationConfig;
}
public void setAuthenticationProvider(AbstractAuthenticationProvider authenticationProvider) {
this.authenticationProvider = authenticationProvider;
}
public void setRemeberMeService(AbstractRemeberMeService remeberMeService) {
this.remeberMeService = remeberMeService;
}
}

View File

@@ -23,7 +23,6 @@ import java.net.URI;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import org.maxkey.authn.AbstractAuthenticationProvider;
import org.maxkey.authn.support.jwt.JwtLoginService;
import org.maxkey.configuration.oidc.OIDCProviderMetadataDetails;
import org.maxkey.constants.ConstantsProperties;
@@ -126,11 +125,9 @@ public class JwtAuthnAutoConfiguration implements InitializingBean {
@Bean(name = "jwtLoginService")
public JwtLoginService jwtLoginService(
DefaultJwtSigningAndValidationService jwtSignerValidationService,
OIDCProviderMetadataDetails oidcProviderMetadata,
AbstractAuthenticationProvider authenticationProvider) {
OIDCProviderMetadataDetails oidcProviderMetadata) {
JwtLoginService jwtLoginService = new JwtLoginService(
authenticationProvider,
oidcProviderMetadata,
jwtSignerValidationService
);