v1.2.2 RC

This commit is contained in:
shimingxy 2020-03-30 10:32:39 +08:00
parent c70aa8df95
commit 6ce1481df5
28 changed files with 3112 additions and 1447 deletions

7
.checkstyle Normal file
View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<fileset-config file-format-version="1.2.0" simple-config="true" sync-formatter="false">
<fileset name="all" enabled="true" check-config-name="checkstyle-rules" local="false">
<file-match-pattern match-pattern=".*" include-pattern="true"/>
</fileset>
</fileset-config>

View File

@ -15,9 +15,15 @@
<arguments> <arguments>
</arguments> </arguments>
</buildCommand> </buildCommand>
<buildCommand>
<name>net.sf.eclipsecs.core.CheckstyleBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec> </buildSpec>
<natures> <natures>
<nature>org.eclipse.jdt.core.javanature</nature> <nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature> <nature>org.eclipse.buildship.core.gradleprojectnature</nature>
<nature>net.sf.eclipsecs.core.CheckstyleNature</nature>
</natures> </natures>
</projectDescription> </projectDescription>

View File

@ -1,18 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<classpath> <classpath>
<classpathentry kind="src" output="bin/main" path="src/main/java"> <classpathentry kind="src" output="bin/main"
path="src/main/java">
<attributes> <attributes>
<attribute name="gradle_scope" value="main"/> <attribute name="gradle_scope" value="main" />
<attribute name="gradle_used_by_scope" value="main,test"/> <attribute name="gradle_used_by_scope" value="main,test" />
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry kind="src" output="bin/test" path="src/test/java"> <classpathentry kind="src" output="bin/test"
path="src/test/java">
<attributes> <attributes>
<attribute name="gradle_scope" value="test"/> <attribute name="gradle_scope" value="test" />
<attribute name="gradle_used_by_scope" value="test"/> <attribute name="gradle_used_by_scope" value="test" />
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8/"/> <classpathentry kind="con"
<classpathentry kind="con" path="org.eclipse.buildship.core.gradleclasspathcontainer"/> path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8/" />
<classpathentry kind="output" path="bin/default"/> <classpathentry kind="con"
path="org.eclipse.buildship.core.gradleclasspathcontainer" />
<classpathentry kind="output" path="bin/default" />
</classpath> </classpath>

View File

@ -25,11 +25,17 @@
<arguments> <arguments>
</arguments> </arguments>
</buildCommand> </buildCommand>
<buildCommand>
<name>net.sf.eclipsecs.core.CheckstyleBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec> </buildSpec>
<natures> <natures>
<nature>org.eclipse.jdt.core.javanature</nature> <nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature> <nature>org.eclipse.buildship.core.gradleprojectnature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature> <nature>org.eclipse.wst.common.project.facet.core.nature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature> <nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>net.sf.eclipsecs.core.CheckstyleNature</nature>
</natures> </natures>
</projectDescription> </projectDescription>

View File

@ -1,6 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0"> <?xml version="1.0" encoding="UTF-8"?>
<wb-module deploy-name="maxkey-core"> <project-modules id="moduleCoreId"
<wb-resource deploy-path="/" source-path="/src/main/java"/> project-version="1.5.0">
<wb-resource deploy-path="/" source-path="/src/test/java"/> <wb-module deploy-name="maxkey-core">
</wb-module> <wb-resource deploy-path="/" source-path="/src/main/java" />
<wb-resource deploy-path="/" source-path="/src/test/java" />
</wb-module>
</project-modules> </project-modules>

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<faceted-project> <faceted-project>
<fixed facet="java"/> <fixed facet="java" />
<fixed facet="jst.utility"/> <fixed facet="jst.utility" />
<installed facet="jst.utility" version="1.0"/> <installed facet="jst.utility" version="1.0" />
<installed facet="java" version="1.8"/> <installed facet="java" version="1.8" />
</faceted-project> </faceted-project>

File diff suppressed because one or more lines are too long

View File

@ -19,58 +19,59 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticatio
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.AuthenticationException;
/** /**
* login Authentication abstract class * login Authentication abstract class
* *
* @author Crystal.Sea * @author Crystal.Sea
* *
*/ */
public abstract class AbstractAuthenticationProvider{ public abstract class AbstractAuthenticationProvider {
private static final Logger _logger = LoggerFactory.getLogger(AbstractAuthenticationProvider.class); private static final Logger _logger = LoggerFactory.getLogger(AbstractAuthenticationProvider.class);
@Autowired @Autowired
@Qualifier("applicationConfig") @Qualifier("applicationConfig")
protected ApplicationConfig applicationConfig; protected ApplicationConfig applicationConfig;
@Autowired @Autowired
@Qualifier("authenticationRealm") @Qualifier("authenticationRealm")
protected AbstractAuthenticationRealm authenticationRealm; protected AbstractAuthenticationRealm authenticationRealm;
@Autowired @Autowired
@Qualifier("tfaOTPAuthn") @Qualifier("tfaOTPAuthn")
protected AbstractOTPAuthn tfaOTPAuthn; protected AbstractOTPAuthn tfaOTPAuthn;
@Autowired @Autowired
@Qualifier("remeberMeService") @Qualifier("remeberMeService")
protected AbstractRemeberMeService remeberMeService; protected AbstractRemeberMeService remeberMeService;
protected abstract String getProviderName();
protected abstract String getProviderName();
protected abstract Authentication doInternalAuthenticate(Authentication authentication); protected abstract Authentication doInternalAuthenticate(Authentication authentication);
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public boolean supports(Class authentication) { public boolean supports(Class authentication) {
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication)); return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
} }
/* /*
* authenticate * authenticate (non-Javadoc)
* (non-Javadoc) *
* @see org.springframework.security.authentication.AuthenticationProvider#authenticate(org.springframework.security.core.Authentication) * @see org.springframework.security.authentication.AuthenticationProvider#
* authenticate(org.springframework.security.core.Authentication)
*/ */
public Authentication authenticate(Authentication authentication) throws AuthenticationException { public Authentication authenticate(Authentication authentication) throws AuthenticationException {
_logger.debug("Trying to authenticate user '{}' via {}", authentication.getPrincipal(), getProviderName()); _logger.debug("Trying to authenticate user '{}' via {}", authentication.getPrincipal(), getProviderName());
try { try {
authentication = doInternalAuthenticate(authentication); authentication = doInternalAuthenticate(authentication);
} catch (AuthenticationException e) { } catch (AuthenticationException e) {
e.printStackTrace(); e.printStackTrace();
_logger.error("Failed to authenticate user {} via {}: {}", new Object[]{authentication.getPrincipal(), getProviderName(), e.getMessage()}); _logger.error("Failed to authenticate user {} via {}: {}",
new Object[] { authentication.getPrincipal(), getProviderName(), e.getMessage() });
throw e; throw e;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
String message = "Unexpected exception in " + getProviderName() + " authentication:"; String message = "Unexpected exception in " + getProviderName() + " authentication:";
_logger.error(message, e); _logger.error(message, e);
throw new AuthenticationServiceException(message, e); throw new AuthenticationServiceException(message, e);
@ -78,188 +79,195 @@ public abstract class AbstractAuthenticationProvider{
if (!authentication.isAuthenticated()) { if (!authentication.isAuthenticated()) {
return authentication; return authentication;
} }
// user authenticated // user authenticated
_logger.debug("'{}' authenticated successfully by {}.", authentication.getPrincipal(), getProviderName()); _logger.debug("'{}' authenticated successfully by {}.", authentication.getPrincipal(), getProviderName());
UserInfo userInfo=WebContext.getUserInfo(); UserInfo userInfo = WebContext.getUserInfo();
Object password_set_type=WebContext.getSession().getAttribute(WebConstants.CURRENT_LOGIN_USER_PASSWORD_SET_TYPE); Object password_set_type = WebContext.getSession()
//登录完成后切换SESSION .getAttribute(WebConstants.CURRENT_LOGIN_USER_PASSWORD_SET_TYPE);
// 登录完成后切换SESSION
_logger.debug("Login Session {}.", WebContext.getSession().getId()); _logger.debug("Login Session {}.", WebContext.getSession().getId());
WebContext.getSession().invalidate(); WebContext.getSession().invalidate();
WebContext.setAttribute(WebConstants.CURRENT_USER_SESSION_ID, WebContext.getSession().getId()); WebContext.setAttribute(WebConstants.CURRENT_USER_SESSION_ID, WebContext.getSession().getId());
_logger.debug("Login Success Session {}.", WebContext.getSession().getId()); _logger.debug("Login Success Session {}.", WebContext.getSession().getId());
authenticationRealm.insertLoginHistory(userInfo,LOGINTYPE.LOCAL,"","xe00000004","success"); authenticationRealm.insertLoginHistory(userInfo, LOGINTYPE.LOCAL, "", "xe00000004", "success");
//认证设置 // 认证设置
WebContext.setAuthentication(authentication); WebContext.setAuthentication(authentication);
WebContext.setUserInfo(userInfo); WebContext.setUserInfo(userInfo);
WebContext.getSession().setAttribute(WebConstants.CURRENT_LOGIN_USER_PASSWORD_SET_TYPE,password_set_type); WebContext.getSession().setAttribute(WebConstants.CURRENT_LOGIN_USER_PASSWORD_SET_TYPE, password_set_type);
// create new authentication response containing the user and it's authorities // create new authentication response containing the user and it's authorities
UsernamePasswordAuthenticationToken simpleUserAuthentication = new UsernamePasswordAuthenticationToken(userInfo.getUsername(), authentication.getCredentials(), authentication.getAuthorities()); UsernamePasswordAuthenticationToken simpleUserAuthentication = new UsernamePasswordAuthenticationToken(
userInfo.getUsername(), authentication.getCredentials(), authentication.getAuthorities());
return simpleUserAuthentication; return simpleUserAuthentication;
} }
/** /**
* session validate * session validate
*
* @param j_username * @param j_username
* @param j_cname * @param j_cname
* @param sessionId * @param sessionId
*/ */
protected void sessionValid(String j_sessionId){ protected void sessionValid(String j_sessionId) {
if(j_sessionId==null || ! j_sessionId.equals(WebContext.getSession().getId())){ if (j_sessionId == null || !j_sessionId.equals(WebContext.getSession().getId())) {
String message=WebContext.getI18nValue("login.error.session"); String message = WebContext.getI18nValue("login.error.session");
_logger.debug("login session valid error."); _logger.debug("login session valid error.");
throw new BadCredentialsException(message); throw new BadCredentialsException(message);
} }
} }
/** /**
* session validate * session validate
*
* @param j_username * @param j_username
* @param j_cname * @param j_cname
* @param sessionId * @param sessionId
*/ */
protected void jwtTokenValid(String j_jwtToken){ protected void jwtTokenValid(String j_jwtToken) {
/*if(j_jwtToken!=null && ! j_jwtToken.equals("")){ /*
if(jwtLoginService.jwtTokenValidation(j_jwtToken)){ * if(j_jwtToken!=null && ! j_jwtToken.equals("")){
return; * if(jwtLoginService.jwtTokenValidation(j_jwtToken)){ return; } }
} */
}*/ String message = WebContext.getI18nValue("login.error.session");
String message=WebContext.getI18nValue("login.error.session"); _logger.debug("login session valid error.");
_logger.debug("login session valid error."); throw new BadCredentialsException(message);
throw new BadCredentialsException(message);
} }
protected void authTypeValid(String j_auth_type){ protected void authTypeValid(String j_auth_type) {
if(j_auth_type==null){ if (j_auth_type == null) {
String message=WebContext.getI18nValue("login.error.authtype"); String message = WebContext.getI18nValue("login.error.authtype");
_logger.debug("login AuthN type can not been null ."); _logger.debug("login AuthN type can not been null .");
throw new BadCredentialsException(message); throw new BadCredentialsException(message);
} }
} }
/** /**
* captcha validate * captcha validate
*
* @param j_username * @param j_username
* @param j_cname * @param j_cname
* @param captcha * @param captcha
*/ */
protected void captchaValid(String j_captcha,String j_auth_type){ protected void captchaValid(String j_captcha, String j_auth_type) {
if(applicationConfig.getLoginConfig().isCaptcha()){//for basic if (applicationConfig.getLoginConfig().isCaptcha()) {// for basic
if(j_auth_type.equalsIgnoreCase("common")){ if (j_auth_type.equalsIgnoreCase("common")) {
_logger.info("captcha : "+WebContext.getSession().getAttribute(WebConstants.KAPTCHA_SESSION_KEY).toString()); _logger.info("captcha : "
if(j_captcha==null + WebContext.getSession().getAttribute(WebConstants.KAPTCHA_SESSION_KEY).toString());
|| !j_captcha.equals(WebContext.getSession().getAttribute(WebConstants.KAPTCHA_SESSION_KEY).toString())){ if (j_captcha == null || !j_captcha
String message=WebContext.getI18nValue("login.error.captcha"); .equals(WebContext.getSession().getAttribute(WebConstants.KAPTCHA_SESSION_KEY).toString())) {
_logger.debug("login captcha valid error."); String message = WebContext.getI18nValue("login.error.captcha");
throw new BadCredentialsException(message); _logger.debug("login captcha valid error.");
} throw new BadCredentialsException(message);
} }
}
} }
} }
/** /**
* captcha validate * captcha validate
*
* @param j_username * @param j_username
* @param j_cname * @param j_cname
* @param j_otp_captcha * @param j_otp_captcha
*/ */
protected void tftcaptchaValid(String j_otp_captcha,String j_auth_type,UserInfo userInfo){ protected void tftcaptchaValid(String j_otp_captcha, String j_auth_type, UserInfo userInfo) {
if(applicationConfig.getLoginConfig().isOneTimePwd()){//for one time password 2 factor if (applicationConfig.getLoginConfig().isOneTimePwd()) {// for one time password 2 factor
if(j_auth_type.equalsIgnoreCase("tfa")){ if (j_auth_type.equalsIgnoreCase("tfa")) {
UserInfo validUserInfo=new UserInfo(); UserInfo validUserInfo = new UserInfo();
validUserInfo.setUsername(userInfo.getUsername()); validUserInfo.setUsername(userInfo.getUsername());
String sharedSecret=PasswordReciprocal.getInstance().decoder(userInfo.getSharedSecret()); String sharedSecret = PasswordReciprocal.getInstance().decoder(userInfo.getSharedSecret());
validUserInfo.setSharedSecret(sharedSecret); validUserInfo.setSharedSecret(sharedSecret);
validUserInfo.setSharedCounter(userInfo.getSharedCounter()); validUserInfo.setSharedCounter(userInfo.getSharedCounter());
validUserInfo.setId(userInfo.getId()); validUserInfo.setId(userInfo.getId());
if(j_otp_captcha==null||!tfaOTPAuthn.validate(validUserInfo, j_otp_captcha)){ if (j_otp_captcha == null || !tfaOTPAuthn.validate(validUserInfo, j_otp_captcha)) {
String message=WebContext.getI18nValue("login.error.captcha"); String message = WebContext.getI18nValue("login.error.captcha");
_logger.debug("login captcha valid error."); _logger.debug("login captcha valid error.");
throw new BadCredentialsException(message); throw new BadCredentialsException(message);
} }
} }
} }
} }
/** /**
* login user by j_username and j_cname * login user by j_username and j_cname first query user by j_cname if first
* first query user by j_cname * step userinfo is null,query user from system
* if first step userinfo is null,query user from system *
* @param j_username * @param j_username
* @param j_cname * @param j_cname
* @return * @return
*/ */
protected UserInfo loadUserInfo(String j_username,String j_password){ protected UserInfo loadUserInfo(String j_username, String j_password) {
UserInfo userInfo = authenticationRealm.loadUserInfo(j_username,j_password); UserInfo userInfo = authenticationRealm.loadUserInfo(j_username, j_password);
if(userInfo != null){
if(userInfo.getUserType()=="SYSTEM"){
_logger.debug("SYSTEM User Login. ");
}else{
_logger.debug("User Login. ");
}
}
return userInfo; if (userInfo != null) {
if (userInfo.getUserType() == "SYSTEM") {
_logger.debug("SYSTEM User Login. ");
} else {
_logger.debug("User Login. ");
}
}
return userInfo;
} }
/** /**
* check input password empty * check input password empty
*
* @param password * @param password
* @return * @return
*/ */
protected boolean emptyPasswordValid(String j_password){ protected boolean emptyPasswordValid(String j_password) {
if(null==j_password||"".equals(j_password)){ if (null == j_password || "".equals(j_password)) {
throw new BadCredentialsException(WebContext.getI18nValue("login.error.password.null")); throw new BadCredentialsException(WebContext.getI18nValue("login.error.password.null"));
} }
return true; return true;
} }
/** /**
* check input username or password empty * check input username or password empty
*
* @param j_username * @param j_username
* @param password * @param password
* @return * @return
*/ */
protected boolean emptyEmailValid(String j_email){ protected boolean emptyEmailValid(String j_email) {
if(null==j_email||"".equals(j_email)){ if (null == j_email || "".equals(j_email)) {
throw new BadCredentialsException("login.error.email.null"); throw new BadCredentialsException("login.error.email.null");
} }
return true; return true;
} }
/** /**
* check input username empty * check input username empty
*
* @param j_username * @param j_username
* @return * @return
*/ */
protected boolean emptyUsernameValid(String j_username){ protected boolean emptyUsernameValid(String j_username) {
if(null==j_username||"".equals(j_username)){ if (null == j_username || "".equals(j_username)) {
throw new BadCredentialsException(WebContext.getI18nValue("login.error.username.null")); throw new BadCredentialsException(WebContext.getI18nValue("login.error.username.null"));
} }
return true; return true;
} }
protected boolean userinfoValid(UserInfo userInfo,String j_username){ protected boolean userinfoValid(UserInfo userInfo, String j_username) {
if(null==userInfo){ if (null == userInfo) {
String message=WebContext.getI18nValue("login.error.username"); String message = WebContext.getI18nValue("login.error.username");
_logger.debug("login user "+j_username+" not in this System ."+message); _logger.debug("login user " + j_username + " not in this System ." + message);
UserInfo loginUser=new UserInfo(j_username); UserInfo loginUser = new UserInfo(j_username);
loginUser.setId(loginUser.generateId()); loginUser.setId(loginUser.generateId());
loginUser.setDisplayName("not exist"); loginUser.setDisplayName("not exist");
loginUser.setLoginCount(0); loginUser.setLoginCount(0);
authenticationRealm.insertLoginHistory(loginUser,LOGINTYPE.LOCAL,"",WebContext.getI18nValue("login.error.username"),"user not exist"); authenticationRealm.insertLoginHistory(loginUser, LOGINTYPE.LOCAL, "",
throw new BadCredentialsException(WebContext.getI18nValue("login.error.username")); WebContext.getI18nValue("login.error.username"), "user not exist");
} throw new BadCredentialsException(WebContext.getI18nValue("login.error.username"));
return true; }
return true;
} }
} }

