mirror of
https://gitee.com/dromara/MaxKey.git
synced 2026-05-14 20:50:14 +08:00
AuthorizationUtils
This commit is contained in:
@@ -22,7 +22,6 @@ import java.util.HashMap;
|
||||
|
||||
import org.maxkey.authn.online.OnlineTicketService;
|
||||
import org.maxkey.authn.realm.AbstractAuthenticationRealm;
|
||||
import org.maxkey.authn.support.rememberme.AbstractRemeberMeService;
|
||||
import org.maxkey.configuration.ApplicationConfig;
|
||||
import org.maxkey.constants.ConstsLoginType;
|
||||
import org.maxkey.constants.ConstsStatus;
|
||||
@@ -62,8 +61,6 @@ public abstract class AbstractAuthenticationProvider {
|
||||
|
||||
protected OtpAuthnService otpAuthnService;
|
||||
|
||||
protected AbstractRemeberMeService remeberMeService;
|
||||
|
||||
protected OnlineTicketService onlineTicketServices;
|
||||
|
||||
public static ArrayList<GrantedAuthority> grantedAdministratorsAuthoritys = new ArrayList<GrantedAuthority>();
|
||||
@@ -372,10 +369,6 @@ public abstract class AbstractAuthenticationProvider {
|
||||
this.tfaOtpAuthn = tfaOtpAuthn;
|
||||
}
|
||||
|
||||
public void setRemeberMeService(AbstractRemeberMeService remeberMeService) {
|
||||
this.remeberMeService = remeberMeService;
|
||||
}
|
||||
|
||||
public void setOnlineTicketServices(OnlineTicketService onlineTicketServices) {
|
||||
this.onlineTicketServices = onlineTicketServices;
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ import java.util.ArrayList;
|
||||
import org.maxkey.authn.online.OnlineTicket;
|
||||
import org.maxkey.authn.online.OnlineTicketService;
|
||||
import org.maxkey.authn.realm.AbstractAuthenticationRealm;
|
||||
import org.maxkey.authn.support.rememberme.AbstractRemeberMeService;
|
||||
import org.maxkey.authn.web.AuthorizationUtils;
|
||||
import org.maxkey.configuration.ApplicationConfig;
|
||||
import org.maxkey.entity.Institutions;
|
||||
import org.maxkey.entity.UserInfo;
|
||||
@@ -37,8 +37,6 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticatio
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.web.authentication.WebAuthenticationDetails;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
|
||||
|
||||
/**
|
||||
@@ -65,13 +63,11 @@ public class RealmAuthenticationProvider extends AbstractAuthenticationProvider
|
||||
ApplicationConfig applicationConfig,
|
||||
AbstractOtpAuthn tfaOtpAuthn,
|
||||
OtpAuthnService otpAuthnService,
|
||||
AbstractRemeberMeService remeberMeService,
|
||||
OnlineTicketService onlineTicketServices) {
|
||||
this.authenticationRealm = authenticationRealm;
|
||||
this.applicationConfig = applicationConfig;
|
||||
this.tfaOtpAuthn = tfaOtpAuthn;
|
||||
this.otpAuthnService = otpAuthnService;
|
||||
this.remeberMeService = remeberMeService;
|
||||
this.onlineTicketServices = onlineTicketServices;
|
||||
}
|
||||
|
||||
@@ -115,20 +111,6 @@ public class RealmAuthenticationProvider extends AbstractAuthenticationProvider
|
||||
authenticationRealm.getPasswordPolicyValidator().applyPasswordPolicy(userInfo);
|
||||
|
||||
UsernamePasswordAuthenticationToken authenticationToken = createOnlineSession(loginCredential,userInfo);
|
||||
//RemeberMe Config check then set RemeberMe cookies
|
||||
if (applicationConfig.getLoginConfig().isRemeberMe()) {
|
||||
if (loginCredential.getRemeberMe() != null && loginCredential.getRemeberMe().equals("remeberMe")) {
|
||||
WebContext.getSession().setAttribute(
|
||||
WebConstants.REMEBER_ME_SESSION,loginCredential.getUsername());
|
||||
_logger.debug("do Remeber Me");
|
||||
remeberMeService.createRemeberMe(
|
||||
userInfo.getUsername(),
|
||||
WebContext.getRequest(),
|
||||
((ServletRequestAttributes)RequestContextHolder.getRequestAttributes())
|
||||
.getResponse()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return authenticationToken;
|
||||
}
|
||||
@@ -225,7 +207,7 @@ public class RealmAuthenticationProvider extends AbstractAuthenticationProvider
|
||||
/*
|
||||
* put Authentication to current session context
|
||||
*/
|
||||
WebContext.setAuthentication(authenticationToken);
|
||||
AuthorizationUtils.setAuthentication(authenticationToken);
|
||||
|
||||
return authenticationToken;
|
||||
}
|
||||
|
||||
@@ -22,13 +22,10 @@ import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.maxkey.authn.support.rememberme.AbstractRemeberMeService;
|
||||
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.security.core.Authentication;
|
||||
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
|
||||
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
|
||||
@@ -74,10 +71,6 @@ public class SavedRequestAwareAuthenticationSuccessHandler
|
||||
protected final Logger _logger = LoggerFactory.getLogger(
|
||||
SavedRequestAwareAuthenticationSuccessHandler.class);
|
||||
|
||||
@Autowired
|
||||
@Qualifier("remeberMeService")
|
||||
protected AbstractRemeberMeService remeberMeService;
|
||||
|
||||
private RequestCache requestCache = new HttpSessionRequestCache();
|
||||
|
||||
@Override
|
||||
@@ -85,9 +78,6 @@ public class SavedRequestAwareAuthenticationSuccessHandler
|
||||
Authentication authentication) throws ServletException, IOException {
|
||||
SavedRequest savedRequest = requestCache.getRequest(request, response);
|
||||
|
||||
remeberMeService.createRemeberMe(
|
||||
authentication.getPrincipal().toString(), request, response);
|
||||
|
||||
if (savedRequest == null) {
|
||||
super.onAuthenticationSuccess(request, response, authentication);
|
||||
|
||||
|
||||
@@ -8,16 +8,17 @@ import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
|
||||
public class AuthJwt {
|
||||
private String token;
|
||||
private String type = "Bearer";
|
||||
private String id;
|
||||
private String name;
|
||||
private String username;
|
||||
private String displayName;
|
||||
private String email;
|
||||
private String instId;
|
||||
private String instName;
|
||||
private List<String> authorities;
|
||||
private String ticket;
|
||||
private String token;
|
||||
private String type = "Bearer";
|
||||
private String id;
|
||||
private String name;
|
||||
private String username;
|
||||
private String displayName;
|
||||
private String email;
|
||||
private String instId;
|
||||
private String instName;
|
||||
private List<String> authorities;
|
||||
|
||||
|
||||
public AuthJwt(String token, String id, String username, String displayName, String email, String instId,
|
||||
@@ -37,6 +38,8 @@ public class AuthJwt {
|
||||
SigninPrincipal signinPrincipal = ((SigninPrincipal)authentication.getPrincipal());
|
||||
|
||||
this.token = token;
|
||||
this.ticket = signinPrincipal.getOnlineTicket().getTicketId().substring(3);
|
||||
|
||||
this.id = signinPrincipal.getUserInfo().getId();
|
||||
this.username = signinPrincipal.getUserInfo().getUsername();
|
||||
this.name = this.username;
|
||||
@@ -115,6 +118,15 @@ public class AuthJwt {
|
||||
public void setAuthorities(List<String> authorities) {
|
||||
this.authorities = authorities;
|
||||
}
|
||||
|
||||
public String getTicket() {
|
||||
return ticket;
|
||||
}
|
||||
|
||||
public void setTicket(String ticket) {
|
||||
this.ticket = ticket;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
|
||||
@@ -24,7 +24,6 @@ import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.maxkey.authn.SigninPrincipal;
|
||||
import org.maxkey.authn.realm.ldap.LdapAuthenticationRealmService;
|
||||
import org.maxkey.authn.support.rememberme.AbstractRemeberMeService;
|
||||
import org.maxkey.entity.Groups;
|
||||
import org.maxkey.entity.HistoryLogin;
|
||||
import org.maxkey.entity.UserInfo;
|
||||
@@ -57,8 +56,6 @@ public abstract class AbstractAuthenticationRealm {
|
||||
protected LoginRepository loginRepository;
|
||||
|
||||
protected LoginHistoryRepository loginHistoryRepository;
|
||||
|
||||
protected AbstractRemeberMeService remeberMeService;
|
||||
|
||||
protected UserInfoService userInfoService;
|
||||
|
||||
@@ -90,16 +87,6 @@ public abstract class AbstractAuthenticationRealm {
|
||||
|
||||
public abstract boolean passwordMatches(UserInfo userInfo, String password);
|
||||
|
||||
|
||||
public static boolean isAuthenticated() {
|
||||
if (WebContext.getUserInfo() != null) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public List<Groups> queryGroups(UserInfo userInfo) {
|
||||
return loginRepository.queryGroups(userInfo);
|
||||
}
|
||||
@@ -183,9 +170,7 @@ public abstract class AbstractAuthenticationRealm {
|
||||
SigninPrincipal signinPrincipal = ((SigninPrincipal) authentication.getPrincipal());
|
||||
UserInfo userInfo = signinPrincipal.getUserInfo();
|
||||
userInfo.setLastLogoffTime(DateUtils.formatDateTime(new Date()));
|
||||
|
||||
remeberMeService.removeRemeberMe(response);
|
||||
|
||||
|
||||
loginHistoryRepository.logoff(userInfo.getLastLogoffTime(), signinPrincipal.getOnlineTicket().getTicketId());
|
||||
|
||||
|
||||
|
||||
@@ -20,8 +20,8 @@ package org.maxkey.authn.realm.jdbc;
|
||||
import org.maxkey.authn.realm.AbstractAuthenticationRealm;
|
||||
import org.maxkey.authn.realm.ldap.LdapAuthenticationRealm;
|
||||
import org.maxkey.authn.realm.ldap.LdapAuthenticationRealmService;
|
||||
import org.maxkey.authn.support.rememberme.AbstractRemeberMeService;
|
||||
import org.maxkey.constants.ConstsLoginType;
|
||||
import org.maxkey.entity.ChangePassword;
|
||||
import org.maxkey.entity.PasswordPolicy;
|
||||
import org.maxkey.entity.UserInfo;
|
||||
import org.maxkey.persistence.repository.LoginHistoryRepository;
|
||||
@@ -59,7 +59,6 @@ public class JdbcAuthenticationRealm extends AbstractAuthenticationRealm {
|
||||
PasswordPolicyValidator passwordPolicyValidator,
|
||||
LoginRepository loginRepository,
|
||||
LoginHistoryRepository loginHistoryRepository,
|
||||
AbstractRemeberMeService remeberMeService,
|
||||
UserInfoService userInfoService,
|
||||
JdbcTemplate jdbcTemplate) {
|
||||
|
||||
@@ -67,7 +66,6 @@ public class JdbcAuthenticationRealm extends AbstractAuthenticationRealm {
|
||||
this.passwordPolicyValidator=passwordPolicyValidator;
|
||||
this.loginRepository = loginRepository;
|
||||
this.loginHistoryRepository = loginHistoryRepository;
|
||||
this.remeberMeService = remeberMeService;
|
||||
this.userInfoService = userInfoService;
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
}
|
||||
@@ -77,7 +75,6 @@ public class JdbcAuthenticationRealm extends AbstractAuthenticationRealm {
|
||||
PasswordPolicyValidator passwordPolicyValidator,
|
||||
LoginRepository loginRepository,
|
||||
LoginHistoryRepository loginHistoryRepository,
|
||||
AbstractRemeberMeService remeberMeService,
|
||||
UserInfoService userInfoService,
|
||||
JdbcTemplate jdbcTemplate,
|
||||
LdapAuthenticationRealmService ldapAuthenticationRealmService) {
|
||||
@@ -85,7 +82,6 @@ public class JdbcAuthenticationRealm extends AbstractAuthenticationRealm {
|
||||
this.passwordPolicyValidator = passwordPolicyValidator;
|
||||
this.loginRepository = loginRepository;
|
||||
this.loginHistoryRepository = loginHistoryRepository;
|
||||
this.remeberMeService = remeberMeService;
|
||||
this.userInfoService = userInfoService;
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
this.ldapAuthenticationRealmService = ldapAuthenticationRealmService;
|
||||
@@ -109,11 +105,9 @@ public class JdbcAuthenticationRealm extends AbstractAuthenticationRealm {
|
||||
passwordMatches = ldapRealm.passwordMatches(userInfo, password);
|
||||
if(passwordMatches) {
|
||||
//write password to database Realm
|
||||
UserInfo changePasswordUser = new UserInfo();
|
||||
changePasswordUser.setId(userInfo.getId());
|
||||
changePasswordUser.setUsername(userInfo.getUsername());
|
||||
changePasswordUser.setPassword(password);
|
||||
userInfoService.changePassword(changePasswordUser, false);
|
||||
ChangePassword changePassword = new ChangePassword(userInfo);
|
||||
changePassword.setPassword(password);
|
||||
userInfoService.changePassword(changePassword, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,10 +22,10 @@ import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.maxkey.authn.AbstractAuthenticationProvider;
|
||||
import org.maxkey.authn.LoginCredential;
|
||||
import org.maxkey.authn.web.AuthorizationUtils;
|
||||
import org.maxkey.configuration.ApplicationConfig;
|
||||
import org.maxkey.constants.ConstsLoginType;
|
||||
import org.maxkey.web.WebConstants;
|
||||
import org.maxkey.web.WebContext;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.web.servlet.AsyncHandlerInterceptor;
|
||||
@@ -46,7 +46,7 @@ public class HttpJwtEntryPoint implements AsyncHandlerInterceptor {
|
||||
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
|
||||
boolean isAuthenticated= WebContext.isAuthenticated();
|
||||
boolean isAuthenticated= AuthorizationUtils.isAuthenticated();
|
||||
String jwt = request.getParameter(WebConstants.JWT_TOKEN_PARAMETER);
|
||||
|
||||
if(!enable
|
||||
|
||||
@@ -22,13 +22,13 @@ import javax.servlet.http.HttpServletResponse;
|
||||
import org.joda.time.DateTime;
|
||||
import org.maxkey.authn.AbstractAuthenticationProvider;
|
||||
import org.maxkey.authn.LoginCredential;
|
||||
import org.maxkey.authn.web.AuthorizationUtils;
|
||||
import org.maxkey.configuration.ApplicationConfig;
|
||||
import org.maxkey.constants.ConstsLoginType;
|
||||
import org.maxkey.crypto.ReciprocalUtils;
|
||||
import org.maxkey.util.DateUtils;
|
||||
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;
|
||||
@@ -47,7 +47,7 @@ public class HttpKerberosEntryPoint implements AsyncHandlerInterceptor {
|
||||
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
|
||||
boolean isAuthenticated= WebContext.isAuthenticated();
|
||||
boolean isAuthenticated= AuthorizationUtils.isAuthenticated();
|
||||
String kerberosTokenString = request.getParameter(WebConstants.KERBEROS_TOKEN_PARAMETER);
|
||||
String kerberosUserDomain = request.getParameter(WebConstants.KERBEROS_USERDOMAIN_PARAMETER);
|
||||
|
||||
|
||||
@@ -1,166 +0,0 @@
|
||||
/*
|
||||
* 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 java.util.Date;
|
||||
import java.util.regex.Pattern;
|
||||
import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import org.maxkey.configuration.ApplicationConfig;
|
||||
import org.maxkey.constants.ConstsTimeInterval;
|
||||
import org.maxkey.crypto.Base64Utils;
|
||||
import org.maxkey.crypto.password.PasswordReciprocal;
|
||||
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.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
|
||||
public abstract class AbstractRemeberMeService {
|
||||
private static final Logger _logger = LoggerFactory.getLogger(AbstractRemeberMeService.class);
|
||||
|
||||
protected Integer remeberMeValidity = ConstsTimeInterval.TWO_WEEK;
|
||||
|
||||
protected String validity;
|
||||
|
||||
@Autowired
|
||||
@Qualifier("applicationConfig")
|
||||
protected ApplicationConfig applicationConfig;
|
||||
|
||||
// follow function is for persist
|
||||
public abstract void save(RemeberMe remeberMe);
|
||||
|
||||
public abstract void update(RemeberMe remeberMe);
|
||||
|
||||
public abstract RemeberMe read(RemeberMe remeberMe);
|
||||
|
||||
public abstract void remove(String username);
|
||||
// end persist
|
||||
|
||||
public boolean createRemeberMe(String username, HttpServletRequest request, HttpServletResponse response) {
|
||||
if (request.getSession().getAttribute(WebConstants.REMEBER_ME_SESSION) != null
|
||||
&& applicationConfig.getLoginConfig().isRemeberMe()) {
|
||||
_logger.debug("Remeber Me ...");
|
||||
RemeberMe remeberMe = new RemeberMe();
|
||||
remeberMe.setAuthKey(WebContext.genId());
|
||||
remeberMe.setId(WebContext.genId());
|
||||
remeberMe.setUsername(WebContext.getUserInfo().getUsername());
|
||||
remeberMe.setLastLogin(new Date());
|
||||
save(remeberMe);
|
||||
_logger.debug("Remeber Me " + remeberMe);
|
||||
_logger.debug("Cookie Name : " + WebConstants.REMEBER_ME_COOKIE);
|
||||
|
||||
String jsonRemeberMe = JsonUtils.object2Json(remeberMe);
|
||||
_logger.debug("Remeber Me JSON " + jsonRemeberMe);
|
||||
|
||||
jsonRemeberMe = PasswordReciprocal.getInstance().encode(jsonRemeberMe);
|
||||
|
||||
String cookieValue = Base64Utils.base64UrlEncode(jsonRemeberMe.getBytes());
|
||||
|
||||
_logger.debug("Remeber Me JSON " + cookieValue);
|
||||
Cookie cookie = new Cookie(WebConstants.REMEBER_ME_COOKIE, cookieValue);
|
||||
|
||||
Integer maxAge = getRemeberMeValidity();
|
||||
_logger.debug("Cookie Max Age :" + maxAge + " seconds.");
|
||||
cookie.setMaxAge(maxAge);
|
||||
|
||||
// cookie.setPath("/");
|
||||
cookie.setDomain(applicationConfig.getDomainName());
|
||||
response.addCookie(cookie);
|
||||
request.getSession().removeAttribute(WebConstants.REMEBER_ME_SESSION);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean updateRemeberMe(RemeberMe remeberMe, HttpServletResponse response) {
|
||||
remeberMe.setAuthKey(WebContext.genId());
|
||||
remeberMe.setLastLogin(new Date());
|
||||
update(remeberMe);
|
||||
_logger.debug("update Remeber Me " + remeberMe);
|
||||
_logger.debug("Cookie Name : " + WebConstants.REMEBER_ME_COOKIE);
|
||||
|
||||
String jsonRemeberMe = JsonUtils.object2Json(remeberMe);
|
||||
_logger.debug("Remeber Me JSON " + jsonRemeberMe);
|
||||
|
||||
_logger.debug("Encode Remeber Me JSON ...");
|
||||
jsonRemeberMe = PasswordReciprocal.getInstance().encode(jsonRemeberMe);
|
||||
_logger.debug("Encode Remeber Me JSON " + jsonRemeberMe);
|
||||
|
||||
String cookieValue = Base64Utils.base64UrlEncode(jsonRemeberMe.getBytes());
|
||||
|
||||
Cookie cookie = new Cookie(WebConstants.REMEBER_ME_COOKIE, cookieValue);
|
||||
|
||||
Integer maxAge = getRemeberMeValidity();
|
||||
_logger.debug("Cookie Max Age :" + maxAge + " seconds.");
|
||||
cookie.setMaxAge(maxAge);
|
||||
|
||||
// cookie.setPath("/");
|
||||
cookie.setDomain(applicationConfig.getDomainName());
|
||||
response.addCookie(cookie);
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean removeRemeberMe(HttpServletResponse response) {
|
||||
Cookie cookie = new Cookie(WebConstants.REMEBER_ME_COOKIE, null);
|
||||
cookie.setMaxAge(0);
|
||||
|
||||
cookie.setDomain(applicationConfig.getDomainName());
|
||||
response.addCookie(cookie);
|
||||
|
||||
remove(WebContext.getUserInfo().getUsername());
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public Integer getRemeberMeValidity() {
|
||||
return remeberMeValidity;
|
||||
}
|
||||
|
||||
public void setRemeberMeValidity(Integer remeberMeValidity) {
|
||||
this.remeberMeValidity = remeberMeValidity;
|
||||
}
|
||||
|
||||
public String getValidity() {
|
||||
return validity;
|
||||
}
|
||||
|
||||
public void setApplicationConfig(ApplicationConfig applicationConfig) {
|
||||
this.applicationConfig = applicationConfig;
|
||||
}
|
||||
|
||||
public void setValidity(String validity) {
|
||||
_logger.debug("validity : " + validity);
|
||||
this.validity = validity;
|
||||
if (Pattern.matches("[0-9]+", validity)) {
|
||||
remeberMeValidity = Integer.parseInt(validity);
|
||||
} else if (validity.equalsIgnoreCase("ONE_DAY")) {
|
||||
remeberMeValidity = ConstsTimeInterval.ONE_DAY;
|
||||
} else if (validity.equalsIgnoreCase("ONE_WEEK")) {
|
||||
remeberMeValidity = ConstsTimeInterval.ONE_WEEK;
|
||||
} else if (validity.equalsIgnoreCase("TWO_WEEK")) {
|
||||
remeberMeValidity = ConstsTimeInterval.TWO_WEEK;
|
||||
} else if (validity.equalsIgnoreCase("ONE_YEAR")) {
|
||||
remeberMeValidity = ConstsTimeInterval.ONE_YEAR;
|
||||
}
|
||||
|
||||
_logger.debug("Remeber Me Validity : " + remeberMeValidity);
|
||||
}
|
||||
}
|
||||
@@ -1,149 +0,0 @@
|
||||
/*
|
||||
* 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.authn.LoginCredential;
|
||||
import org.maxkey.configuration.ApplicationConfig;
|
||||
import org.maxkey.constants.ConstsLoginType;
|
||||
import org.maxkey.crypto.Base64Utils;
|
||||
import org.maxkey.crypto.password.PasswordReciprocal;
|
||||
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
|
||||
|| readRemeberMeCookie==null
|
||||
|| !applicationConfig.getLoginConfig().isRemeberMe()){
|
||||
return true;
|
||||
}
|
||||
|
||||
_logger.trace("RemeberMe Login Start ...");
|
||||
_logger.trace("Request url : "+ request.getRequestURL());
|
||||
_logger.trace("Request URI : "+ request.getRequestURI());
|
||||
_logger.trace("Request ContextPath : "+ request.getContextPath());
|
||||
_logger.trace("Request ServletPath : "+ request.getServletPath());
|
||||
_logger.trace("RequestSessionId : "+ request.getRequestedSessionId());
|
||||
_logger.trace("isRequestedSessionIdValid : "+ request.isRequestedSessionIdValid());
|
||||
_logger.trace("getSession : "+ request.getSession(false));
|
||||
|
||||
// session not exists,session timeout,recreate new session
|
||||
if(request.getSession(false) == null) {
|
||||
_logger.info("recreate new session .");
|
||||
request.getSession(true);
|
||||
}
|
||||
|
||||
_logger.trace("getSession.getId : "+ request.getSession().getId());
|
||||
|
||||
_logger.debug("Try RemeberMe login ");
|
||||
String remeberMe = readRemeberMeCookie.getValue();
|
||||
_logger.debug("RemeberMe : " + remeberMe);
|
||||
|
||||
remeberMe = new String(Base64Utils.base64UrlDecode(remeberMe));
|
||||
|
||||
remeberMe = PasswordReciprocal.getInstance().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)) {
|
||||
LoginCredential loginCredential =
|
||||
new LoginCredential(storeRemeberMe.getUsername(),"",ConstsLoginType.REMEBER_ME);
|
||||
authenticationProvider.authentication(loginCredential,true);
|
||||
remeberMeService.updateRemeberMe(remeberMeCookie, response);
|
||||
_logger.debug("RemeberMe Logined in , username " + storeRemeberMe.getUsername());
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
/*
|
||||
* 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 java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.maxkey.constants.ConstsTimeInterval;
|
||||
|
||||
import com.github.benmanes.caffeine.cache.Cache;
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
|
||||
public class InMemoryRemeberMeService extends AbstractRemeberMeService {
|
||||
|
||||
protected static final Cache<String, RemeberMe> remeberMeStore =
|
||||
Caffeine.newBuilder()
|
||||
.expireAfterWrite(ConstsTimeInterval.TWO_WEEK, TimeUnit.SECONDS)
|
||||
.build();
|
||||
|
||||
@Override
|
||||
public void save(RemeberMe remeberMe) {
|
||||
remeberMeStore.put(remeberMe.getUsername(), remeberMe);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void update(RemeberMe remeberMe) {
|
||||
remeberMeStore.put(remeberMe.getUsername(), remeberMe);
|
||||
}
|
||||
|
||||
@Override
|
||||
public RemeberMe read(RemeberMe remeberMe) {
|
||||
return remeberMeStore.getIfPresent(remeberMe.getUsername());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove(String username) {
|
||||
remeberMeStore.invalidate(username);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
/*
|
||||
* 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 java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Types;
|
||||
import java.util.List;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.core.RowMapper;
|
||||
|
||||
public class JdbcRemeberMeService extends AbstractRemeberMeService {
|
||||
private static final Logger _logger = LoggerFactory.getLogger(JdbcRemeberMeService.class);
|
||||
|
||||
private static final String DEFAULT_DEFAULT_INSERT_STATEMENT =
|
||||
"INSERT INTO REMEMBER_ME(ID, USERNAME,AUTHKEY,LASTLOGIN)VALUES( ? , ? , ? , ?)";
|
||||
|
||||
private static final String DEFAULT_DEFAULT_SELECT_STATEMENT =
|
||||
"SELECT ID, USERNAME,AUTHKEY,LASTLOGIN FROM REMEMBER_ME "
|
||||
+ " WHERE ID = ? AND USERNAME = ? AND AUTHKEY = ?";
|
||||
|
||||
private static final String DEFAULT_DEFAULT_DELETE_STATEMENT =
|
||||
"DELETE FROM REMEMBER_ME WHERE USERNAME = ?";
|
||||
|
||||
private static final String DEFAULT_DEFAULT_UPDATE_STATEMENT =
|
||||
"UPDATE REMEMBER_ME SET AUTHKEY = ? , LASTLOGIN = ? WHERE ID = ?";
|
||||
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
|
||||
public JdbcRemeberMeService(JdbcTemplate jdbcTemplate) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(RemeberMe remeberMe) {
|
||||
jdbcTemplate.update(DEFAULT_DEFAULT_INSERT_STATEMENT,
|
||||
new Object[] { remeberMe.getId(), remeberMe.getUsername(), remeberMe.getAuthKey(),
|
||||
remeberMe.getLastLogin() },
|
||||
new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.TIMESTAMP });
|
||||
}
|
||||
|
||||
@Override
|
||||
public void update(RemeberMe remeberMe) {
|
||||
jdbcTemplate.update(DEFAULT_DEFAULT_UPDATE_STATEMENT,
|
||||
new Object[] {
|
||||
remeberMe.getAuthKey(),
|
||||
remeberMe.getLastLogin(),
|
||||
remeberMe.getId()
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public RemeberMe read(RemeberMe remeberMe) {
|
||||
List<RemeberMe> listRemeberMe = jdbcTemplate.query(DEFAULT_DEFAULT_SELECT_STATEMENT,
|
||||
new RowMapper<RemeberMe>() {
|
||||
public RemeberMe mapRow(ResultSet rs, int rowNum) throws SQLException {
|
||||
RemeberMe remeberMe = new RemeberMe();
|
||||
remeberMe.setId(rs.getString(1));
|
||||
remeberMe.setUsername(rs.getString(2));
|
||||
remeberMe.setAuthKey(rs.getString(3));
|
||||
remeberMe.setLastLogin(rs.getDate(4));
|
||||
return remeberMe;
|
||||
}
|
||||
}, remeberMe.getId(), remeberMe.getUsername(), remeberMe.getAuthKey());
|
||||
_logger.debug("listRemeberMe " + listRemeberMe);
|
||||
return (listRemeberMe.size() > 0) ? listRemeberMe.get(0) : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove(String username) {
|
||||
jdbcTemplate.update(DEFAULT_DEFAULT_DELETE_STATEMENT, username);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
/*
|
||||
* 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 org.maxkey.constants.ConstsTimeInterval;
|
||||
import org.maxkey.persistence.redis.RedisConnection;
|
||||
import org.maxkey.persistence.redis.RedisConnectionFactory;
|
||||
|
||||
public class RedisRemeberMeService extends AbstractRemeberMeService {
|
||||
|
||||
protected int serviceTicketValiditySeconds = ConstsTimeInterval.TWO_WEEK;
|
||||
|
||||
RedisConnectionFactory connectionFactory;
|
||||
|
||||
public static String PREFIX = "REDIS_REMEBER_ME_SERVICE_";
|
||||
|
||||
@Override
|
||||
public void save(RemeberMe remeberMe) {
|
||||
RedisConnection conn = connectionFactory.getConnection();
|
||||
conn.setexObject(PREFIX + remeberMe.getUsername(), serviceTicketValiditySeconds, remeberMe);
|
||||
conn.close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void update(RemeberMe remeberMe) {
|
||||
RedisConnection conn = connectionFactory.getConnection();
|
||||
conn.setexObject(PREFIX + remeberMe.getUsername(), serviceTicketValiditySeconds, remeberMe);
|
||||
conn.close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public RemeberMe read(RemeberMe remeberMe) {
|
||||
RedisConnection conn = connectionFactory.getConnection();
|
||||
RemeberMe readRemeberMe = (RemeberMe)conn.getObject(PREFIX + remeberMe.getUsername());
|
||||
conn.close();
|
||||
return readRemeberMe;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove(String username) {
|
||||
RedisConnection conn = connectionFactory.getConnection();
|
||||
conn.delete(PREFIX + username);
|
||||
conn.close();
|
||||
}
|
||||
|
||||
public RedisRemeberMeService(RedisConnectionFactory connectionFactory) {
|
||||
super();
|
||||
this.connectionFactory = connectionFactory;
|
||||
}
|
||||
|
||||
public void setConnectionFactory(RedisConnectionFactory connectionFactory) {
|
||||
this.connectionFactory = connectionFactory;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
/*
|
||||
* 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 java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
public class RemeberMe implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 8010496585233991785L;
|
||||
|
||||
String id;
|
||||
|
||||
String username;
|
||||
|
||||
String authKey;
|
||||
|
||||
Date lastLogin;
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getAuthKey() {
|
||||
return authKey;
|
||||
}
|
||||
|
||||
public void setAuthKey(String authKey) {
|
||||
this.authKey = authKey;
|
||||
}
|
||||
|
||||
public Date getLastLogin() {
|
||||
return lastLogin;
|
||||
}
|
||||
|
||||
public void setLastLogin(Date lastLogin) {
|
||||
this.lastLogin = lastLogin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "RemeberMe [id=" + id
|
||||
+ ", username=" + username
|
||||
+ ", authKey=" + authKey + ", lastLogin=" + lastLogin
|
||||
+ "]";
|
||||
}
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
/*
|
||||
* Copyright [2021] [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 org.maxkey.constants.ConstsPersistence;
|
||||
import org.maxkey.persistence.redis.RedisConnectionFactory;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
|
||||
public class RemeberMeServiceFactory {
|
||||
private static final Logger _logger =
|
||||
LoggerFactory.getLogger(RemeberMeServiceFactory.class);
|
||||
|
||||
public AbstractRemeberMeService getService(
|
||||
int persistence,
|
||||
JdbcTemplate jdbcTemplate,
|
||||
RedisConnectionFactory redisConnFactory){
|
||||
|
||||
AbstractRemeberMeService remeberMeService = null;
|
||||
if (persistence == ConstsPersistence.INMEMORY) {
|
||||
remeberMeService = new InMemoryRemeberMeService();
|
||||
_logger.debug("InMemoryRemeberMeService");
|
||||
} else if (persistence == ConstsPersistence.JDBC) {
|
||||
//remeberMeService = new JdbcRemeberMeService(jdbcTemplate);
|
||||
_logger.debug("JdbcRemeberMeService not support ");
|
||||
} else if (persistence == ConstsPersistence.REDIS) {
|
||||
remeberMeService = new RedisRemeberMeService(redisConnFactory);
|
||||
_logger.debug("RedisRemeberMeService");
|
||||
}
|
||||
return remeberMeService;
|
||||
}
|
||||
}
|
||||
@@ -21,10 +21,10 @@ import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import org.maxkey.authn.AbstractAuthenticationProvider;
|
||||
import org.maxkey.authn.LoginCredential;
|
||||
import org.maxkey.authn.web.AuthorizationUtils;
|
||||
import org.maxkey.configuration.ApplicationConfig;
|
||||
import org.maxkey.constants.ConstsLoginType;
|
||||
import org.maxkey.util.StringUtils;
|
||||
import org.maxkey.web.WebContext;
|
||||
import org.opensaml.saml1.core.impl.AssertionImpl;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -44,7 +44,7 @@ public class HttpWsFederationEntryPoint implements AsyncHandlerInterceptor {
|
||||
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
|
||||
boolean isAuthenticated= WebContext.isAuthenticated();
|
||||
boolean isAuthenticated= AuthorizationUtils.isAuthenticated();
|
||||
String wsFederationWA = request.getParameter(WsFederationConstants.WA);
|
||||
String wsFederationWResult = request.getParameter(WsFederationConstants.WRESULT);
|
||||
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
package org.maxkey.authn.web;
|
||||
|
||||
import java.text.ParseException;
|
||||
|
||||
import javax.servlet.http.Cookie;
|
||||
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.entity.UserInfo;
|
||||
import org.maxkey.util.AuthorizationHeaderUtils;
|
||||
import org.maxkey.web.WebConstants;
|
||||
import org.maxkey.web.WebContext;
|
||||
import org.springframework.security.core.Authentication;
|
||||
|
||||
public class AuthorizationUtils {
|
||||
|
||||
static final String Authorization = "Authorization";
|
||||
|
||||
public static void authenticateWithCookie(
|
||||
HttpServletRequest request,
|
||||
AuthJwtService authJwtService,
|
||||
OnlineTicketService onlineTicketService
|
||||
) throws ParseException{
|
||||
if(getAuthentication() == null) {
|
||||
Cookie authCookie = WebContext.getCookie(request, Authorization);
|
||||
if(authCookie != null ) {
|
||||
String authorization = authCookie.getValue();
|
||||
doAuthenticate(authorization,authJwtService,onlineTicketService);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void authenticate(
|
||||
HttpServletRequest request,
|
||||
AuthJwtService authJwtService,
|
||||
OnlineTicketService onlineTicketService
|
||||
) throws ParseException{
|
||||
if(getAuthentication() == null) {
|
||||
String authorization = AuthorizationHeaderUtils.resolveBearer(request);
|
||||
if(authorization != null ) {
|
||||
doAuthenticate(authorization,authJwtService,onlineTicketService);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void doAuthenticate(
|
||||
String authorization,
|
||||
AuthJwtService authJwtService,
|
||||
OnlineTicketService onlineTicketService) throws ParseException {
|
||||
if(authJwtService.validateJwtToken(authorization)) {
|
||||
String ticket = authJwtService.resolveTicket(authorization);
|
||||
OnlineTicket onlineTicket = onlineTicketService.get(ticket);
|
||||
if(onlineTicket != null) {
|
||||
setAuthentication(onlineTicket.getAuthentication());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static void setAuthentication(Authentication authentication) {
|
||||
WebContext.setAttribute(WebConstants.AUTHENTICATION, authentication);
|
||||
}
|
||||
|
||||
public static Authentication getAuthentication() {
|
||||
Authentication authentication = (Authentication) WebContext.getAttribute(WebConstants.AUTHENTICATION);
|
||||
return authentication;
|
||||
}
|
||||
|
||||
public static boolean isAuthenticated() {
|
||||
return getAuthentication() != null;
|
||||
}
|
||||
|
||||
public static boolean isNotAuthenticated() {
|
||||
return getAuthentication() == null;
|
||||
}
|
||||
|
||||
public static SigninPrincipal getPrincipal() {
|
||||
Authentication authentication = getAuthentication();
|
||||
return authentication == null ? null :(SigninPrincipal) authentication.getPrincipal();
|
||||
}
|
||||
|
||||
public static UserInfo getUserInfo() {
|
||||
Authentication authentication = getAuthentication();
|
||||
UserInfo userInfo = null;
|
||||
if(isAuthenticated() && (authentication.getPrincipal() instanceof SigninPrincipal)) {
|
||||
SigninPrincipal signinPrincipal = ((SigninPrincipal) authentication.getPrincipal());
|
||||
userInfo = signinPrincipal.getUserInfo();
|
||||
}
|
||||
return userInfo;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -24,7 +24,7 @@ public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentR
|
||||
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
|
||||
UserInfo userInfo = null;
|
||||
Authentication authentication = (Authentication ) webRequest.getAttribute(WebConstants.AUTHENTICATION, RequestAttributes.SCOPE_SESSION);
|
||||
if(authentication.getPrincipal() instanceof SigninPrincipal) {
|
||||
if((authentication != null) && (authentication.getPrincipal() instanceof SigninPrincipal)) {
|
||||
SigninPrincipal signinPrincipal = ((SigninPrincipal) authentication.getPrincipal());
|
||||
userInfo = signinPrincipal.getUserInfo();
|
||||
if (userInfo != null) {
|
||||
|
||||
@@ -45,7 +45,7 @@ public class SessionSecurityContextHolderStrategy implements SecurityContextHold
|
||||
SecurityContext ctx = createEmptyContext();
|
||||
Authentication authentication = null;
|
||||
try {
|
||||
authentication = (Authentication)WebContext.getAuthentication();
|
||||
authentication = (Authentication)AuthorizationUtils.getAuthentication();
|
||||
if (authentication != null) {
|
||||
ctx.setAuthentication(authentication);
|
||||
}
|
||||
@@ -59,7 +59,7 @@ public class SessionSecurityContextHolderStrategy implements SecurityContextHold
|
||||
|
||||
@Override
|
||||
public void setContext(SecurityContext context) {
|
||||
WebContext.setAuthentication(context.getAuthentication());
|
||||
AuthorizationUtils.setAuthentication(context.getAuthentication());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -18,24 +18,24 @@ import com.fasterxml.jackson.databind.DatabindException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
@Controller
|
||||
public class AuthEntryPoint {
|
||||
private static final Logger _logger = LoggerFactory.getLogger(AuthEntryPoint.class);
|
||||
public class UnauthorizedEntryPoint {
|
||||
private static final Logger _logger = LoggerFactory.getLogger(UnauthorizedEntryPoint.class);
|
||||
|
||||
@RequestMapping(value={"/auth/entrypoint"})
|
||||
public void entryPoint(
|
||||
HttpServletRequest request, HttpServletResponse response)
|
||||
throws StreamWriteException, DatabindException, IOException {
|
||||
_logger.trace("AuthEntryPoint /entrypoint.");
|
||||
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
_logger.trace("UnauthorizedEntryPoint /entrypoint.");
|
||||
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
|
||||
final Map<String, Object> body = new HashMap<>();
|
||||
body.put("status", HttpServletResponse.SC_UNAUTHORIZED);
|
||||
body.put("error", "Unauthorized");
|
||||
body.put("message", "Unauthorized");
|
||||
body.put("path", request.getServletPath());
|
||||
final Map<String, Object> responseBody = new HashMap<>();
|
||||
responseBody.put("status", HttpServletResponse.SC_UNAUTHORIZED);
|
||||
responseBody.put("error", "Unauthorized");
|
||||
responseBody.put("message", "Unauthorized");
|
||||
responseBody.put("path", request.getServletPath());
|
||||
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.writeValue(response.getOutputStream(), body);
|
||||
mapper.writeValue(response.getOutputStream(), responseBody);
|
||||
}
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
/*
|
||||
* 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.web.interceptor;
|
||||
|
||||
import javax.servlet.RequestDispatcher;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
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.configuration.ApplicationConfig;
|
||||
import org.maxkey.util.AuthorizationHeaderUtils;
|
||||
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.stereotype.Component;
|
||||
import org.springframework.web.servlet.AsyncHandlerInterceptor;
|
||||
/**
|
||||
* 权限Interceptor处理
|
||||
* 权限处理需在servlet.xml中配置
|
||||
* mvc:interceptors permission
|
||||
* @author Crystal.Sea
|
||||
*
|
||||
*/
|
||||
@Component
|
||||
public class PermissionAdapter implements AsyncHandlerInterceptor {
|
||||
private static final Logger _logger = LoggerFactory.getLogger(PermissionAdapter.class);
|
||||
//无需Interceptor url
|
||||
@Autowired
|
||||
@Qualifier("applicationConfig")
|
||||
private ApplicationConfig applicationConfig;
|
||||
|
||||
@Autowired
|
||||
@Qualifier("onlineTicketService")
|
||||
OnlineTicketService onlineTicketService;
|
||||
|
||||
@Autowired
|
||||
@Qualifier("authJwtService")
|
||||
AuthJwtService authJwtService ;
|
||||
|
||||
/*
|
||||
* 请求前处理
|
||||
* (non-Javadoc)
|
||||
* @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)
|
||||
*/
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
|
||||
_logger.trace("PermissionAdapter preHandle");
|
||||
String authorization = AuthorizationHeaderUtils.resolveBearer(request);
|
||||
|
||||
if(authJwtService.validateJwtToken(authorization)) {
|
||||
String ticket = authJwtService.resolveTicket(authorization);
|
||||
if(WebContext.getAuthentication()==null) {
|
||||
OnlineTicket onlineTicket = onlineTicketService.get(ticket);
|
||||
if(onlineTicket != null) {
|
||||
WebContext.setAuthentication(onlineTicket.getAuthentication());
|
||||
}
|
||||
}
|
||||
//判断用户是否登录
|
||||
if(WebContext.getAuthentication()==null
|
||||
||WebContext.getAuthentication().getAuthorities()==null){//判断用户和角色,判断用户是否登录用户
|
||||
_logger.trace("No Authentication ... forward to /auth/entrypoint");
|
||||
RequestDispatcher dispatcher = request.getRequestDispatcher("/auth/entrypoint");
|
||||
dispatcher.forward(request, response);
|
||||
return false;
|
||||
}
|
||||
|
||||
//非管理员用户直接注销
|
||||
if (!((SigninPrincipal) WebContext.getAuthentication().getPrincipal()).isRoleAdministrators()) {
|
||||
_logger.debug("Not ADMINISTRATORS Authentication .");
|
||||
RequestDispatcher dispatcher = request.getRequestDispatcher("/logout");
|
||||
dispatcher.forward(request, response);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
boolean hasAccess=true;
|
||||
|
||||
|
||||
/*
|
||||
boolean preHandler = super.preHandle(request, response, handler);
|
||||
|
||||
if(preHandler) {
|
||||
preHandler = false;
|
||||
|
||||
|
||||
if(!preHandler){//无权限转向
|
||||
log.debug("You do not have permission to access "+accessUrl);
|
||||
RequestDispatcher dispatcher = request.getRequestDispatcher("/accessdeny");
|
||||
dispatcher.forward(request, response);
|
||||
return false;
|
||||
}
|
||||
}*/
|
||||
return hasAccess;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
* 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.web.interceptor;
|
||||
|
||||
import javax.servlet.RequestDispatcher;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
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.web.AuthorizationUtils;
|
||||
import org.maxkey.configuration.ApplicationConfig;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.servlet.AsyncHandlerInterceptor;
|
||||
/**
|
||||
* 权限Interceptor处理
|
||||
* 权限处理需在servlet.xml中配置
|
||||
* mvc:interceptors permission
|
||||
* @author Crystal.Sea
|
||||
*
|
||||
*/
|
||||
@Component
|
||||
public class PermissionInterceptor implements AsyncHandlerInterceptor {
|
||||
private static final Logger _logger = LoggerFactory.getLogger(PermissionInterceptor.class);
|
||||
//无需Interceptor url
|
||||
@Autowired
|
||||
ApplicationConfig applicationConfig;
|
||||
|
||||
@Autowired
|
||||
OnlineTicketService onlineTicketService;
|
||||
|
||||
@Autowired
|
||||
AuthJwtService authJwtService ;
|
||||
|
||||
/*
|
||||
* 请求前处理
|
||||
* (non-Javadoc)
|
||||
* @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)
|
||||
*/
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
|
||||
_logger.trace("PermissionAdapter preHandle");
|
||||
AuthorizationUtils.authenticate(request, authJwtService, onlineTicketService);
|
||||
//判断用户是否登录
|
||||
if(AuthorizationUtils.getAuthentication()==null
|
||||
||AuthorizationUtils.getAuthentication().getAuthorities()==null){//判断用户和角色,判断用户是否登录用户
|
||||
_logger.trace("No Authentication ... forward to /auth/entrypoint");
|
||||
RequestDispatcher dispatcher = request.getRequestDispatcher("/auth/entrypoint");
|
||||
dispatcher.forward(request, response);
|
||||
return false;
|
||||
}
|
||||
|
||||
//非管理员用户直接注销
|
||||
if (!((SigninPrincipal) AuthorizationUtils.getAuthentication().getPrincipal()).isRoleAdministrators()) {
|
||||
_logger.debug("Not ADMINISTRATORS Authentication .");
|
||||
RequestDispatcher dispatcher = request.getRequestDispatcher("/logout");
|
||||
dispatcher.forward(request, response);
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean hasAccess=true;
|
||||
|
||||
return hasAccess;
|
||||
}
|
||||
}
|
||||
@@ -24,8 +24,6 @@ import org.maxkey.authn.jwt.AuthJwtService;
|
||||
import org.maxkey.authn.online.OnlineTicketService;
|
||||
import org.maxkey.authn.online.OnlineTicketServiceFactory;
|
||||
import org.maxkey.authn.realm.AbstractAuthenticationRealm;
|
||||
import org.maxkey.authn.support.rememberme.AbstractRemeberMeService;
|
||||
import org.maxkey.authn.support.rememberme.RemeberMeServiceFactory;
|
||||
import org.maxkey.authn.web.SessionListenerAdapter;
|
||||
import org.maxkey.configuration.ApplicationConfig;
|
||||
import org.maxkey.configuration.AuthJwkConfig;
|
||||
@@ -69,7 +67,6 @@ public class AuthenticationAutoConfiguration implements InitializingBean {
|
||||
ApplicationConfig applicationConfig,
|
||||
AbstractOtpAuthn tfaOtpAuthn,
|
||||
OtpAuthnService otpAuthnService,
|
||||
AbstractRemeberMeService remeberMeService,
|
||||
OnlineTicketService onlineTicketServices
|
||||
) {
|
||||
|
||||
@@ -79,7 +76,6 @@ public class AuthenticationAutoConfiguration implements InitializingBean {
|
||||
applicationConfig,
|
||||
tfaOtpAuthn,
|
||||
otpAuthnService,
|
||||
remeberMeService,
|
||||
onlineTicketServices
|
||||
);
|
||||
|
||||
@@ -125,18 +121,6 @@ public class AuthenticationAutoConfiguration implements InitializingBean {
|
||||
return new LoginHistoryRepository(jdbcTemplate);
|
||||
}
|
||||
|
||||
/**
|
||||
* remeberMeService .
|
||||
* @return
|
||||
*/
|
||||
@Bean(name = "remeberMeService")
|
||||
public AbstractRemeberMeService remeberMeService(
|
||||
@Value("${maxkey.server.persistence}") int persistence,
|
||||
@Value("${maxkey.login.remeberme.validity}") int validity,
|
||||
JdbcTemplate jdbcTemplate,
|
||||
RedisConnectionFactory redisConnFactory) {
|
||||
return new RemeberMeServiceFactory().getService(persistence, jdbcTemplate, redisConnFactory);
|
||||
}
|
||||
|
||||
@Bean(name = "onlineTicketService")
|
||||
public OnlineTicketService onlineTicketService(
|
||||
|
||||
Reference in New Issue
Block a user