View File

@ -6,13 +6,13 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority;
public class BasicAuthentication implements Authentication{ public class BasicAuthentication implements Authentication {
/** /**
* *
*/ */
private static final long serialVersionUID = -110742975439268030L; private static final long serialVersionUID = -110742975439268030L;
String j_username ; String j_username;
String j_password ; String j_password;
String j_sessionid; String j_sessionid;
String j_captcha; String j_captcha;
String j_otp_captcha; String j_otp_captcha;
@ -21,135 +21,134 @@ public class BasicAuthentication implements Authentication{
String j_jwt_token; String j_jwt_token;
ArrayList<GrantedAuthority> grantedAuthority; ArrayList<GrantedAuthority> grantedAuthority;
boolean authenticated; boolean authenticated;
public BasicAuthentication() {
grantedAuthority = new ArrayList<GrantedAuthority>();
grantedAuthority.add(new SimpleGrantedAuthority("ROLE_USER"));
grantedAuthority.add(new SimpleGrantedAuthority("ORDINARY_USER"));
}
@Override public BasicAuthentication() {
public String getName() { grantedAuthority = new ArrayList<GrantedAuthority>();
return "Basic Authentication"; grantedAuthority.add(new SimpleGrantedAuthority("ROLE_USER"));
} grantedAuthority.add(new SimpleGrantedAuthority("ORDINARY_USER"));
}
@Override @Override
public Collection<? extends GrantedAuthority> getAuthorities() { public String getName() {
return grantedAuthority; return "Basic Authentication";
} }
@Override @Override
public Object getCredentials() { public Collection<? extends GrantedAuthority> getAuthorities() {
return this.getJ_password(); return grantedAuthority;
} }
@Override @Override
public Object getDetails() { public Object getCredentials() {
return null; return this.getJ_password();
} }
@Override @Override
public Object getPrincipal() { public Object getDetails() {
return this.getJ_username(); return null;
} }
@Override @Override
public boolean isAuthenticated() { public Object getPrincipal() {
return authenticated; return this.getJ_username();
} }
@Override @Override
public void setAuthenticated(boolean authenticated) throws IllegalArgumentException { public boolean isAuthenticated() {
this.authenticated=authenticated; return authenticated;
}
}
public String getJ_username() { @Override
return j_username; public void setAuthenticated(boolean authenticated) throws IllegalArgumentException {
} this.authenticated = authenticated;
public String getUsername() {
return j_username;
}
public void setJ_username(String j_username) { }
this.j_username = j_username;
}
public String getJ_password() { public String getJ_username() {
return j_password; return j_username;
} }
public void setJ_password(String j_password) { public String getUsername() {
this.j_password = j_password; return j_username;
} }
public String getJ_sessionid() { public void setJ_username(String j_username) {
return j_sessionid; this.j_username = j_username;
} }
public String getSessionid() {
return j_sessionid;
}
public void setJ_sessionid(String j_sessionid) { public String getJ_password() {
this.j_sessionid = j_sessionid; return j_password;
} }
public String getJ_captcha() { public void setJ_password(String j_password) {
return j_captcha; this.j_password = j_password;
} }
public void setJ_captcha(String j_captcha) { public String getJ_sessionid() {
this.j_captcha = j_captcha; return j_sessionid;
} }
public String getJ_otp_captcha() { public String getSessionid() {
return j_otp_captcha; return j_sessionid;
} }
public void setJ_otp_captcha(String j_otp_captcha) { public void setJ_sessionid(String j_sessionid) {
this.j_otp_captcha = j_otp_captcha; this.j_sessionid = j_sessionid;
} }
public String getJ_remeberme() { public String getJ_captcha() {
return j_remeberme; return j_captcha;
} }
public void setJ_remeberme(String j_remeberme) { public void setJ_captcha(String j_captcha) {
this.j_remeberme = j_remeberme; this.j_captcha = j_captcha;
} }
public String getJ_auth_type() { public String getJ_otp_captcha() {
return j_auth_type; return j_otp_captcha;
} }
public void setJ_auth_type(String j_auth_type) { public void setJ_otp_captcha(String j_otp_captcha) {
this.j_auth_type = j_auth_type; this.j_otp_captcha = j_otp_captcha;
} }
public String getJ_jwt_token() { public String getJ_remeberme() {
return j_jwt_token; return j_remeberme;
} }
public void setJ_jwt_token(String j_jwt_token) { public void setJ_remeberme(String j_remeberme) {
this.j_jwt_token = j_jwt_token; this.j_remeberme = j_remeberme;
} }
public ArrayList<GrantedAuthority> getGrantedAuthority() {
return grantedAuthority;
}
public void setGrantedAuthority(ArrayList<GrantedAuthority> grantedAuthority) { public String getJ_auth_type() {
this.grantedAuthority = grantedAuthority; return j_auth_type;
} }
@Override public void setJ_auth_type(String j_auth_type) {
public String toString() { this.j_auth_type = j_auth_type;
return "BasicAuthentication [j_username=" + j_username + ", j_sessionId=" + j_sessionid + ", j_captcha=" }
+ j_captcha + ", j_otp_captcha=" + j_otp_captcha + ", j_remeberMe=" + j_remeberme + ", j_auth_type="
+ j_auth_type + ", j_jwtToken=" + j_jwt_token + ", authenticated=" + authenticated + "]"; public String getJ_jwt_token() {
} return j_jwt_token;
}
public void setJ_jwt_token(String j_jwt_token) {
this.j_jwt_token = j_jwt_token;
}
public ArrayList<GrantedAuthority> getGrantedAuthority() {
return grantedAuthority;
}
public void setGrantedAuthority(ArrayList<GrantedAuthority> grantedAuthority) {
this.grantedAuthority = grantedAuthority;
}
@Override
public String toString() {
return "BasicAuthentication [j_username=" + j_username + ", j_sessionId=" + j_sessionid + ", j_captcha="
+ j_captcha + ", j_otp_captcha=" + j_otp_captcha + ", j_remeberMe=" + j_remeberme + ", j_auth_type="
+ j_auth_type + ", j_jwtToken=" + j_jwt_token + ", authenticated=" + authenticated + "]";
}
} }

View File

@ -18,67 +18,67 @@ import org.springframework.web.context.request.ServletRequestAttributes;
* *
*/ */
public class RealmAuthenticationProvider extends AbstractAuthenticationProvider { public class RealmAuthenticationProvider extends AbstractAuthenticationProvider {
private static final Logger _logger = LoggerFactory.getLogger(RealmAuthenticationProvider.class); private static final Logger _logger = LoggerFactory.getLogger(RealmAuthenticationProvider.class);
protected String getProviderName() { protected String getProviderName() {
return "RealmAuthenticationProvider"; return "RealmAuthenticationProvider";
} }
@Override @Override
protected Authentication doInternalAuthenticate(Authentication authentication) { protected Authentication doInternalAuthenticate(Authentication authentication) {
BasicAuthentication auth =(BasicAuthentication)authentication; BasicAuthentication auth = (BasicAuthentication)authentication;
_logger.debug("authentication "+auth); _logger.debug("authentication " + auth);
sessionValid(auth.getJ_sessionid());
//jwtTokenValid(j_jwtToken);
authTypeValid(auth.getJ_auth_type());
captchaValid(auth.getJ_captcha(),auth.getJ_auth_type());
emptyPasswordValid(auth.getJ_password());
UserInfo userInfo = null;
emptyUsernameValid(auth.getJ_username());
userInfo= loadUserInfo(auth.getJ_username(),auth.getJ_password());
userinfoValid(userInfo, auth.getJ_password());
tftcaptchaValid(auth.getJ_otp_captcha(),auth.getJ_auth_type(),userInfo);
authenticationRealm.passwordPolicyValid(userInfo);
authenticationRealm.passwordMatches(userInfo, auth.getJ_password());
authenticationRealm.grantAuthority(userInfo);
/**
* put userInfo to current session context
*/
WebContext.setUserInfo(userInfo);
auth.setAuthenticated(true);
if(auth.isAuthenticated()&&applicationConfig.getLoginConfig().isRemeberMe()){
if(auth.getJ_remeberme()!=null&&auth.getJ_remeberme().equals("remeberMe")){
WebContext.getSession().setAttribute(WebConstants.REMEBER_ME_SESSION,auth.getJ_username());
_logger.debug("do Remeber Me");
remeberMeService.createRemeberMe(
userInfo.getUsername(),
WebContext.getRequest(),
((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse());
}
}
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =new UsernamePasswordAuthenticationToken( sessionValid(auth.getJ_sessionid());
auth,
"PASSWORD", //jwtTokenValid(j_jwtToken);
authenticationRealm.grantAuthority(userInfo));
usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetails(WebContext.getRequest())); authTypeValid(auth.getJ_auth_type());
return usernamePasswordAuthenticationToken; captchaValid(auth.getJ_captcha(),auth.getJ_auth_type());
emptyPasswordValid(auth.getJ_password());
UserInfo userInfo = null;
emptyUsernameValid(auth.getJ_username());
userInfo= loadUserInfo(auth.getJ_username(),auth.getJ_password());
userinfoValid(userInfo, auth.getJ_password());
tftcaptchaValid(auth.getJ_otp_captcha(),auth.getJ_auth_type(),userInfo);
authenticationRealm.passwordPolicyValid(userInfo);
authenticationRealm.passwordMatches(userInfo, auth.getJ_password());
authenticationRealm.grantAuthority(userInfo);
/**
* put userInfo to current session context
*/
WebContext.setUserInfo(userInfo);
auth.setAuthenticated(true);
if(auth.isAuthenticated()&&applicationConfig.getLoginConfig().isRemeberMe()){
if(auth.getJ_remeberme()!=null&&auth.getJ_remeberme().equals("remeberMe")){
WebContext.getSession().setAttribute(WebConstants.REMEBER_ME_SESSION,auth.getJ_username());
_logger.debug("do Remeber Me");
remeberMeService.createRemeberMe(
userInfo.getUsername(),
WebContext.getRequest(),
((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse());
}
}
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =new UsernamePasswordAuthenticationToken(
auth,
"PASSWORD",
authenticationRealm.grantAuthority(userInfo));
usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetails(WebContext.getRequest()));
return usernamePasswordAuthenticationToken;
} }
} }

View File

@ -25,11 +25,17 @@
<arguments> <arguments>
</arguments> </arguments>
</buildCommand> </buildCommand>
<buildCommand>
<name>net.sf.eclipsecs.core.CheckstyleBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec> </buildSpec>
<natures> <natures>
<nature>org.eclipse.jdt.core.javanature</nature> <nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature> <nature>org.eclipse.buildship.core.gradleprojectnature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature> <nature>org.eclipse.wst.common.project.facet.core.nature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature> <nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>net.sf.eclipsecs.core.CheckstyleNature</nature>
</natures> </natures>
</projectDescription> </projectDescription>

View File

@ -17,23 +17,23 @@ package org.maxkey.authz.oauth2.common;
*/ */
public enum AuthenticationScheme { public enum AuthenticationScheme {
/** /**
* Send an Authorization header. * Send an Authorization header.
*/ */
header, header,
/** /**
* Send a query parameter in the URI. * Send a query parameter in the URI.
*/ */
query, query,
/** /**
* Send in the form body. * Send in the form body.
*/ */
form, form,
/** /**
* Do not send at all. * Do not send at all.
*/ */
none none
} }

View File

@ -18,222 +18,227 @@ import java.util.TreeSet;
*/ */
public class DefaultOAuth2AccessToken implements Serializable, OAuth2AccessToken { public class DefaultOAuth2AccessToken implements Serializable, OAuth2AccessToken {
private static final long serialVersionUID = 914967629530462926L; private static final long serialVersionUID = 914967629530462926L;
private String value; private String value;
private Date expiration; private Date expiration;
private String tokenType = BEARER_TYPE.toLowerCase(); private String tokenType = BEARER_TYPE.toLowerCase();
private OAuth2RefreshToken refreshToken; private OAuth2RefreshToken refreshToken;
private Set<String> scope; private Set<String> scope;
private Map<String, Object> additionalInformation = Collections.emptyMap(); private Map<String, Object> additionalInformation = Collections.emptyMap();
/** /**
* Create an access token from the value provided. * Create an access token from the value provided.
*/ */
public DefaultOAuth2AccessToken(String value) { public DefaultOAuth2AccessToken(String value) {
this.value = value; this.value = value;
} }
/** /**
* Private constructor for JPA and other serialization tools. * Private constructor for JPA and other serialization tools.
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
private DefaultOAuth2AccessToken() { private DefaultOAuth2AccessToken() {
this((String) null); this((String) null);
} }
/** /**
* Copy constructor for access token. * Copy constructor for access token.
* *
* @param accessToken * @param accessToken
*/ */
public DefaultOAuth2AccessToken(OAuth2AccessToken accessToken) { public DefaultOAuth2AccessToken(OAuth2AccessToken accessToken) {
this(accessToken.getValue()); this(accessToken.getValue());
setAdditionalInformation(accessToken.getAdditionalInformation()); setAdditionalInformation(accessToken.getAdditionalInformation());
setRefreshToken(accessToken.getRefreshToken()); setRefreshToken(accessToken.getRefreshToken());
setExpiration(accessToken.getExpiration()); setExpiration(accessToken.getExpiration());
setScope(accessToken.getScope()); setScope(accessToken.getScope());
setTokenType(accessToken.getTokenType()); setTokenType(accessToken.getTokenType());
} }
public void setValue(String value) { public void setValue(String value) {
this.value = value; this.value = value;
} }
/** /**
* The token value. * The token value.
* *
* @return The token value. * @return The token value.
*/ */
public String getValue() { public String getValue() {
return value; return value;
} }
public int getExpiresIn() { public int getExpiresIn() {
return expiration != null ? Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L) return expiration != null ? Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L).intValue()
.intValue() : 0; : 0;
} }
protected void setExpiresIn(int delta) { protected void setExpiresIn(int delta) {
setExpiration(new Date(System.currentTimeMillis() + delta)); setExpiration(new Date(System.currentTimeMillis() + delta));
} }
/** /**
* The instant the token expires. * The instant the token expires.
* *
* @return The instant the token expires. * @return The instant the token expires.
*/ */
public Date getExpiration() { public Date getExpiration() {
return expiration; return expiration;
} }
/** /**
* The instant the token expires. * The instant the token expires.
* *
* @param expiration The instant the token expires. * @param expiration The instant the token expires.
*/ */
public void setExpiration(Date expiration) { public void setExpiration(Date expiration) {
this.expiration = expiration; this.expiration = expiration;
} }
/** /**
* Convenience method for checking expiration * Convenience method for checking expiration
* *
* @return true if the expiration is befor ethe current time * @return true if the expiration is befor ethe current time
*/ */
public boolean isExpired() { public boolean isExpired() {
return expiration != null && expiration.before(new Date()); return expiration != null && expiration.before(new Date());
} }
/** /**
* The token type, as introduced in draft 11 of the OAuth 2 spec. The spec doesn't define (yet) that the valid token * The token type, as introduced in draft 11 of the OAuth 2 spec. The spec
* types are, but says it's required so the default will just be "undefined". * doesn't define (yet) that the valid token types are, but says it's required
* * so the default will just be "undefined".
* @return The token type, as introduced in draft 11 of the OAuth 2 spec. *
*/ * @return The token type, as introduced in draft 11 of the OAuth 2 spec.
public String getTokenType() { */
return tokenType; public String getTokenType() {
} return tokenType;
}
/** /**
* The token type, as introduced in draft 11 of the OAuth 2 spec. * The token type, as introduced in draft 11 of the OAuth 2 spec.
* *
* @param tokenType The token type, as introduced in draft 11 of the OAuth 2 spec. * @param tokenType The token type, as introduced in draft 11 of the OAuth 2
*/ * spec.
public void setTokenType(String tokenType) { */
this.tokenType = tokenType; public void setTokenType(String tokenType) {
} this.tokenType = tokenType;
}
/** /**
* The refresh token associated with the access token, if any. * The refresh token associated with the access token, if any.
* *
* @return The refresh token associated with the access token, if any. * @return The refresh token associated with the access token, if any.
*/ */
public OAuth2RefreshToken getRefreshToken() { public OAuth2RefreshToken getRefreshToken() {
return refreshToken; return refreshToken;
} }
/** /**
* The refresh token associated with the access token, if any. * The refresh token associated with the access token, if any.
* *
* @param refreshToken The refresh token associated with the access token, if any. * @param refreshToken The refresh token associated with the access token, if
*/ * any.
public void setRefreshToken(OAuth2RefreshToken refreshToken) { */
this.refreshToken = refreshToken; public void setRefreshToken(OAuth2RefreshToken refreshToken) {
} this.refreshToken = refreshToken;
}
/** /**
* The scope of the token. * The scope of the token.
* *
* @return The scope of the token. * @return The scope of the token.
*/ */
public Set<String> getScope() { public Set<String> getScope() {
return scope; return scope;
} }
/** /**
* The scope of the token. * The scope of the token.
* *
* @param scope The scope of the token. * @param scope The scope of the token.
*/ */
public void setScope(Set<String> scope) { public void setScope(Set<String> scope) {
this.scope = scope; this.scope = scope;
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
return obj != null && toString().equals(obj.toString()); return obj != null && toString().equals(obj.toString());
} }
@Override @Override
public int hashCode() { public int hashCode() {
return toString().hashCode(); return toString().hashCode();
} }
@Override @Override
public String toString() { public String toString() {
return String.valueOf(getValue()); return String.valueOf(getValue());
} }
public static OAuth2AccessToken valueOf(Map<String, String> tokenParams) { public static OAuth2AccessToken valueOf(Map<String, String> tokenParams) {
DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(tokenParams.get(ACCESS_TOKEN)); DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(tokenParams.get(ACCESS_TOKEN));
if (tokenParams.containsKey(EXPIRES_IN)) { if (tokenParams.containsKey(EXPIRES_IN)) {
long expiration = 0; long expiration = 0;
try { try {
expiration = Long.parseLong(String.valueOf(tokenParams.get(EXPIRES_IN))); expiration = Long.parseLong(String.valueOf(tokenParams.get(EXPIRES_IN)));
} } catch (NumberFormatException e) {
catch (NumberFormatException e) { // fall through...
// fall through... }
} token.setExpiration(new Date(System.currentTimeMillis() + (expiration * 1000L)));
token.setExpiration(new Date(System.currentTimeMillis() + (expiration * 1000L))); }
}
if (tokenParams.containsKey(REFRESH_TOKEN)) { if (tokenParams.containsKey(REFRESH_TOKEN)) {
String refresh = tokenParams.get(REFRESH_TOKEN); String refresh = tokenParams.get(REFRESH_TOKEN);
DefaultOAuth2RefreshToken refreshToken = new DefaultOAuth2RefreshToken(refresh); DefaultOAuth2RefreshToken refreshToken = new DefaultOAuth2RefreshToken(refresh);
token.setRefreshToken(refreshToken); token.setRefreshToken(refreshToken);
} }
if (tokenParams.containsKey(SCOPE)) { if (tokenParams.containsKey(SCOPE)) {
Set<String> scope = new TreeSet<String>(); Set<String> scope = new TreeSet<String>();
for (StringTokenizer tokenizer = new StringTokenizer(tokenParams.get(SCOPE), " ,"); tokenizer for (StringTokenizer tokenizer = new StringTokenizer(tokenParams.get(SCOPE), " ,"); tokenizer
.hasMoreTokens();) { .hasMoreTokens();) {
scope.add(tokenizer.nextToken()); scope.add(tokenizer.nextToken());
} }
token.setScope(scope); token.setScope(scope);
} }
if (tokenParams.containsKey(TOKEN_TYPE)) { if (tokenParams.containsKey(TOKEN_TYPE)) {
token.setTokenType(tokenParams.get(TOKEN_TYPE)); token.setTokenType(tokenParams.get(TOKEN_TYPE));
} }
return token; return token;
} }
/** /**
* Additional information that token granters would like to add to the token, e.g. to support new token types. * Additional information that token granters would like to add to the token,
* * e.g. to support new token types.
* @return the additional information (default empty) *
*/ * @return the additional information (default empty)
public Map<String, Object> getAdditionalInformation() { */
return additionalInformation; public Map<String, Object> getAdditionalInformation() {
} return additionalInformation;
}
/** /**
* Additional information that token granters would like to add to the token, e.g. to support new token types. If * Additional information that token granters would like to add to the token,
* the values in the map are primitive then remote communication is going to always work. It should also be safe to * e.g. to support new token types. If the values in the map are primitive then
* use maps (nested if desired), or something that is explicitly serializable by Jackson. * remote communication is going to always work. It should also be safe to use
* * maps (nested if desired), or something that is explicitly serializable by
* @param additionalInformation the additional information to set * Jackson.
*/ *
public void setAdditionalInformation(Map<String, Object> additionalInformation) { * @param additionalInformation the additional information to set
this.additionalInformation = new LinkedHashMap<String, Object>(additionalInformation); */
} public void setAdditionalInformation(Map<String, Object> additionalInformation) {
this.additionalInformation = new LinkedHashMap<String, Object>(additionalInformation);
}
} }

View File

@ -1,10 +1,8 @@
package org.maxkey.authz.oauth2.common; package org.maxkey.authz.oauth2.common;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.annotation.JsonValue;
import java.io.Serializable;
/** /**
* An OAuth 2 refresh token. * An OAuth 2 refresh token.
@ -14,59 +12,59 @@ import com.fasterxml.jackson.annotation.JsonValue;
*/ */
public class DefaultOAuth2RefreshToken implements Serializable, OAuth2RefreshToken { public class DefaultOAuth2RefreshToken implements Serializable, OAuth2RefreshToken {
private static final long serialVersionUID = 8349970621900575838L; private static final long serialVersionUID = 8349970621900575838L;
private String value; private String value;
/** /**
* Create a new refresh token. * Create a new refresh token.
*/ */
@JsonCreator @JsonCreator
public DefaultOAuth2RefreshToken(String value) { public DefaultOAuth2RefreshToken(String value) {
this.value = value; this.value = value;
} }
/** /**
* Default constructor for JPA and other serialization tools. * Default constructor for JPA and other serialization tools.
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
private DefaultOAuth2RefreshToken() { private DefaultOAuth2RefreshToken() {
this(null); this(null);
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.springframework.security.oauth2.common.IFOO#getValue() * @see org.springframework.security.oauth2.common.IFOO#getValue()
*/ */
@JsonValue @JsonValue
public String getValue() { public String getValue() {
return value; return value;
} }
@Override @Override
public String toString() { public String toString() {
return getValue(); return getValue();
} }
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) { if (this == o) {
return true; return true;
} }
if (!(o instanceof DefaultOAuth2RefreshToken)) { if (!(o instanceof DefaultOAuth2RefreshToken)) {
return false; return false;
} }
DefaultOAuth2RefreshToken that = (DefaultOAuth2RefreshToken) o; DefaultOAuth2RefreshToken that = (DefaultOAuth2RefreshToken) o;
if (value != null ? !value.equals(that.value) : that.value != null) { if (value != null ? !value.equals(that.value) : that.value != null) {
return false; return false;
} }
return true; return true;
} }
@Override @Override
public int hashCode() { public int hashCode() {
return value != null ? value.hashCode() : 0; return value != null ? value.hashCode() : 0;
} }
} }

View File

@ -1,9 +1,7 @@
package org.maxkey; package org.maxkey;
import java.util.Date; import java.util.Date;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import org.apache.ibatis.io.VFS; import org.apache.ibatis.io.VFS;
import org.apache.mybatis.jpa.SpringBootVFS; import org.apache.mybatis.jpa.SpringBootVFS;
import org.maxkey.web.InitApplicationContext; import org.maxkey.web.InitApplicationContext;
@ -17,25 +15,30 @@ import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication @SpringBootApplication
public class MaxKeyApplication extends SpringBootServletInitializer { public class MaxKeyApplication extends SpringBootServletInitializer {
private static final Logger _logger = LoggerFactory.getLogger(MaxKeyApplication.class); private static final Logger _logger = LoggerFactory.getLogger(MaxKeyApplication.class);
public static void main(String[] args) { /**
VFS.addImplClass(SpringBootVFS.class); * @param args args
ConfigurableApplicationContext applicationContext =SpringApplication.run(MaxKeyApplication.class, args); */
InitApplicationContext initWebContext=new InitApplicationContext(applicationContext); public static void main(String[] args) {
try { VFS.addImplClass(SpringBootVFS.class);
initWebContext.init(null); ConfigurableApplicationContext applicationContext =
} catch (ServletException e) { SpringApplication.run(MaxKeyApplication.class, args);
e.printStackTrace(); InitApplicationContext initWebContext = new InitApplicationContext(applicationContext);
_logger.error("",e); try {
} initWebContext.init(null);
_logger.info("MaxKey at "+new Date(applicationContext.getStartupDate())); } catch (ServletException e) {
_logger.info("MaxKey Server Port "+applicationContext.getBean(MaxKeyConfig.class).getPort()); e.printStackTrace();
_logger.info("MaxKey started."); _logger.error("", e);
} }
_logger.info("MaxKey at " + new Date(applicationContext.getStartupDate()));
_logger.info("MaxKey Server Port "
+ applicationContext.getBean(MaxKeyConfig.class).getPort());
_logger.info("MaxKey started.");
}
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(MaxKeyApplication.class); return application.sources(MaxKeyApplication.class);
} }
} }

View File

@ -18,21 +18,21 @@ import org.springframework.context.annotation.PropertySource;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
@Configuration @Configuration
@ImportResource(locations={"classpath:spring/maxkey.xml"}) @ImportResource(locations = { "classpath:spring/maxkey.xml" })
@PropertySource("classpath:/application.properties") @PropertySource("classpath:/application.properties")
public class MaxKeyConfig { public class MaxKeyConfig {
@Value("${server.port:8080}") @Value("${server.port:8080}")
private int port; private int port;
public int getPort() { public int getPort() {
return port; return port;
} }
public void setPort(int port) { public void setPort(int port) {
this.port = port; this.port = port;
} }
@Bean @Bean
public FilterRegistrationBean<TokenEndpointAuthenticationFilter> TokenEndpointAuthenticationFilter() { public FilterRegistrationBean<TokenEndpointAuthenticationFilter> TokenEndpointAuthenticationFilter() {
FilterRegistrationBean<TokenEndpointAuthenticationFilter> registration = new FilterRegistrationBean<TokenEndpointAuthenticationFilter>(); FilterRegistrationBean<TokenEndpointAuthenticationFilter> registration = new FilterRegistrationBean<TokenEndpointAuthenticationFilter>();
registration.setFilter(new TokenEndpointAuthenticationFilter()); registration.setFilter(new TokenEndpointAuthenticationFilter());
@ -41,52 +41,50 @@ public class MaxKeyConfig {
registration.setOrder(1); registration.setOrder(1);
return registration; return registration;
} }
/** /**
* 配置默认错误页面仅用于内嵌tomcat启动时 * 配置默认错误页面仅用于内嵌tomcat启动时 使用这种方式在打包为war后不起作用
* 使用这种方式在打包为war后不起作用
* *
* @return * @return
*/ */
@Bean @Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() { public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() { return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() {
@Override @Override
public void customize(ConfigurableWebServerFactory factory) { public void customize(ConfigurableWebServerFactory factory) {
ErrorPage errorPage400 = new ErrorPage(HttpStatus.BAD_REQUEST,"/exception/error/400"); ErrorPage errorPage400 = new ErrorPage(HttpStatus.BAD_REQUEST, "/exception/error/400");
ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND,"/exception/error/404"); ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/exception/error/404");
ErrorPage errorPage500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR,"/exception/error/500"); ErrorPage errorPage500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/exception/error/500");
factory.addErrorPages(errorPage400, errorPage404,errorPage500); factory.addErrorPages(errorPage400, errorPage404, errorPage500);
} }
}; };
} }
@Bean
public Connector connector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(80);
connector.setSecure(false);
connector.setRedirectPort(443);
return connector;
}
@Bean @Bean
public TomcatServletWebServerFactory tomcatServletWebServerFactory(Connector connector) { public Connector connector() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() { Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
@Override connector.setScheme("http");
protected void postProcessContext(Context context) { connector.setPort(80);
SecurityConstraint securityConstraint = new SecurityConstraint(); connector.setSecure(false);
securityConstraint.setUserConstraint("CONFIDENTIAL"); connector.setRedirectPort(443);
SecurityCollection collection = new SecurityCollection(); return connector;
collection.addPattern("/*"); }
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint); @Bean
} public TomcatServletWebServerFactory tomcatServletWebServerFactory(Connector connector) {
}; TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
tomcat.addAdditionalTomcatConnectors(connector); @Override
return tomcat; protected void postProcessContext(Context context) {
} SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
};
tomcat.addAdditionalTomcatConnectors(connector);
return tomcat;
}
} }

View File

@ -1,7 +1,6 @@
package org.maxkey.web.contorller; package org.maxkey.web.contorller;
import java.util.List; import java.util.List;
import org.maxkey.constants.OPERATEMESSAGE; import org.maxkey.constants.OPERATEMESSAGE;
import org.maxkey.constants.PROTOCOLS; import org.maxkey.constants.PROTOCOLS;
import org.maxkey.crypto.ReciprocalUtils; import org.maxkey.crypto.ReciprocalUtils;
@ -27,217 +26,233 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
/**
* AppListController.
*
* @author Administrator
*
*/
@Controller @Controller
public class AppListController{ public class AppListController {
final static Logger _logger = LoggerFactory.getLogger(AppListController.class); static final Logger _logger = LoggerFactory.getLogger(AppListController.class);
@Autowired
private UserInfoService userInfoService;
@Autowired
protected JdbcTemplate jdbcTemplate;
@Autowired
MyAppsListService myAppsListService;
@Autowired
AccountsService appUsersService;
@Autowired
AppsService appsService;
@RequestMapping(value={"/appList"})
public ModelAndView appList(@RequestParam(value="gridList",required = false) String gridList) {
ModelAndView modelAndView=new ModelAndView("main/appList");
if(gridList!=null&&!gridList.equals("")){
int intGridList=Integer.parseInt(gridList);
jdbcTemplate.update("UPDATE USERINFO SET GRIDLIST = ? WHERE ID = ?",
intGridList,WebContext.getUserInfo().getId());
WebContext.getUserInfo().setGridList(intGridList);
}
modelAndView.addObject("appList", queryAccessableApps());
return modelAndView;
}
@RequestMapping(value={"/appConfigList"})
public ModelAndView appConfigList() {
ModelAndView modelAndView=new ModelAndView("main/appConfigList");
modelAndView.addObject("appList", queryAccessableApps());
return modelAndView;
}
private List<UserApps> queryAccessableApps(){
UserApps userApplications=new UserApps();
userApplications.setUsername(WebContext.getUserInfo().getUsername());
List<UserApps> appList=myAppsListService.queryMyApps(userApplications);
for (UserApps app : appList){
WebContext.setAttribute(app.getId(), app.getIcon());
}
return appList;
}
@RequestMapping(value={"/forward/appProtectedConfig/{protocol}/{credential}/{appId}"}) @Autowired
public ModelAndView forwardAppLoginConfig( private UserInfoService userInfoService;
@PathVariable("protocol") String protocol,
@PathVariable("credential") int credential,
@PathVariable("appId") String appId){
ModelAndView modelAndView=new ModelAndView("main/appProtectedConfig");
UserInfo userInfo=WebContext.getUserInfo(); @Autowired
protected JdbcTemplate jdbcTemplate;
if(userInfo.getProtectedAppsMap().get(appId)!=null){
modelAndView.addObject("protectedappId",true);
}else{
modelAndView.addObject("protectedappId",false);
}
modelAndView.addObject("uid",userInfo.getId());
modelAndView.addObject("appId",appId);
modelAndView.addObject("protocol",protocol);
modelAndView.addObject("credential",credential);
return modelAndView;
}
@ResponseBody
@RequestMapping(value={"/appProtectedConfig"})
public Message appLoginConfig(
@RequestParam("protocol") String protocol,
@RequestParam("credential") int credential,
@RequestParam("appId") String appId,
@RequestParam("protectedappId") String protectedappId,
@RequestParam("password") String password
){
UserInfo userInfo=WebContext.getUserInfo(); @Autowired
String userAppProtectedPassword=ReciprocalUtils.decoder(userInfo.getAppLoginPassword()); MyAppsListService myAppsListService;
if(userAppProtectedPassword.equals(password)){
@Autowired
if(protectedappId.equalsIgnoreCase("YES")){ AccountsService appUsersService;
if(userInfo.getProtectedApps()!=null&&userInfo.getProtectedApps().indexOf(appId)<0){
userInfo.setProtectedApps(userInfo.getProtectedApps()+","+appId); @Autowired
if(userInfo.getProtectedAppsMap()!=null){ AppsService appsService;
userInfo.getProtectedAppsMap().put(appId, appId);
} /**
}else{ * gridList.
userInfo.setProtectedApps(","+appId); * @param gridList 类型
} * @return
}else{ */
if(userInfo.getProtectedApps()!=null&&userInfo.getProtectedApps().indexOf(appId)>-1){ @RequestMapping(value = { "/appList" })
//userInfo.setSecondProtectedApps(userInfo.getSecondProtectedApps()+","+appId); public ModelAndView appList(
String []protectedApps=userInfo.getProtectedApps().split(","); @RequestParam(value = "gridList", required = false) String gridList) {
String protectedAppIds=""; ModelAndView modelAndView = new ModelAndView("main/appList");
if(userInfo.getProtectedAppsMap()!=null){
userInfo.getProtectedAppsMap().remove(appId); if (gridList != null && !gridList.equals("")) {
} int intGridList = Integer.parseInt(gridList);
for(String protectedAppId:protectedApps){ jdbcTemplate.update("UPDATE USERINFO SET GRIDLIST = ? WHERE ID = ?", intGridList,
if(protectedAppId.equalsIgnoreCase(appId)||protectedAppId.trim().equals(""))continue; WebContext.getUserInfo().getId());
protectedAppIds=protectedAppIds+","+protectedAppId; WebContext.getUserInfo().setGridList(intGridList);
} }
userInfo.setProtectedApps(protectedAppIds); modelAndView.addObject("appList", queryAccessableApps());
} return modelAndView;
} }
userInfoService.updateProtectedApps(userInfo); @RequestMapping(value = { "/appConfigList" })
}else{ public ModelAndView appConfigList() {
return new Message(WebContext.getI18nValue(OPERATEMESSAGE.UPDATE_ERROR),MessageType.error); ModelAndView modelAndView = new ModelAndView("main/appConfigList");
} modelAndView.addObject("appList", queryAccessableApps());
return modelAndView;
return new Message(WebContext.getI18nValue(OPERATEMESSAGE.UPDATE_SUCCESS),MessageType.success); }
}
private List<UserApps> queryAccessableApps() {
UserApps userApplications = new UserApps();
@RequestMapping(value={"/forward/appUserConfig/{protocol}/{credential}/{appId}"}) userApplications.setUsername(WebContext.getUserInfo().getUsername());
public ModelAndView forwardAppUserConfig(
@PathVariable("protocol") String protocol, List<UserApps> appList = myAppsListService.queryMyApps(userApplications);
@PathVariable("credential") int credential, for (UserApps app : appList) {
@PathVariable("appId") String appId){ WebContext.setAttribute(app.getId(), app.getIcon());
ModelAndView modelAndView=new ModelAndView("main/appUserConfig"); }
//modelAndView.addObject("appList",appList);
return appList;
Accounts appUsers=new Accounts(); }
UserInfo userInfo=WebContext.getUserInfo();
if(credential==Apps.CREDENTIALS.USER_DEFINED){ /**
appUsers=appUsersService.load(new Accounts(userInfo.getId(),appId)); * forwardAppLoginConfig.
if(protocol.equalsIgnoreCase(PROTOCOLS.DESKTOP)|| * @param protocol protocol
protocol.equalsIgnoreCase(PROTOCOLS.FORMBASED)|| * @param credential credential
protocol.equalsIgnoreCase(PROTOCOLS.BASIC)|| * @param appId appId
protocol.equalsIgnoreCase(PROTOCOLS.EXTEND_API) * @return
){ */
@RequestMapping(value = { "/forward/appProtectedConfig/{protocol}/{credential}/{appId}" })
modelAndView.addObject("username",true); public ModelAndView forwardAppLoginConfig(@PathVariable("protocol") String protocol,
modelAndView.addObject("password",true); @PathVariable("credential") int credential, @PathVariable("appId") String appId) {
}else if(protocol.equalsIgnoreCase(PROTOCOLS.SAML20) ModelAndView modelAndView = new ModelAndView("main/appProtectedConfig");
){
modelAndView.addObject("username",true); UserInfo userInfo = WebContext.getUserInfo();
modelAndView.addObject("password",false);
}else{ if (userInfo.getProtectedAppsMap().get(appId) != null) {
modelAndView.addObject("username",false); modelAndView.addObject("protectedappId", true);
modelAndView.addObject("password",false); } else {
} modelAndView.addObject("protectedappId", false);
if(appUsers!=null){ }
modelAndView.addObject("identity_username",appUsers.getRelatedUsername()); modelAndView.addObject("uid", userInfo.getId());
modelAndView.addObject("identity_password",ReciprocalUtils.decoder(appUsers.getRelatedPassword())); modelAndView.addObject("appId", appId);
}else{ modelAndView.addObject("protocol", protocol);
modelAndView.addObject("identity_username",""); modelAndView.addObject("credential", credential);
modelAndView.addObject("identity_password",""); return modelAndView;
}
}else{ }
modelAndView.addObject("username",false);
modelAndView.addObject("password",false); /**
} * appLoginConfig.
* @param protocol protocol
modelAndView.addObject("uid",userInfo.getId()); * @param credential credential
modelAndView.addObject("appId",appId); * @param appId appId
modelAndView.addObject("protocol",protocol); * @param protectedappId protectedappId
modelAndView.addObject("credential",credential); * @param password password
return modelAndView; * @return
*/
} @ResponseBody
@RequestMapping(value = { "/appProtectedConfig" })
@ResponseBody public Message appLoginConfig(
@RequestMapping(value={"/appUserConfig"}) @RequestParam("protocol") String protocol,
public Message appUserConfig( @RequestParam("credential") int credential,
@RequestParam("protocol") String protocol, @RequestParam("appId") String appId,
@RequestParam("credential") int credential, @RequestParam("protectedappId") String protectedappId,
@RequestParam("appId") String appId, @RequestParam("password") String password) {
@RequestParam("identity_username") String identity_username,
@RequestParam("identity_password") String identity_password UserInfo userInfo = WebContext.getUserInfo();
){ String userAppProtectedPassword = ReciprocalUtils.decoder(userInfo.getAppLoginPassword());
if (userAppProtectedPassword.equals(password)) {
Apps app=appsService.get(appId);
UserInfo userInfo=WebContext.getUserInfo(); if (protectedappId.equalsIgnoreCase("YES")) {
if (userInfo.getProtectedApps() != null
Accounts appUsers=new Accounts(); && userInfo.getProtectedApps().indexOf(appId) < 0) {
appUsers.setAppId(appId); userInfo.setProtectedApps(userInfo.getProtectedApps() + "," + appId);
appUsers.setUid(userInfo.getId()); if (userInfo.getProtectedAppsMap() != null) {
userInfo.getProtectedAppsMap().put(appId, appId);
if(identity_password!=null&&!identity_password.equals("")&&credential==Apps.CREDENTIALS.USER_DEFINED){ }
appUsers=appUsersService.load(new Accounts(userInfo.getId(),appId)); } else {
if(appUsers==null){ userInfo.setProtectedApps("," + appId);
appUsers=new Accounts(); }
appUsers.setId(appUsers.generateId()); } else {
appUsers.setAppId(appId); if (userInfo.getProtectedApps() != null
appUsers.setAppName(app.getName()); && userInfo.getProtectedApps().indexOf(appId) > -1) {
appUsers.setUid(userInfo.getId()); // userInfo.setSecondProtectedApps(userInfo.getSecondProtectedApps()+","+appId);
appUsers.setUsername(userInfo.getUsername()); String[] protectedApps = userInfo.getProtectedApps().split(",");
appUsers.setDisplayName(userInfo.getDisplayName()); String protectedAppIds = "";
if (userInfo.getProtectedAppsMap() != null) {
appUsers.setRelatedUsername(identity_username); userInfo.getProtectedAppsMap().remove(appId);
appUsers.setRelatedPassword(ReciprocalUtils.encode(identity_password)); }
appUsersService.insert(appUsers); for (String protectedAppId : protectedApps) {
}else{ if (protectedAppId.equalsIgnoreCase(appId)
appUsers.setRelatedUsername(identity_username); || protectedAppId.trim().equals("")) {
appUsers.setRelatedPassword(ReciprocalUtils.encode(identity_password)); continue;
appUsersService.update(appUsers); }
} protectedAppIds = protectedAppIds + "," + protectedAppId;
} }
userInfo.setProtectedApps(protectedAppIds);
return new Message(WebContext.getI18nValue(OPERATEMESSAGE.UPDATE_SUCCESS),MessageType.success); }
} }
userInfoService.updateProtectedApps(userInfo);
} else {
return new Message(WebContext.getI18nValue(OPERATEMESSAGE.UPDATE_ERROR), MessageType.error);
}
return new Message(WebContext.getI18nValue(OPERATEMESSAGE.UPDATE_SUCCESS), MessageType.success);
}
@RequestMapping(value = { "/forward/appUserConfig/{protocol}/{credential}/{appId}" })
public ModelAndView forwardAppUserConfig(@PathVariable("protocol") String protocol,
@PathVariable("credential") int credential, @PathVariable("appId") String appId) {
ModelAndView modelAndView = new ModelAndView("main/appUserConfig");
// modelAndView.addObject("appList",appList);
Accounts appUsers = new Accounts();
UserInfo userInfo = WebContext.getUserInfo();
if (credential == Apps.CREDENTIALS.USER_DEFINED) {
appUsers = appUsersService.load(new Accounts(userInfo.getId(), appId));
if (protocol.equalsIgnoreCase(PROTOCOLS.DESKTOP) || protocol.equalsIgnoreCase(PROTOCOLS.FORMBASED)
|| protocol.equalsIgnoreCase(PROTOCOLS.BASIC) || protocol.equalsIgnoreCase(PROTOCOLS.EXTEND_API)) {
modelAndView.addObject("username", true);
modelAndView.addObject("password", true);
} else if (protocol.equalsIgnoreCase(PROTOCOLS.SAML20)) {
modelAndView.addObject("username", true);
modelAndView.addObject("password", false);
} else {
modelAndView.addObject("username", false);
modelAndView.addObject("password", false);
}
if (appUsers != null) {
modelAndView.addObject("identity_username", appUsers.getRelatedUsername());
modelAndView.addObject("identity_password", ReciprocalUtils.decoder(appUsers.getRelatedPassword()));
} else {
modelAndView.addObject("identity_username", "");
modelAndView.addObject("identity_password", "");
}
} else {
modelAndView.addObject("username", false);
modelAndView.addObject("password", false);
}
modelAndView.addObject("uid", userInfo.getId());
modelAndView.addObject("appId", appId);
modelAndView.addObject("protocol", protocol);
modelAndView.addObject("credential", credential);
return modelAndView;
}
@ResponseBody
@RequestMapping(value = { "/appUserConfig" })
public Message appUserConfig(@RequestParam("protocol") String protocol, @RequestParam("credential") int credential,
@RequestParam("appId") String appId, @RequestParam("identity_username") String identity_username,
@RequestParam("identity_password") String identity_password) {
Apps app = appsService.get(appId);
UserInfo userInfo = WebContext.getUserInfo();
Accounts appUsers = new Accounts();
appUsers.setAppId(appId);
appUsers.setUid(userInfo.getId());
if (identity_password != null && !identity_password.equals("") && credential == Apps.CREDENTIALS.USER_DEFINED) {
appUsers = appUsersService.load(new Accounts(userInfo.getId(), appId));
if (appUsers == null) {
appUsers = new Accounts();
appUsers.setId(appUsers.generateId());
appUsers.setAppId(appId);
appUsers.setAppName(app.getName());
appUsers.setUid(userInfo.getId());
appUsers.setUsername(userInfo.getUsername());
appUsers.setDisplayName(userInfo.getDisplayName());
appUsers.setRelatedUsername(identity_username);
appUsers.setRelatedPassword(ReciprocalUtils.encode(identity_password));
appUsersService.insert(appUsers);
} else {
appUsers.setRelatedUsername(identity_username);
appUsers.setRelatedPassword(ReciprocalUtils.encode(identity_password));
appUsersService.update(appUsers);
}
}
return new Message(WebContext.getI18nValue(OPERATEMESSAGE.UPDATE_SUCCESS), MessageType.success);
}
} }

View File

@ -19,120 +19,119 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
@Controller @Controller
@RequestMapping(value={"/forgotpassword"}) @RequestMapping(value = { "/forgotpassword" })
public class ForgotPasswordContorller { public class ForgotPasswordContorller {
private static Logger _logger = LoggerFactory.getLogger(ForgotPasswordContorller.class); private static Logger _logger = LoggerFactory.getLogger(ForgotPasswordContorller.class);
@Autowired @Autowired
ForgotPasswordService forgotPasswordService; ForgotPasswordService forgotPasswordService;
@Autowired @Autowired
private UserInfoService userInfoService; private UserInfoService userInfoService;
@Autowired @Autowired
protected ApplicationConfig applicationConfig; protected ApplicationConfig applicationConfig;
@Autowired @Autowired
private PasswordEncoder passwordEncoder; private PasswordEncoder passwordEncoder;
@RequestMapping(value = { "/forward" })
@RequestMapping(value={"/forward"}) public ModelAndView forwardreg() {
public ModelAndView forwardreg() { _logger.debug("Registration /forgotpassword/forward.");
_logger.debug("Registration /forgotpassword/forward."); return new ModelAndView("forgotpassword/forward");
return new ModelAndView("forgotpassword/forward"); }
}
@RequestMapping(value = { "/email" })
public ModelAndView email(@RequestParam String email) {
@RequestMapping(value={"/email"}) _logger.debug("Registration /forgotpassword/email.");
public ModelAndView email(@RequestParam String email) { _logger.debug("email : " + email);
_logger.debug("Registration /forgotpassword/email."); UserInfo userInfo = forgotPasswordService.queryUserInfoByEmail(email);
_logger.debug("email : "+email); ModelAndView modelAndView = new ModelAndView("forgotpassword/email");
UserInfo userInfo=forgotPasswordService.queryUserInfoByEmail(email); modelAndView.addObject("emailsend", 0);
ModelAndView modelAndView=new ModelAndView("forgotpassword/email"); modelAndView.addObject("email", email);
modelAndView.addObject("emailsend", 0);
modelAndView.addObject("email", email); if (userInfo != null) {
ForgotPassword forgotPassword = new ForgotPassword();
if(userInfo!=null){ forgotPassword.setId(forgotPassword.generateId());
ForgotPassword forgotPassword =new ForgotPassword(); forgotPassword.setEmail(email);
forgotPassword.setId(forgotPassword.generateId()); forgotPassword.setUid(userInfo.getId());
forgotPassword.setEmail(email); forgotPassword.setUsername(userInfo.getUsername());
forgotPassword.setUid(userInfo.getId()); forgotPasswordService.insert(forgotPassword);
forgotPassword.setUsername(userInfo.getUsername());
forgotPasswordService.insert(forgotPassword); HtmlEmail hemail = new HtmlEmail();
HtmlEmail hemail = new HtmlEmail(); try {
hemail.setHostName(applicationConfig.getEmailConfig().getSmtpHost());
try { hemail.setSmtpPort(applicationConfig.getEmailConfig().getPort());
hemail.setHostName(applicationConfig.getEmailConfig().getSmtpHost()); hemail.setAuthenticator(new DefaultAuthenticator(applicationConfig.getEmailConfig().getUsername(),
hemail.setSmtpPort(applicationConfig.getEmailConfig().getPort()); applicationConfig.getEmailConfig().getPassword()));
hemail.setAuthenticator(new DefaultAuthenticator(applicationConfig.getEmailConfig().getUsername(), applicationConfig.getEmailConfig().getPassword()));
hemail.addTo(userInfo.getEmail(), userInfo.getNickName());
hemail.addTo(userInfo.getEmail(), userInfo.getNickName()); hemail.setFrom(applicationConfig.getEmailConfig().getSenderMail(), "ConnSec");
hemail.setFrom(applicationConfig.getEmailConfig().getSenderMail(), "ConnSec"); hemail.setSubject("ConnSec Cloud Identity & Access ReSet Password .");
hemail.setSubject("ConnSec Cloud Identity & Access ReSet Password .");
// set the html message
// set the html message String forgotPasswordUrl = WebContext.getHttpContextPath() + "/forgotpassword/resetpwd/"
String forgotPasswordUrl=WebContext.getHttpContextPath()+"/forgotpassword/resetpwd/"+forgotPassword.getId(); + forgotPassword.getId();
// set the html message
// set the html message String emailText = "<html>";
String emailText="<html>"; emailText += "<a href='" + forgotPasswordUrl + "'>Reset Password</a><br>";
emailText+="<a href='"+forgotPasswordUrl+"'>Reset Password</a><br>"; emailText += " or copy " + forgotPasswordUrl + " to brower.";
emailText+=" or copy "+forgotPasswordUrl+" to brower."; emailText += "</html>";
emailText+="</html>";
hemail.setHtmlMsg(emailText);
hemail.setHtmlMsg(emailText);
// set the alternative message
// set the alternative message hemail.setTextMsg("Your email client does not support HTML messages");
hemail.setTextMsg("Your email client does not support HTML messages");
// send the email
// send the email hemail.send();
hemail.send(); modelAndView.addObject("emailsend", 1);
modelAndView.addObject("emailsend", 1); } catch (EmailException e) {
} catch (EmailException e) { // TODO Auto-generated catch block
// TODO Auto-generated catch block e.printStackTrace();
e.printStackTrace(); }
} }
} return modelAndView;
return modelAndView ; }
}
@RequestMapping(value = { "/resetpwd/{id}" })
@RequestMapping(value={"/resetpwd/{id}"}) public ModelAndView resetpwd(@PathVariable("id") String id) {
public ModelAndView resetpwd(@PathVariable("id") String id) { _logger.debug("Registration /forgotpassword/resetpwd.");
_logger.debug("Registration /forgotpassword/resetpwd."); ForgotPassword forgotPassword = forgotPasswordService.get(id);
ForgotPassword forgotPassword=forgotPasswordService.get(id); ModelAndView mav = new ModelAndView("forgotpassword/resetpwd");
ModelAndView mav=new ModelAndView("forgotpassword/resetpwd"); if (forgotPassword != null) {
if(forgotPassword!=null){ mav.addObject("model", forgotPassword);
mav.addObject("model", forgotPassword); }
}
return mav;
return mav; }
}
@RequestMapping(value = { "/setpassword/{id}" })
@RequestMapping(value={"/setpassword/{id}"}) public ModelAndView setPassWord(@PathVariable("id") String id, @RequestParam String password,
public ModelAndView setPassWord(@PathVariable("id") String id,@RequestParam String password,@RequestParam String confirmpassword) { @RequestParam String confirmpassword) {
_logger.debug("forgotPassword /forgotPassword/pwdreseted."); _logger.debug("forgotPassword /forgotPassword/pwdreseted.");
ModelAndView modelAndView=new ModelAndView("forgotpassword/pwdreseted"); ModelAndView modelAndView = new ModelAndView("forgotpassword/pwdreseted");
if(password.equals(confirmpassword)){ if (password.equals(confirmpassword)) {
ForgotPassword forgotPassword=forgotPasswordService.get(id); ForgotPassword forgotPassword = forgotPasswordService.get(id);
if(forgotPassword!=null){ if (forgotPassword != null) {
UserInfo userInfo=new UserInfo(); UserInfo userInfo = new UserInfo();
userInfo.setId(forgotPassword.getUid()); userInfo.setId(forgotPassword.getUid());
userInfo.setPassword(password); userInfo.setPassword(password);
userInfo.setDecipherable(password); userInfo.setDecipherable(password);
userInfo.setUsername(forgotPassword.getUsername()); userInfo.setUsername(forgotPassword.getUsername());
userInfoService.changePassword(userInfo); userInfoService.changePassword(userInfo);
forgotPasswordService.remove(id); forgotPasswordService.remove(id);
modelAndView.addObject("pwdreseted", 1); modelAndView.addObject("pwdreseted", 1);
}else{ } else {
modelAndView.addObject("pwdreseted", 2); modelAndView.addObject("pwdreseted", 2);
} }
}else{ } else {
modelAndView.addObject("pwdreseted", 0); modelAndView.addObject("pwdreseted", 0);
} }
return modelAndView; return modelAndView;
} }
} }

View File

@ -2,13 +2,12 @@ package org.maxkey.web.contorller;
import java.text.SimpleDateFormat; 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.dao.service.HistoryLoginAppsService; import org.maxkey.dao.service.HistoryLoginAppsService;
import org.maxkey.dao.service.HistoryLoginService; import org.maxkey.dao.service.HistoryLoginService;
import org.maxkey.dao.service.HistoryLogsService; import org.maxkey.dao.service.HistoryLogsService;
import org.maxkey.domain.HistoryLoginApps;
import org.maxkey.domain.HistoryLogin; import org.maxkey.domain.HistoryLogin;
import org.maxkey.domain.HistoryLoginApps;
import org.maxkey.domain.HistoryLogs; import org.maxkey.domain.HistoryLogs;
import org.maxkey.util.DateUtils; import org.maxkey.util.DateUtils;
import org.maxkey.web.WebContext; import org.maxkey.web.WebContext;
@ -24,89 +23,89 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
/** /**
* 登录日志和操作日志查询 * 登录日志和操作日志查询.
* *
* @author Crystal.sea * @author Crystal.sea
* *
*/ */
@Controller @Controller
@RequestMapping(value={"/historys"}) @RequestMapping(value = { "/historys" })
public class HistorysController { public class HistorysController {
final static Logger _logger = LoggerFactory.getLogger(HistorysController.class); static final Logger _logger = LoggerFactory.getLogger(HistorysController.class);
@Autowired
HistoryLoginService historyLoginService;
@Autowired
protected HistoryLoginAppsService historyLoginAppsService;
@Autowired
HistoryLogsService historyLogsService;
@RequestMapping(value={"/logs"})
public String List(){
return "historys/logsList";
}
/**
* 查询操作日志
* @param logs
* @return
*/
@RequestMapping(value={"/logs/grid"})
@ResponseBody
public JpaPageResults<HistoryLogs> logsDataGrid(@ModelAttribute("historyLogs") HistoryLogs historyLogs){
_logger.debug("history/logs/grid/ logsGrid() "+historyLogs);
return historyLogsService.queryPageResults(historyLogs);
}
@RequestMapping(value={"/login"}) @Autowired
public String authList(){ HistoryLoginService historyLoginService;
return "historys/loginList";
}
/**
* 查询登录日志
* @param logsAuth
* @return
*/
@RequestMapping(value={"/login/grid"})
@ResponseBody
public JpaPageResults<HistoryLogin> logAuthsGrid(@ModelAttribute("historyLogin") HistoryLogin historyLogin){
_logger.debug("history/login/grid/ logsGrid() "+historyLogin);
historyLogin.setUid(WebContext.getUserInfo().getId());
return historyLoginService.queryPageResults(historyLogin);
}
@RequestMapping(value={"/loginApps"}) @Autowired
public String loginAppHistoryList(){ protected HistoryLoginAppsService historyLoginAppsService;
return "historys/loginAppsList";
}
/**
* 查询单点登录日志
* @param logsSso
* @return
*/
@RequestMapping(value={"/loginApps/grid"})
@ResponseBody
public JpaPageResults<HistoryLoginApps> logsSsoGrid(@ModelAttribute("historyLoginApps") HistoryLoginApps historyLoginApps){
_logger.debug("history/loginApps/grid/ logsGrid() "+historyLoginApps);
historyLoginApps.setId(null);
return historyLoginAppsService.queryPageResults(historyLoginApps);
} @Autowired
HistoryLogsService historyLogsService;
@RequestMapping(value = { "/logs" })
public String List() {
return "historys/logsList";
}
@InitBinder /**
* 查询操作日志.
*
* @param logs
* @return
*/
@RequestMapping(value = { "/logs/grid" })
@ResponseBody
public JpaPageResults<HistoryLogs> logsDataGrid(@ModelAttribute("historyLogs") HistoryLogs historyLogs) {
_logger.debug("history/logs/grid/ logsGrid() " + historyLogs);
return historyLogsService.queryPageResults(historyLogs);
}
@RequestMapping(value = { "/login" })
public String authList() {
return "historys/loginList";
}
/**
* 查询登录日志.
*
* @param logsAuth
* @return
*/
@RequestMapping(value = { "/login/grid" })
@ResponseBody
public JpaPageResults<HistoryLogin> logAuthsGrid(@ModelAttribute("historyLogin") HistoryLogin historyLogin) {
_logger.debug("history/login/grid/ logsGrid() " + historyLogin);
historyLogin.setUid(WebContext.getUserInfo().getId());
return historyLoginService.queryPageResults(historyLogin);
}
@RequestMapping(value = { "/loginApps" })
public String loginAppHistoryList() {
return "historys/loginAppsList";
}
/**
* 查询单点登录日志.
*
* @param logsSso
* @return
*/
@RequestMapping(value = { "/loginApps/grid" })
@ResponseBody
public JpaPageResults<HistoryLoginApps> logsSsoGrid(
@ModelAttribute("historyLoginApps") HistoryLoginApps historyLoginApps) {
_logger.debug("history/loginApps/grid/ logsGrid() " + historyLoginApps);
historyLoginApps.setId(null);
return historyLoginAppsService.queryPageResults(historyLoginApps);
}
@InitBinder
public void initBinder(WebDataBinder binder) { public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat(DateUtils.FORMAT_DATE_HH_MM_SS); SimpleDateFormat dateFormat = new SimpleDateFormat(DateUtils.FORMAT_DATE_HH_MM_SS);
dateFormat.setLenient(false); dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
} }
} }

View File

@ -2,7 +2,6 @@ package org.maxkey.web.contorller;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.util.UUID; import java.util.UUID;
import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.binary.Hex;
import org.maxkey.crypto.Base32Utils; import org.maxkey.crypto.Base32Utils;
import org.maxkey.crypto.password.PasswordReciprocal; import org.maxkey.crypto.password.PasswordReciprocal;
@ -11,8 +10,8 @@ import org.maxkey.crypto.password.opt.algorithm.OTPSecret;
import org.maxkey.dao.service.UserInfoService; import org.maxkey.dao.service.UserInfoService;
import org.maxkey.domain.UserInfo; import org.maxkey.domain.UserInfo;
import org.maxkey.util.RQCodeUtils; import org.maxkey.util.RQCodeUtils;
import org.maxkey.web.WebContext;
import org.maxkey.web.ImageEndpoint; import org.maxkey.web.ImageEndpoint;
import org.maxkey.web.WebContext;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -23,127 +22,128 @@ import org.springframework.web.servlet.ModelAndView;
/** /**
* .
* @author Crystal.Sea * @author Crystal.Sea
* *
*/ */
@Controller @Controller
@RequestMapping(value = { "/safe/otp" }) @RequestMapping(value = { "/safe/otp" })
public class OneTimePasswordController { public class OneTimePasswordController {
final static Logger _logger = LoggerFactory.getLogger(OneTimePasswordController.class); static final Logger _logger = LoggerFactory.getLogger(OneTimePasswordController.class);
@Autowired @Autowired
@Qualifier("userInfoService") @Qualifier("userInfoService")
private UserInfoService userInfoService; private UserInfoService userInfoService;
@Autowired
@Qualifier("keyUriFormat")
KeyUriFormat keyUriFormat;
@Autowired @Autowired
@Qualifier("passwordReciprocal") @Qualifier("keyUriFormat")
PasswordReciprocal passwordReciprocal; KeyUriFormat keyUriFormat;
@RequestMapping(value={"/timebased"})
public ModelAndView timebased(){
ModelAndView modelAndView=new ModelAndView("safe/timeBased");
UserInfo userInfo=WebContext.getUserInfo();
String sharedSecret=passwordReciprocal.decoder(userInfo.getSharedSecret());
keyUriFormat.setSecret(sharedSecret);
String otpauth=keyUriFormat.format(userInfo.getUsername());
byte[] byteSharedSecret=Base32Utils.decode(sharedSecret);
String hexSharedSecret=Hex.encodeHexString(byteSharedSecret);
modelAndView.addObject("id", genRQCode(otpauth));
modelAndView.addObject("userInfo", userInfo);
modelAndView.addObject("format", keyUriFormat);
modelAndView.addObject("sharedSecret", sharedSecret);
modelAndView.addObject("hexSharedSecret", hexSharedSecret);
return modelAndView;
}
@RequestMapping(value={"gen/timebased"})
public ModelAndView gentimebased(){
UserInfo userInfo=WebContext.getUserInfo();
byte[] byteSharedSecret=OTPSecret.generate(keyUriFormat.getCrypto());
String sharedSecret=Base32Utils.encode(byteSharedSecret);
sharedSecret=passwordReciprocal.encode(sharedSecret);
userInfo.setSharedSecret(sharedSecret);
userInfoService.changeSharedSecret(userInfo);
WebContext.setUserInfo(userInfo);
return WebContext.redirect("/safe/otp/timebased");
}
@RequestMapping(value={"/counterbased"}) @Autowired
public ModelAndView counterbased(){ @Qualifier("passwordReciprocal")
ModelAndView modelAndView=new ModelAndView("safe/counterBased"); PasswordReciprocal passwordReciprocal;
UserInfo userInfo=WebContext.getUserInfo();
String sharedSecret=passwordReciprocal.decoder(userInfo.getSharedSecret());
keyUriFormat.setSecret(sharedSecret);
keyUriFormat.setCounter(Long.parseLong(userInfo.getSharedCounter()));
String otpauth=keyUriFormat.format(userInfo.getUsername());
byte[] byteSharedSecret=Base32Utils.decode(sharedSecret);
String hexSharedSecret=Hex.encodeHexString(byteSharedSecret);
modelAndView.addObject("id", genRQCode(otpauth));
modelAndView.addObject("userInfo", userInfo);
modelAndView.addObject("format", keyUriFormat);
modelAndView.addObject("sharedSecret", sharedSecret);
modelAndView.addObject("hexSharedSecret", hexSharedSecret);
return modelAndView;
}
@RequestMapping(value={"gen/counterbased"})
public ModelAndView gencounterbased(){
UserInfo userInfo=WebContext.getUserInfo();
byte[] byteSharedSecret=OTPSecret.generate(keyUriFormat.getCrypto());
String sharedSecret=Base32Utils.encode(byteSharedSecret);
sharedSecret=passwordReciprocal.encode(sharedSecret);
userInfo.setSharedSecret(sharedSecret);
userInfo.setSharedCounter("0");
userInfoService.changeSharedSecret(userInfo);
WebContext.setUserInfo(userInfo);
return WebContext.redirect("/safe/otp/counterbased");
}
@RequestMapping(value={"/hotp"}) @RequestMapping(value = {"/timebased"})
public ModelAndView hotp(){ public ModelAndView timebased() {
ModelAndView modelAndView=new ModelAndView("safe/hotp"); ModelAndView modelAndView = new ModelAndView("safe/timeBased");
UserInfo userInfo=WebContext.getUserInfo(); UserInfo userInfo = WebContext.getUserInfo();
String sharedSecret=passwordReciprocal.decoder(userInfo.getSharedSecret()); String sharedSecret = passwordReciprocal.decoder(userInfo.getSharedSecret());
keyUriFormat.setSecret(sharedSecret); keyUriFormat.setSecret(sharedSecret);
keyUriFormat.setCounter(Long.parseLong(userInfo.getSharedCounter())); String otpauth = keyUriFormat.format(userInfo.getUsername());
String otpauth=keyUriFormat.format(userInfo.getUsername()); byte[] byteSharedSecret = Base32Utils.decode(sharedSecret);
byte[] byteSharedSecret=Base32Utils.decode(sharedSecret); String hexSharedSecret = Hex.encodeHexString(byteSharedSecret);
String hexSharedSecret=Hex.encodeHexString(byteSharedSecret); modelAndView.addObject("id", genRqCode(otpauth));
modelAndView.addObject("id", genRQCode(otpauth)); modelAndView.addObject("userInfo", userInfo);
modelAndView.addObject("userInfo", userInfo); modelAndView.addObject("format", keyUriFormat);
modelAndView.addObject("format", keyUriFormat); modelAndView.addObject("sharedSecret", sharedSecret);
modelAndView.addObject("sharedSecret", sharedSecret); modelAndView.addObject("hexSharedSecret", hexSharedSecret);
modelAndView.addObject("hexSharedSecret", hexSharedSecret); return modelAndView;
return modelAndView; }
} @RequestMapping(value = {"gen/timebased"})
public ModelAndView gentimebased() {
@RequestMapping(value={"gen/hotp"}) UserInfo userInfo = WebContext.getUserInfo();
public ModelAndView genhotp(){ byte[] byteSharedSecret = OTPSecret.generate(keyUriFormat.getCrypto());
UserInfo userInfo=WebContext.getUserInfo(); String sharedSecret = Base32Utils.encode(byteSharedSecret);
byte[] byteSharedSecret=OTPSecret.generate(keyUriFormat.getCrypto()); sharedSecret = passwordReciprocal.encode(sharedSecret);
String sharedSecret=Base32Utils.encode(byteSharedSecret); userInfo.setSharedSecret(sharedSecret);
sharedSecret=passwordReciprocal.encode(sharedSecret); userInfoService.changeSharedSecret(userInfo);
userInfo.setSharedSecret(sharedSecret); WebContext.setUserInfo(userInfo);
userInfo.setSharedCounter("0"); return WebContext.redirect("/safe/otp/timebased");
userInfoService.changeSharedSecret(userInfo); }
WebContext.setUserInfo(userInfo);
return WebContext.redirect("/safe/otp/hotp");
} @RequestMapping(value = {"/counterbased"})
public ModelAndView counterbased() {
ModelAndView modelAndView = new ModelAndView("safe/counterBased");
public String genRQCode(String otpauth){ UserInfo userInfo = WebContext.getUserInfo();
BufferedImage bufferedImage = RQCodeUtils.write2BufferedImage(otpauth, "gif", 300, 300); String sharedSecret = passwordReciprocal.decoder(userInfo.getSharedSecret());
byte[] imageByte=ImageEndpoint.bufferedImage2Byte(bufferedImage); keyUriFormat.setSecret(sharedSecret);
String uuid=UUID.randomUUID().toString().toLowerCase(); keyUriFormat.setCounter(Long.parseLong(userInfo.getSharedCounter()));
WebContext.getSession().setAttribute(uuid, imageByte); String otpauth = keyUriFormat.format(userInfo.getUsername());
return uuid;
} byte[] byteSharedSecret = Base32Utils.decode(sharedSecret);
String hexSharedSecret = Hex.encodeHexString(byteSharedSecret);
modelAndView.addObject("id", genRqCode(otpauth));
modelAndView.addObject("userInfo", userInfo);
modelAndView.addObject("format", keyUriFormat);
modelAndView.addObject("sharedSecret", sharedSecret);
modelAndView.addObject("hexSharedSecret", hexSharedSecret);
return modelAndView;
}
@RequestMapping(value = {"gen/counterbased"})
public ModelAndView gencounterbased() {
UserInfo userInfo = WebContext.getUserInfo();
byte[] byteSharedSecret = OTPSecret.generate(keyUriFormat.getCrypto());
String sharedSecret = Base32Utils.encode(byteSharedSecret);
sharedSecret = passwordReciprocal.encode(sharedSecret);
userInfo.setSharedSecret(sharedSecret);
userInfo.setSharedCounter("0");
userInfoService.changeSharedSecret(userInfo);
WebContext.setUserInfo(userInfo);
return WebContext.redirect("/safe/otp/counterbased");
}
@RequestMapping(value = {"/hotp"})
public ModelAndView hotp() {
ModelAndView modelAndView = new ModelAndView("safe/hotp");
UserInfo userInfo = WebContext.getUserInfo();
String sharedSecret = passwordReciprocal.decoder(userInfo.getSharedSecret());
keyUriFormat.setSecret(sharedSecret);
keyUriFormat.setCounter(Long.parseLong(userInfo.getSharedCounter()));
String otpauth = keyUriFormat.format(userInfo.getUsername());
byte[] byteSharedSecret = Base32Utils.decode(sharedSecret);
String hexSharedSecret = Hex.encodeHexString(byteSharedSecret);
modelAndView.addObject("id", genRqCode(otpauth));
modelAndView.addObject("userInfo", userInfo);
modelAndView.addObject("format", keyUriFormat);
modelAndView.addObject("sharedSecret", sharedSecret);
modelAndView.addObject("hexSharedSecret", hexSharedSecret);
return modelAndView;
}
@RequestMapping(value = {"gen/hotp"})
public ModelAndView genhotp() {
UserInfo userInfo = WebContext.getUserInfo();
byte[] byteSharedSecret = OTPSecret.generate(keyUriFormat.getCrypto());
String sharedSecret = Base32Utils.encode(byteSharedSecret);
sharedSecret = passwordReciprocal.encode(sharedSecret);
userInfo.setSharedSecret(sharedSecret);
userInfo.setSharedCounter("0");
userInfoService.changeSharedSecret(userInfo);
WebContext.setUserInfo(userInfo);
return WebContext.redirect("/safe/otp/hotp");
}
public String genRqCode(String otpauth) {
BufferedImage bufferedImage = RQCodeUtils.write2BufferedImage(otpauth, "gif", 300, 300);
byte[] imageByte = ImageEndpoint.bufferedImage2Byte(bufferedImage);
String uuid = UUID.randomUUID().toString().toLowerCase();
WebContext.getSession().setAttribute(uuid, imageByte);
return uuid;
}
} }

View File

@ -1,7 +1,6 @@
package org.maxkey.web.contorller; package org.maxkey.web.contorller;
import javax.validation.Valid; import javax.validation.Valid;
import org.maxkey.constants.OPERATEMESSAGE; import org.maxkey.constants.OPERATEMESSAGE;
import org.maxkey.dao.service.MyProfileService; import org.maxkey.dao.service.MyProfileService;
import org.maxkey.dao.service.UserInfoService; import org.maxkey.dao.service.UserInfoService;
@ -20,45 +19,45 @@ import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
@Controller @Controller
@RequestMapping(value={"/profile"}) @RequestMapping(value = { "/profile" })
public class ProfileController { public class ProfileController {
final static Logger _logger = LoggerFactory.getLogger(ProfileController.class); static final Logger _logger = LoggerFactory.getLogger(ProfileController.class);
@Autowired @Autowired
private UserInfoService userInfoService; private UserInfoService userInfoService;
@Autowired @Autowired
private MyProfileService myProfileService; private MyProfileService myProfileService;
@RequestMapping(value = { "/myProfile" })
@RequestMapping(value={"/myProfile"}) public ModelAndView forwardBasic() {
public ModelAndView forwardBasic(){ ModelAndView modelAndView = new ModelAndView("profile/myProfile");
ModelAndView modelAndView=new ModelAndView("profile/myProfile"); UserInfo userInfo = userInfoService.loadByUsername(WebContext.getUserInfo().getUsername());
UserInfo userInfo=userInfoService.loadByUsername(WebContext.getUserInfo().getUsername()); WebContext.getSession().setAttribute(userInfo.getId(), userInfo.getPicture());
WebContext.getSession().setAttribute(userInfo.getId(), userInfo.getPicture());
// HashMap<String,Object>extraAttributeMap=new HashMap<String,Object>();
// HashMap<String,Object>extraAttributeMap=new HashMap<String,Object>(); // extraAttributeMap=(HashMap<String,Object>)JsonUtils.json2Object(userInfo.getExtraAttribute(),extraAttributeMap);
// extraAttributeMap=(HashMap<String,Object>)JsonUtils.json2Object(userInfo.getExtraAttribute(),extraAttributeMap); // modelAndView.addObject("extraAttributeMap", extraAttributeMap);
// modelAndView.addObject("extraAttributeMap", extraAttributeMap); // _logger.info("extraAttributeMap : "+extraAttributeMap);
// _logger.info("extraAttributeMap : "+extraAttributeMap); //
modelAndView.addObject("model", userInfo);
modelAndView.addObject("model", userInfo); return modelAndView;
return modelAndView; }
}
/**
* 修改用户.
/** *
* 修改用户 * @param userInfo
* @param userInfo * @param result
* @param result * @return
* @return */
*/ @RequestMapping(value = "/update/myProfile")
@RequestMapping(value="/update/myProfile") public ModelAndView updatebasic(
public ModelAndView updatebasic(@Valid @ModelAttribute("userInfo")UserInfo userInfo,BindingResult result) { @Valid @ModelAttribute("userInfo") UserInfo userInfo,
_logger.debug(userInfo.toString()); BindingResult result) {
_logger.debug(userInfo.toString());
// if(userInfo.getExtraAttributeValue()!=null){ // if(userInfo.getExtraAttributeValue()!=null){
// String []extraAttributeLabel=userInfo.getExtraAttributeName().split(","); // String []extraAttributeLabel=userInfo.getExtraAttributeName().split(",");
// String []extraAttributeValue=userInfo.getExtraAttributeValue().split(","); // String []extraAttributeValue=userInfo.getExtraAttributeValue().split(",");
@ -69,16 +68,19 @@ public class ProfileController {
// String extraAttribute=JsonUtils.object2Json(extraAttributeMap); // String extraAttribute=JsonUtils.object2Json(extraAttributeMap);
// userInfo.setExtraAttribute(extraAttribute); // userInfo.setExtraAttribute(extraAttribute);
// } // }
if(myProfileService.updateProfile(userInfo)>0) { if (myProfileService.updateProfile(userInfo) > 0) {
new Message(WebContext.getI18nValue(OPERATEMESSAGE.UPDATE_SUCCESS),userInfo,MessageType.success,OperateType.add,MessageScope.DB); new Message(
WebContext.getI18nValue(OPERATEMESSAGE.UPDATE_SUCCESS),
}else{ userInfo, MessageType.success,
new Message(WebContext.getI18nValue(OPERATEMESSAGE.UPDATE_ERROR),MessageType.error); OperateType.add, MessageScope.DB);
}
} else {
return WebContext.forward("forwardMyProfile"); new Message(WebContext.getI18nValue(OPERATEMESSAGE.UPDATE_ERROR), MessageType.error);
}
}
return WebContext.forward("forwardMyProfile");
}
} }

View File

@ -1,7 +1,6 @@
package org.maxkey.web.filter; package org.maxkey.web.filter;
import java.io.IOException; import java.io.IOException;
import javax.servlet.Filter; import javax.servlet.Filter;
import javax.servlet.FilterChain; import javax.servlet.FilterChain;
import javax.servlet.FilterConfig; import javax.servlet.FilterConfig;
@ -12,7 +11,6 @@ import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
import org.maxkey.config.ApplicationConfig; import org.maxkey.config.ApplicationConfig;
import org.maxkey.domain.IpAddrFilter; import org.maxkey.domain.IpAddrFilter;
import org.maxkey.web.WebContext; import org.maxkey.web.WebContext;
@ -24,58 +22,59 @@ import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.context.support.WebApplicationContextUtils;
public class IpAddressFilter implements Filter { public class IpAddressFilter implements Filter {
private static final Logger _logger = LoggerFactory.getLogger(IpAddressFilter.class); private static final Logger _logger = LoggerFactory.getLogger(IpAddressFilter.class);
@Autowired
@Qualifier("applicationConfig")
private ApplicationConfig applicationConfig;
boolean whiteList=false;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
@Override @Autowired
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) @Qualifier("applicationConfig")
throws IOException, ServletException { private ApplicationConfig applicationConfig;
if(applicationConfig==null){
_logger.info("applicationConfig init .");
applicationConfig=WebApplicationContextUtils.getWebApplicationContext(request.getServletContext()).getBean("applicationConfig", ApplicationConfig.class);
}
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
HttpSession session = httpServletRequest.getSession();
String ipAddress=WebContext.getRequestIpAddress(httpServletRequest);
_logger.trace("IpAddress "+ipAddress);
//黑名单地址
if(IpAddressCache.ipAddressBlackListMap.containsKey(ipAddress)){
IpAddrFilter ipAddrFilter=IpAddressCache.ipAddressBlackListMap.get(ipAddress);
_logger.info("You IpAddress in Black List "+ipAddrFilter);
RequestDispatcher dispatcher = request.getRequestDispatcher("/accessdeny");
dispatcher.forward(request, response);
return ;
} boolean whiteList = false;
//白名单地址
if(whiteList&&!IpAddressCache.ipAddressWhiteListMap.containsKey(ipAddress)){
_logger.info("You IpAddress not in White List "+ipAddress);
RequestDispatcher dispatcher = request.getRequestDispatcher("/accessdeny");
dispatcher.forward(request, response);
return ;
}
chain.doFilter(request, response);
}
@Override @Override
public void destroy() { public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (applicationConfig == null) {
_logger.info("applicationConfig init .");
applicationConfig = WebApplicationContextUtils.getWebApplicationContext(
request.getServletContext())
.getBean("applicationConfig", ApplicationConfig.class);
}
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
HttpSession session = httpServletRequest.getSession();
String ipAddress = WebContext.getRequestIpAddress(httpServletRequest);
_logger.trace("IpAddress " + ipAddress);
// 黑名单地址
if (IpAddressCache.ipAddressBlackListMap.containsKey(ipAddress)) {
IpAddrFilter ipAddrFilter = IpAddressCache.ipAddressBlackListMap.get(ipAddress);
_logger.info("You IpAddress in Black List " + ipAddrFilter);
RequestDispatcher dispatcher = request.getRequestDispatcher("/accessdeny");
dispatcher.forward(request, response);
return;
}
// 白名单地址
if (whiteList && !IpAddressCache.ipAddressWhiteListMap.containsKey(ipAddress)) {
_logger.info("You IpAddress not in White List " + ipAddress);
RequestDispatcher dispatcher = request.getRequestDispatcher("/accessdeny");
dispatcher.forward(request, response);
return;
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
} }

View File

@ -10,40 +10,45 @@ import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
import org.maxkey.util.StringUtils; import org.maxkey.util.StringUtils;
import org.maxkey.web.WebConstants; import org.maxkey.web.WebConstants;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
* * SingleSignOnFilter.
* @author Crystal.Sea * @author Crystal.Sea
*/ */
public class SingleSignOnFilter implements Filter { public class SingleSignOnFilter implements Filter {
private static final Logger _logger = LoggerFactory.getLogger(SingleSignOnFilter.class); private static final Logger _logger = LoggerFactory.getLogger(SingleSignOnFilter.class);
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request; /**
HttpServletResponse httpServletResponse = (HttpServletResponse) response; *doFilter.
HttpSession session = httpServletRequest.getSession(); */
//浠巗ession涓幏鍙栧瓨鏀剧殑appid public void doFilter(ServletRequest request,
String appId = (String) session.getAttribute(WebConstants.SINGLE_SIGN_ON_APP_ID); ServletResponse response, FilterChain chain)throws IOException, ServletException {
//鑾峰彇鏈<EFBFBD>鍚庝竴涓<EFBFBD>"/"鐨勬暟鎹綔涓篴ppid锛屼繚瀛樺湪session涓<EFBFBD>
if(StringUtils.isNullOrBlank(appId)) {
String uir = httpServletRequest.getRequestURI();
session.setAttribute(WebConstants.SINGLE_SIGN_ON_APP_ID, uir.substring(uir.lastIndexOf("/")+1));
session.setAttribute("protocol", "formbase");
}
chain.doFilter(request, response);
}
public void destroy() {
_logger.debug(" destroy.");
}
public void init(FilterConfig config) throws ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) request;
_logger.debug(" init."); HttpServletResponse httpServletResponse = (HttpServletResponse) response;
} HttpSession session = httpServletRequest.getSession();
// 浠巗ession涓幏鍙栧瓨鏀剧殑appid
String appId = (String) session.getAttribute(WebConstants.SINGLE_SIGN_ON_APP_ID);
// 鑾峰彇鏈<EFBFBD>鍚庝竴涓<EFBFBD>"/"鐨勬暟鎹綔涓篴ppid锛屼繚瀛樺湪session涓<EFBFBD>
if (StringUtils.isNullOrBlank(appId)) {
String uir = httpServletRequest.getRequestURI();
session.setAttribute(WebConstants.SINGLE_SIGN_ON_APP_ID,
uir.substring(uir.lastIndexOf("/") + 1));
session.setAttribute("protocol", "formbase");
}
chain.doFilter(request, response);
}
public void destroy() {
_logger.debug(" destroy.");
}
public void init(FilterConfig config) throws ServletException {
_logger.debug(" init.");
}
} }

View File

@ -1,9 +1,7 @@
package org.maxkey.web.interceptor; package org.maxkey.web.interceptor;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.maxkey.authz.endpoint.AuthorizeBaseEndpoint; import org.maxkey.authz.endpoint.AuthorizeBaseEndpoint;
import org.maxkey.dao.service.AppsService; import org.maxkey.dao.service.AppsService;
import org.maxkey.dao.service.HistoryLoginAppsService; import org.maxkey.dao.service.HistoryLoginAppsService;
@ -20,42 +18,47 @@ import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
public class HistoryLoginAppAdapter extends HandlerInterceptorAdapter { public class HistoryLoginAppAdapter extends HandlerInterceptorAdapter {
private static final Logger _logger = LoggerFactory.getLogger(HistoryLoginAppAdapter.class); private static final Logger _logger = LoggerFactory.getLogger(HistoryLoginAppAdapter.class);
@Autowired @Autowired
HistoryLoginAppsService historyLoginAppsService; HistoryLoginAppsService historyLoginAppsService;
@Autowired @Autowired
@Qualifier("appsService") @Qualifier("appsService")
protected AppsService appsService; protected AppsService appsService;
/*
* (non-Javadoc) /**
* @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object) * postHandle .
*/ * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle(
public void postHandle(HttpServletRequest request,HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception { * javax.servlet.http.HttpServletRequest,
_logger.debug("postHandle"); * javax.servlet.http.HttpServletResponse, java.lang.Object)
String appId=null; */
if(WebContext.getAttribute(WebConstants.SINGLE_SIGN_ON_APP_ID)!=null){ public void postHandle(HttpServletRequest request,
appId=WebContext.getAttribute(WebConstants.SINGLE_SIGN_ON_APP_ID).toString(); HttpServletResponse response,
} Object handler,ModelAndView modelAndView) throws Exception {
if(appId==null){ _logger.debug("postHandle");
PreLoginAppAdapter.getAppIdFromRequestURI(request); String appId = null;
} if (WebContext.getAttribute(WebConstants.SINGLE_SIGN_ON_APP_ID) != null) {
//Applications app=applicationsService.get(appId); appId = WebContext.getAttribute(WebConstants.SINGLE_SIGN_ON_APP_ID).toString();
Apps app=(Apps)WebContext.getAttribute(AuthorizeBaseEndpoint.class.getName()); }
String sessionId=(String)WebContext.getAttribute(WebConstants.CURRENT_USER_SESSION_ID); if (appId == null) {
UserInfo userInfo =WebContext.getUserInfo(); PreLoginAppAdapter.getAppIdFromRequestUrl(request);
_logger.debug("sessionId : "+sessionId+" ,appId : "+appId); }
HistoryLoginApps historyLoginApps=new HistoryLoginApps(); //Applications app=applicationsService.get(appId);
historyLoginApps.setId(historyLoginApps.generateId()); final Apps app = (Apps)WebContext.getAttribute(AuthorizeBaseEndpoint.class.getName());
historyLoginApps.setAppId(appId); String sessionId = (String)WebContext.getAttribute(WebConstants.CURRENT_USER_SESSION_ID);
historyLoginApps.setSessionId(sessionId); final UserInfo userInfo = WebContext.getUserInfo();
historyLoginApps.setAppName(app.getName()); _logger.debug("sessionId : " + sessionId + " ,appId : " + appId);
historyLoginApps.setUid(userInfo.getId()); HistoryLoginApps historyLoginApps = new HistoryLoginApps();
historyLoginApps.setUsername(userInfo.getUsername()); historyLoginApps.setId(historyLoginApps.generateId());
historyLoginApps.setDisplayName(userInfo.getDisplayName()); historyLoginApps.setAppId(appId);
historyLoginAppsService.insert(historyLoginApps); historyLoginApps.setSessionId(sessionId);
WebContext.removeAttribute(WebConstants.CURRENT_SINGLESIGNON_URI); historyLoginApps.setAppName(app.getName());
WebContext.removeAttribute(WebConstants.SINGLE_SIGN_ON_APP_ID); historyLoginApps.setUid(userInfo.getId());
} historyLoginApps.setUsername(userInfo.getUsername());
historyLoginApps.setDisplayName(userInfo.getDisplayName());
historyLoginAppsService.insert(historyLoginApps);
WebContext.removeAttribute(WebConstants.CURRENT_SINGLESIGNON_URI);
WebContext.removeAttribute(WebConstants.SINGLE_SIGN_ON_APP_ID);
}
} }

View File

@ -2,7 +2,6 @@ package org.maxkey.web.interceptor;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.maxkey.dao.service.HistoryLogsService; import org.maxkey.dao.service.HistoryLogsService;
import org.maxkey.domain.HistoryLogs; import org.maxkey.domain.HistoryLogs;
import org.maxkey.domain.UserInfo; import org.maxkey.domain.UserInfo;
@ -19,47 +18,53 @@ import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
/** /**
* Contorller调用完成后进行日志操作 * Contorller调用完成后进行日志操作
*
* 日志处理需在parasec-servlet.xml中配置 * 日志处理需在parasec-servlet.xml中配置
* mvc:interceptors log * mvc:interceptors log
* @author Crystal.Sea * @author Crystal.Sea
* *
*/ */
public class HistoryLogsAdapter extends HandlerInterceptorAdapter { public class HistoryLogsAdapter extends HandlerInterceptorAdapter {
private static final Logger _logger = LoggerFactory.getLogger(HistoryLogsAdapter.class); private static final Logger _logger = LoggerFactory.getLogger(HistoryLogsAdapter.class);
@Autowired @Autowired
@Qualifier("historyLogsService") @Qualifier("historyLogsService")
private HistoryLogsService historyLogsService; private HistoryLogsService historyLogsService;
// after the handler is executed /**
public void postHandle(HttpServletRequest request,HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception { * after the handler is executed.
_logger.debug("postHandle"); */
Message message = WebContext.getMessage();//读取session中message public void postHandle(HttpServletRequest request,
HttpServletResponse response,
if(message != null){ Object handler,ModelAndView modelAndView) throws Exception {
if(message.getMessageScope() == MessageScope.DB || message.getMessageScope() == MessageScope.DB_CLIENT) {//判断message类型 _logger.debug("postHandle");
UserInfo userInfo =WebContext.getUserInfo();//取得当前用户信息 Message message = WebContext.getMessage();//读取session中message
//创建日志记录 if (message != null) {
HistoryLogs historyLogs = new HistoryLogs( //判断message类型
message.getServiceName(), if (message.getMessageScope() == MessageScope.DB
message.getCode(), || message.getMessageScope() == MessageScope.DB_CLIENT) {
message.getMessage(), UserInfo userInfo = WebContext.getUserInfo();//取得当前用户信息
JsonUtils.object2Json(message.getMessageObject()),
message.getMessageType().toString(), //创建日志记录
message.getOperateType().toString(), HistoryLogs historyLogs = new HistoryLogs(
userInfo==null?null:userInfo.getId(), message.getServiceName(),
userInfo==null?null:userInfo.getUsername(), message.getCode(),
"" message.getMessage(),
); JsonUtils.object2Json(message.getMessageObject()),
_logger.debug("insert db historyLogs content : "+historyLogs); message.getMessageType().toString(),
historyLogsService.insert(historyLogs);//日志插入数据库 message.getOperateType().toString(),
if(message.getMessageScope() == MessageScope.DB) {//message类型仅插入数据库 userInfo == null ? null : userInfo.getId(),
WebContext.clearMessage();//清除message userInfo == null ? null : userInfo.getUsername(),
} ""
} );
} _logger.debug("insert db historyLogs content : " + historyLogs);
} historyLogsService.insert(historyLogs);//日志插入数据库
//message类型仅插入数据库
if (message.getMessageScope() == MessageScope.DB) {
WebContext.clearMessage();//清除message
}
}
}
}
} }

View File

@ -1,11 +1,9 @@
package org.maxkey.web.interceptor; package org.maxkey.web.interceptor;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.RequestDispatcher; import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.maxkey.config.ApplicationConfig; import org.maxkey.config.ApplicationConfig;
import org.maxkey.web.WebContext; import org.maxkey.web.WebContext;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -13,56 +11,58 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
/** /**
* 权限Interceptor处理 * 权限Interceptor处理 权限处理需在servlet.xml中配置 mvc:interceptors permission
* 权限处理需在servlet.xml中配置 *
* mvc:interceptors permission
* @author Crystal.Sea * @author Crystal.Sea
* *
*/ */
public class PermissionAdapter extends HandlerInterceptorAdapter { public class PermissionAdapter extends HandlerInterceptorAdapter {
private static final Logger _logger = LoggerFactory.getLogger(PermissionAdapter.class); private static final Logger _logger = LoggerFactory.getLogger(PermissionAdapter.class);
//无需Interceptor url // 无需Interceptor url
@Autowired @Autowired
@Qualifier("applicationConfig") @Qualifier("applicationConfig")
private ApplicationConfig applicationConfig; private ApplicationConfig applicationConfig;
static ConcurrentHashMap<String ,String >navigationsMap=null; static ConcurrentHashMap<String, String> navigationsMap = null;
/*
* 请求前处理 /*
* (non-Javadoc) * 请求前处理 (non-Javadoc)
* @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object) *
*/ * @see
@Override * org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle(
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception { * javax.servlet.http.HttpServletRequest,
_logger.trace("PermissionAdapter preHandle"); * javax.servlet.http.HttpServletResponse, java.lang.Object)
//判断用户是否登录 */
if(WebContext.getAuthentication()==null||WebContext.getAuthentication().getAuthorities()==null){//判断用户和角色判断用户是否登录用户 @Override
_logger.trace("No Authentication ... forward to /login"); public boolean preHandle(HttpServletRequest request,
RequestDispatcher dispatcher = request.getRequestDispatcher("/login"); HttpServletResponse response, Object handler)
dispatcher.forward(request, response); throws Exception {
return false; _logger.trace("PermissionAdapter preHandle");
} // 判断用户是否登录, 判断用户和角色判断用户是否登录用户
if (WebContext.getAuthentication() == null
|| WebContext.getAuthentication().getAuthorities() == null) {
boolean hasAccess=true; _logger.trace("No Authentication ... forward to /login");
RequestDispatcher dispatcher = request.getRequestDispatcher("/login");
dispatcher.forward(request, response);
/* return false;
boolean preHandler = super.preHandle(request, response, handler); }
if(preHandler) { boolean hasAccess = true;
preHandler = false;
/*
* boolean preHandler = super.preHandle(request, response, handler);
if(!preHandler){//无权限转向 *
log.debug("You do not have permission to access "+accessUrl); * if(preHandler) { preHandler = false;
RequestDispatcher dispatcher = request.getRequestDispatcher("/accessdeny"); *
dispatcher.forward(request, response); *
return false; * if(!preHandler){//无权限转向
} * log.debug("You do not have permission to access "+accessUrl);
}*/ * RequestDispatcher dispatcher = request.getRequestDispatcher("/accessdeny");
return hasAccess; * dispatcher.forward(request, response); return false; } }
} */
return hasAccess;
}
} }

View File

@ -1,9 +1,7 @@
package org.maxkey.web.interceptor; package org.maxkey.web.interceptor;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.maxkey.domain.UserInfo; import org.maxkey.domain.UserInfo;
import org.maxkey.web.WebConstants; import org.maxkey.web.WebConstants;
import org.maxkey.web.WebContext; import org.maxkey.web.WebContext;
@ -11,38 +9,43 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
public class PreLoginAppAdapter extends HandlerInterceptorAdapter { public class PreLoginAppAdapter extends HandlerInterceptorAdapter {
private static final Logger _logger = LoggerFactory.getLogger(PreLoginAppAdapter.class);
private static final Logger _logger = LoggerFactory.getLogger(PreLoginAppAdapter.class);
@Override
@Override public boolean preHandle(HttpServletRequest request,
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception { HttpServletResponse response, Object handler)
_logger.debug("preHandle"); throws Exception {
UserInfo userInfo=WebContext.getUserInfo(); _logger.debug("preHandle");
String redirect_uri=request.getRequestURL().toString(); UserInfo userInfo = WebContext.getUserInfo();
String appId=getAppIdFromRequestURI(request); String redirect_uri = request.getRequestURL().toString();
_logger.debug("preHandle app Id "+appId); String appId = getAppIdFromRequestUrl(request);
Object singlesignon_uri=WebContext.getAttribute(WebConstants.CURRENT_SINGLESIGNON_URI); _logger.debug("preHandle app Id " + appId);
if(singlesignon_uri!=null&&singlesignon_uri.equals(redirect_uri)){ Object singlesignon_uri = WebContext.getAttribute(WebConstants.CURRENT_SINGLESIGNON_URI);
return true; if (singlesignon_uri != null && singlesignon_uri.equals(redirect_uri)) {
} return true;
/*if(userInfo.getProtectedAppsMap().get(appId)!=null){ }
/*
request.setAttribute("redirect_uri",redirect_uri); * if(userInfo.getProtectedAppsMap().get(appId)!=null){
_logger.debug(""+redirect_uri); *
RequestDispatcher dispatcher = request.getRequestDispatcher("/authorize/protected/forward"); * request.setAttribute("redirect_uri",redirect_uri);
dispatcher.forward(request, response); * _logger.debug(""+redirect_uri); RequestDispatcher dispatcher =
return false; * request.getRequestDispatcher("/authorize/protected/forward");
}*/ * dispatcher.forward(request, response); return false; }
*/
return true;
} return true;
}
public static String getAppIdFromRequestURI(HttpServletRequest request){
String[] uri=request.getRequestURI().split("/"); /**
String appId=uri[uri.length-1]; * Request URL .
return appId; * @param request http
} * @return .
*/
public static String getAppIdFromRequestUrl(HttpServletRequest request) {
String[] uri = request.getRequestURI().split("/");
String appId = uri[uri.length - 1];
return appId;
}
} }

324
style/checkstyle-rules.xml Normal file
View File

@ -0,0 +1,324 @@
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
"https://checkstyle.org/dtds/configuration_1_3.dtd">
<!--
Checkstyle configuration that checks the Google coding conventions from Google Java Style
that can be found at https://google.github.io/styleguide/javaguide.html
Checkstyle is very configurable. Be sure to read the documentation at
http://checkstyle.org (or in your downloaded distribution).
To completely disable a check, just comment it out or delete it from the file.
To suppress certain violations please review suppression filters.
Authors: Max Vetrenko, Ruslan Diachenko, Roman Ivanov.
-->
<module name = "Checker">
<property name="charset" value="UTF-8"/>
<property name="severity" value="warning"/>
<property name="fileExtensions" value="java, properties, xml"/>
<!-- Excludes all 'module-info.java' files -->
<!-- See https://checkstyle.org/config_filefilters.html -->
<module name="BeforeExecutionExclusionFileFilter">
<property name="fileNamePattern" value="module\-info\.java$"/>
</module>
<!-- https://checkstyle.org/config_filters.html#SuppressionFilter -->
<module name="SuppressionFilter">
<property name="file" value="${org.checkstyle.google.suppressionfilter.config}"
default="checkstyle-suppressions.xml" />
<property name="optional" value="true"/>
</module>
<!-- Checks for whitespace -->
<!-- See http://checkstyle.org/config_whitespace.html -->
<module name="FileTabCharacter">
<property name="eachLine" value="true"/>
</module>
<module name="LineLength">
<property name="fileExtensions" value="java"/>
<property name="max" value="100"/>
<property name="ignorePattern" value="^package.*|^import.*|a href|href|http://|https://|ftp://"/>
</module>
<module name="TreeWalker">
<module name="OuterTypeFilename"/>
<module name="IllegalTokenText">
<property name="tokens" value="STRING_LITERAL, CHAR_LITERAL"/>
<property name="format"
value="\\u00(09|0(a|A)|0(c|C)|0(d|D)|22|27|5(C|c))|\\(0(10|11|12|14|15|42|47)|134)"/>
<property name="message"
value="Consider using special escape sequence instead of octal value or Unicode escaped value."/>
</module>
<module name="AvoidEscapedUnicodeCharacters">
<property name="allowEscapesForControlCharacters" value="true"/>
<property name="allowByTailComment" value="true"/>
<property name="allowNonPrintableEscapes" value="true"/>
</module>
<module name="AvoidStarImport"/>
<module name="OneTopLevelClass"/>
<module name="NoLineWrap">
<property name="tokens" value="PACKAGE_DEF, IMPORT, STATIC_IMPORT"/>
</module>
<module name="EmptyBlock">
<property name="option" value="TEXT"/>
<property name="tokens"
value="LITERAL_TRY, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE, LITERAL_SWITCH"/>
</module>
<module name="NeedBraces">
<property name="tokens"
value="LITERAL_DO, LITERAL_ELSE, LITERAL_FOR, LITERAL_IF, LITERAL_WHILE"/>
</module>
<module name="LeftCurly">
<property name="tokens"
value="ANNOTATION_DEF, CLASS_DEF, CTOR_DEF, ENUM_CONSTANT_DEF, ENUM_DEF,
INTERFACE_DEF, LAMBDA, LITERAL_CASE, LITERAL_CATCH, LITERAL_DEFAULT,
LITERAL_DO, LITERAL_ELSE, LITERAL_FINALLY, LITERAL_FOR, LITERAL_IF,
LITERAL_SWITCH, LITERAL_SYNCHRONIZED, LITERAL_TRY, LITERAL_WHILE, METHOD_DEF,
OBJBLOCK, STATIC_INIT"/>
</module>
<module name="RightCurly">
<property name="id" value="RightCurlySame"/>
<property name="tokens"
value="LITERAL_TRY, LITERAL_CATCH, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE,
LITERAL_DO"/>
</module>
<module name="RightCurly">
<property name="id" value="RightCurlyAlone"/>
<property name="option" value="alone"/>
<property name="tokens"
value="CLASS_DEF, METHOD_DEF, CTOR_DEF, LITERAL_FOR, LITERAL_WHILE, STATIC_INIT,
INSTANCE_INIT, ANNOTATION_DEF, ENUM_DEF"/>
</module>
<module name="SuppressionXpathSingleFilter">
<!-- suppresion is required till https://github.com/checkstyle/checkstyle/issues/7541 -->
<property name="id" value="RightCurlyAlone"/>
<property name="query" value="//RCURLY[parent::SLIST[count(./*)=1]
or preceding-sibling::*[last()][self::LCURLY]]"/>
</module>
<module name="WhitespaceAround">
<property name="allowEmptyConstructors" value="true"/>
<property name="allowEmptyLambdas" value="true"/>
<property name="allowEmptyMethods" value="true"/>
<property name="allowEmptyTypes" value="true"/>
<property name="allowEmptyLoops" value="true"/>
<property name="tokens"
value="ASSIGN, BAND, BAND_ASSIGN, BOR, BOR_ASSIGN, BSR, BSR_ASSIGN, BXOR,
BXOR_ASSIGN, COLON, DIV, DIV_ASSIGN, DO_WHILE, EQUAL, GE, GT, LAMBDA, LAND,
LCURLY, LE, LITERAL_CATCH, LITERAL_DO, LITERAL_ELSE, LITERAL_FINALLY,
LITERAL_FOR, LITERAL_IF, LITERAL_RETURN, LITERAL_SWITCH, LITERAL_SYNCHRONIZED,
LITERAL_TRY, LITERAL_WHILE, LOR, LT, MINUS, MINUS_ASSIGN, MOD, MOD_ASSIGN,
NOT_EQUAL, PLUS, PLUS_ASSIGN, QUESTION, RCURLY, SL, SLIST, SL_ASSIGN, SR,
SR_ASSIGN, STAR, STAR_ASSIGN, LITERAL_ASSERT, TYPE_EXTENSION_AND"/>
<message key="ws.notFollowed"
value="WhitespaceAround: ''{0}'' is not followed by whitespace. Empty blocks may only be represented as '{}' when not part of a multi-block statement (4.1.3)"/>
<message key="ws.notPreceded"
value="WhitespaceAround: ''{0}'' is not preceded with whitespace."/>
</module>
<module name="OneStatementPerLine"/>
<module name="MultipleVariableDeclarations"/>
<module name="ArrayTypeStyle"/>
<module name="MissingSwitchDefault"/>
<module name="FallThrough"/>
<module name="UpperEll"/>
<module name="ModifierOrder"/>
<module name="EmptyLineSeparator">
<property name="tokens"
value="PACKAGE_DEF, IMPORT, STATIC_IMPORT, CLASS_DEF, INTERFACE_DEF, ENUM_DEF,
STATIC_INIT, INSTANCE_INIT, METHOD_DEF, CTOR_DEF, VARIABLE_DEF"/>
<property name="allowNoEmptyLineBetweenFields" value="true"/>
</module>
<module name="SeparatorWrap">
<property name="id" value="SeparatorWrapDot"/>
<property name="tokens" value="DOT"/>
<property name="option" value="nl"/>
</module>
<module name="SeparatorWrap">
<property name="id" value="SeparatorWrapComma"/>
<property name="tokens" value="COMMA"/>
<property name="option" value="EOL"/>
</module>
<module name="SeparatorWrap">
<!-- ELLIPSIS is EOL until https://github.com/google/styleguide/issues/258 -->
<property name="id" value="SeparatorWrapEllipsis"/>
<property name="tokens" value="ELLIPSIS"/>
<property name="option" value="EOL"/>
</module>
<module name="SeparatorWrap">
<!-- ARRAY_DECLARATOR is EOL until https://github.com/google/styleguide/issues/259 -->
<property name="id" value="SeparatorWrapArrayDeclarator"/>
<property name="tokens" value="ARRAY_DECLARATOR"/>
<property name="option" value="EOL"/>
</module>
<module name="SeparatorWrap">
<property name="id" value="SeparatorWrapMethodRef"/>
<property name="tokens" value="METHOD_REF"/>
<property name="option" value="nl"/>
</module>
<module name="PackageName">
<property name="format" value="^[a-z]+(\.[a-z][a-z0-9]*)*$"/>
<message key="name.invalidPattern"
value="Package name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="TypeName">
<property name="tokens" value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, ANNOTATION_DEF"/>
<message key="name.invalidPattern"
value="Type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="MemberName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$"/>
<message key="name.invalidPattern"
value="Member name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="ParameterName">
<property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/>
<message key="name.invalidPattern"
value="Parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="LambdaParameterName">
<property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/>
<message key="name.invalidPattern"
value="Lambda parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="CatchParameterName">
<property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/>
<message key="name.invalidPattern"
value="Catch parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="LocalVariableName">
<property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/>
<message key="name.invalidPattern"
value="Local variable name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="ClassTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Class type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="MethodTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Method type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="InterfaceTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Interface type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="NoFinalizer"/>
<module name="GenericWhitespace">
<message key="ws.followed"
value="GenericWhitespace ''{0}'' is followed by whitespace."/>
<message key="ws.preceded"
value="GenericWhitespace ''{0}'' is preceded with whitespace."/>
<message key="ws.illegalFollow"
value="GenericWhitespace ''{0}'' should followed by whitespace."/>
<message key="ws.notPreceded"
value="GenericWhitespace ''{0}'' is not preceded with whitespace."/>
</module>
<module name="Indentation">
<property name="basicOffset" value="4"/>
<property name="braceAdjustment" value="0"/>
<property name="caseIndent" value="4"/>
<property name="throwsIndent" value="8"/>
<property name="lineWrappingIndentation" value="8"/>
<property name="arrayInitIndent" value="4"/>
</module>
<module name="AbbreviationAsWordInName">
<property name="ignoreFinal" value="false"/>
<property name="allowedAbbreviationLength" value="1"/>
<property name="tokens"
value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, ANNOTATION_DEF, ANNOTATION_FIELD_DEF,
PARAMETER_DEF, VARIABLE_DEF, METHOD_DEF"/>
</module>
<module name="OverloadMethodsDeclarationOrder"/>
<module name="VariableDeclarationUsageDistance"/>
<module name="CustomImportOrder">
<property name="sortImportsInGroupAlphabetically" value="true"/>
<property name="separateLineBetweenGroups" value="true"/>
<property name="customImportOrderRules" value="STATIC###THIRD_PARTY_PACKAGE"/>
<property name="tokens" value="IMPORT, STATIC_IMPORT, PACKAGE_DEF"/>
</module>
<module name="MethodParamPad">
<property name="tokens"
value="CTOR_DEF, LITERAL_NEW, METHOD_CALL, METHOD_DEF,
SUPER_CTOR_CALL, ENUM_CONSTANT_DEF"/>
</module>
<module name="NoWhitespaceBefore">
<property name="tokens"
value="COMMA, SEMI, POST_INC, POST_DEC, DOT, ELLIPSIS, METHOD_REF"/>
<property name="allowLineBreaks" value="true"/>
</module>
<module name="ParenPad">
<property name="tokens"
value="ANNOTATION, ANNOTATION_FIELD_DEF, CTOR_CALL, CTOR_DEF, DOT, ENUM_CONSTANT_DEF,
EXPR, LITERAL_CATCH, LITERAL_DO, LITERAL_FOR, LITERAL_IF, LITERAL_NEW,
LITERAL_SWITCH, LITERAL_SYNCHRONIZED, LITERAL_WHILE, METHOD_CALL,
METHOD_DEF, QUESTION, RESOURCE_SPECIFICATION, SUPER_CTOR_CALL, LAMBDA"/>
</module>
<module name="OperatorWrap">
<property name="option" value="NL"/>
<property name="tokens"
value="BAND, BOR, BSR, BXOR, DIV, EQUAL, GE, GT, LAND, LE, LITERAL_INSTANCEOF, LOR,
LT, MINUS, MOD, NOT_EQUAL, PLUS, QUESTION, SL, SR, STAR, METHOD_REF "/>
</module>
<module name="AnnotationLocation">
<property name="id" value="AnnotationLocationMostCases"/>
<property name="tokens"
value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF"/>
</module>
<module name="AnnotationLocation">
<property name="id" value="AnnotationLocationVariables"/>
<property name="tokens" value="VARIABLE_DEF"/>
<property name="allowSamelineMultipleAnnotations" value="true"/>
</module>
<module name="NonEmptyAtclauseDescription"/>
<module name="InvalidJavadocPosition"/>
<module name="JavadocTagContinuationIndentation"/>
<module name="SummaryJavadoc">
<property name="forbiddenSummaryFragments"
value="^@return the *|^This method returns |^A [{]@code [a-zA-Z0-9]+[}]( is a )"/>
</module>
<module name="JavadocParagraph"/>
<module name="AtclauseOrder">
<property name="tagOrder" value="@param, @return, @throws, @deprecated"/>
<property name="target"
value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF, VARIABLE_DEF"/>
</module>
<module name="JavadocMethod">
<property name="scope" value="public"/>
<property name="allowMissingParamTags" value="true"/>
<property name="allowMissingReturnTag" value="true"/>
<property name="allowedAnnotations" value="Override, Test"/>
<property name="tokens" value="METHOD_DEF, CTOR_DEF, ANNOTATION_FIELD_DEF"/>
</module>
<module name="MissingJavadocMethod">
<property name="scope" value="public"/>
<property name="minLineCount" value="2"/>
<property name="allowedAnnotations" value="Override, Test"/>
<property name="tokens" value="METHOD_DEF, CTOR_DEF, ANNOTATION_FIELD_DEF"/>
</module>
<module name="MethodName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9_]*$"/>
<message key="name.invalidPattern"
value="Method name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="SingleLineJavadoc">
<property name="ignoreInlineTags" value="false"/>
</module>
<module name="EmptyCatchBlock">
<property name="exceptionVariableName" value="expected"/>
</module>
<module name="CommentsIndentation">
<property name="tokens" value="SINGLE_LINE_COMMENT, BLOCK_COMMENT_BEGIN"/>
</module>
<!-- https://checkstyle.org/config_filters.html#SuppressionXpathFilter -->
<module name="SuppressionXpathFilter">
<property name="file" value="${org.checkstyle.google.suppressionxpathfilter.config}"
default="checkstyle-xpath-suppressions.xml" />
<property name="optional" value="true"/>
</module>
</module>
</module>