From 586e473e483559d8cfb94c5fade1f1365f1864f9 Mon Sep 17 00:00:00 2001 From: MaxKey Date: Wed, 20 Apr 2022 17:06:18 +0800 Subject: [PATCH] sso --- .../authn/AbstractAuthenticationProvider.java | 49 +---- .../authn/RealmAuthenticationProvider.java | 108 ++++++---- .../org/maxkey/authn/jwt/AuthJwtService.java | 73 +++++-- .../AbstractSocialSignOnEndpoint.java | 64 ++---- .../socialsignon/SocialSignOnEndpoint.java | 189 +++++++----------- .../service/SocialSignOnProviderService.java | 61 +++--- .../SocialSignOnAutoConfiguration.java | 2 +- .../crypto/signature/HMAC512ServiceTest.java | 5 +- .../org/maxkey/entity/SocialsProvider.java | 10 + .../maxkey/entity/SocialsProviderLogin.java | 50 +---- .../repository/InstitutionsRepository.java | 33 +-- .../java/org/maxkey/web/WebConstants.java | 2 + .../main/java/org/maxkey/web/WebContext.java | 10 + .../org/maxkey/web/WebInstRequestFilter.java | 23 ++- .../maxkey/web/endpoint/LoginEntryPoint.java | 131 +++++------- .../web/contorller/LoginEntryPoint.java | 4 +- 16 files changed, 353 insertions(+), 461 deletions(-) diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/AbstractAuthenticationProvider.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/AbstractAuthenticationProvider.java index 6d7e63762..61ea5414c 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/AbstractAuthenticationProvider.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/AbstractAuthenticationProvider.java @@ -35,7 +35,6 @@ import org.slf4j.LoggerFactory; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; -import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; /** @@ -71,59 +70,15 @@ public abstract class AbstractAuthenticationProvider { protected abstract String getProviderName(); - protected abstract Authentication doInternalAuthenticate(LoginCredential authentication); + public abstract Authentication authenticate(LoginCredential authentication); - public abstract Authentication authentication(LoginCredential loginCredential,boolean isTrusted); + public abstract Authentication authentication(LoginCredential loginCredential,boolean isTrusted); @SuppressWarnings("rawtypes") public boolean supports(Class authentication) { return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication)); } - /** - * authenticate . - * - */ - public Authentication authenticate(LoginCredential loginCredential) - throws AuthenticationException { - _logger.debug("Trying to authenticate user '{}' via {}", - loginCredential.getPrincipal(), getProviderName()); - // 登录SESSION - _logger.debug("Login Session {}.", WebContext.getSession().getId()); - Authentication authentication = null; - try { - authentication = doInternalAuthenticate(loginCredential); - } catch (AuthenticationException e) { - _logger.error("Failed to authenticate user {} via {}: {}", - new Object[] { loginCredential.getPrincipal(), - getProviderName(), - e.getMessage() }); - WebContext.setAttribute( - WebConstants.LOGIN_ERROR_SESSION_MESSAGE, e.getMessage()); - } catch (Exception e) { - _logger.error("Login error Unexpected exception in {} authentication:\n{}" , - getProviderName(), e.getMessage()); - } - - if (authentication== null || !authentication.isAuthenticated()) { - return authentication; - } - - // user authenticated - _logger.debug("'{}' authenticated successfully by {}.", - authentication.getPrincipal(), getProviderName()); - - changeSession(authentication); - - authenticationRealm.insertLoginHistory(((SigninPrincipal) authentication.getPrincipal()).getUserInfo(), - ConstsLoginType.LOCAL, - "", - "xe00000004", - WebConstants.LOGIN_RESULT.SUCCESS); - - return authentication; - } - protected void changeSession(Authentication authentication) { HashMap sessionAttributeMap = new HashMap(); diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/RealmAuthenticationProvider.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/RealmAuthenticationProvider.java index fb68aeaac..e47778811 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/RealmAuthenticationProvider.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/RealmAuthenticationProvider.java @@ -24,6 +24,7 @@ import org.maxkey.authn.online.OnlineTicketService; import org.maxkey.authn.realm.AbstractAuthenticationRealm; import org.maxkey.authn.web.AuthorizationUtils; import org.maxkey.configuration.ApplicationConfig; +import org.maxkey.constants.ConstsLoginType; import org.maxkey.entity.Institutions; import org.maxkey.entity.UserInfo; import org.maxkey.password.onetimepwd.AbstractOtpAuthn; @@ -35,6 +36,7 @@ import org.slf4j.LoggerFactory; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.web.authentication.WebAuthenticationDetails; @@ -71,47 +73,73 @@ public class RealmAuthenticationProvider extends AbstractAuthenticationProvider this.onlineTicketServices = onlineTicketServices; } - @Override - protected Authentication doInternalAuthenticate(LoginCredential loginCredential) { - - _logger.debug("authentication " + loginCredential); - - //sessionValid(loginCredential.getSessionId()); - - //jwtTokenValid(j_jwtToken); - - authTypeValid(loginCredential.getAuthType()); - - Institutions inst = (Institutions)WebContext.getAttribute(WebConstants.CURRENT_INST); - if(inst.getCaptchaSupport().equalsIgnoreCase("YES")) { - captchaValid(loginCredential.getCaptcha(),loginCredential.getAuthType()); - } - - emptyPasswordValid(loginCredential.getPassword()); - - UserInfo userInfo = null; - - emptyUsernameValid(loginCredential.getUsername()); - - userInfo = loadUserInfo(loginCredential.getUsername(),loginCredential.getPassword()); - - statusValid(loginCredential , userInfo); - //mfa - tftcaptchaValid(loginCredential.getOtpCaptcha(),loginCredential.getAuthType(),userInfo); - - //Validate PasswordPolicy - authenticationRealm.getPasswordPolicyValidator().passwordPolicyValid(userInfo); - if(loginCredential.getAuthType().equalsIgnoreCase(AuthType.MOBILE)) { - mobilecaptchaValid(loginCredential.getPassword(),loginCredential.getAuthType(),userInfo); - }else { - //Match password - authenticationRealm.passwordMatches(userInfo, loginCredential.getPassword()); + @Override + public Authentication authenticate(LoginCredential loginCredential) { + UsernamePasswordAuthenticationToken authenticationToken = null; + _logger.debug("Trying to authenticate user '{}' via {}", + loginCredential.getPrincipal(), getProviderName()); + try { + + _logger.debug("authentication " + loginCredential); + + //sessionValid(loginCredential.getSessionId()); + + //jwtTokenValid(j_jwtToken); + + authTypeValid(loginCredential.getAuthType()); + + Institutions inst = (Institutions)WebContext.getAttribute(WebConstants.CURRENT_INST); + if(inst.getCaptchaSupport().equalsIgnoreCase("YES")) { + captchaValid(loginCredential.getCaptcha(),loginCredential.getAuthType()); + } + + emptyPasswordValid(loginCredential.getPassword()); + + UserInfo userInfo = null; + + emptyUsernameValid(loginCredential.getUsername()); + + userInfo = loadUserInfo(loginCredential.getUsername(),loginCredential.getPassword()); + + statusValid(loginCredential , userInfo); + //mfa + tftcaptchaValid(loginCredential.getOtpCaptcha(),loginCredential.getAuthType(),userInfo); + + //Validate PasswordPolicy + authenticationRealm.getPasswordPolicyValidator().passwordPolicyValid(userInfo); + if(loginCredential.getAuthType().equalsIgnoreCase(AuthType.MOBILE)) { + mobilecaptchaValid(loginCredential.getPassword(),loginCredential.getAuthType(),userInfo); + }else { + //Match password + authenticationRealm.passwordMatches(userInfo, loginCredential.getPassword()); + } + //apply PasswordSetType and resetBadPasswordCount + authenticationRealm.getPasswordPolicyValidator().applyPasswordPolicy(userInfo); + + authenticationToken = createOnlineSession(loginCredential,userInfo); + // user authenticated + _logger.debug("'{}' authenticated successfully by {}.", + loginCredential.getPrincipal(), getProviderName()); + + changeSession(authenticationToken); + + authenticationRealm.insertLoginHistory(userInfo, + ConstsLoginType.LOCAL, + "", + "xe00000004", + WebConstants.LOGIN_RESULT.SUCCESS); + } catch (AuthenticationException e) { + _logger.error("Failed to authenticate user {} via {}: {}", + new Object[] { loginCredential.getPrincipal(), + getProviderName(), + e.getMessage() }); + WebContext.setAttribute( + WebConstants.LOGIN_ERROR_SESSION_MESSAGE, e.getMessage()); + } catch (Exception e) { + _logger.error("Login error Unexpected exception in {} authentication:\n{}" , + getProviderName(), e.getMessage()); } - //apply PasswordSetType and resetBadPasswordCount - authenticationRealm.getPasswordPolicyValidator().applyPasswordPolicy(userInfo); - - UsernamePasswordAuthenticationToken authenticationToken = createOnlineSession(loginCredential,userInfo); - + return authenticationToken; } diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/jwt/AuthJwtService.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/jwt/AuthJwtService.java index 99da5515c..d50cc85c3 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/jwt/AuthJwtService.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/jwt/AuthJwtService.java @@ -58,12 +58,22 @@ public class AuthJwtService { this.hmac512Service = new HMAC512Service(authJwkConfig.getSecret()); } - public AuthJwt generateAuthJwt(Authentication authentication) { - return new AuthJwt(generateToken(authentication), authentication); + + /** + * create AuthJwt use Authentication JWT + * @param authentication + * @return AuthJwt + */ + public AuthJwt genAuthJwt(Authentication authentication) { + return new AuthJwt(genJwt(authentication), authentication); } - public String generateToken(Authentication authentication) { - String token = ""; + /** + * JWT with Authentication + * @param authentication + * @return + */ + public String genJwt(Authentication authentication) { SigninPrincipal principal = ((SigninPrincipal)authentication.getPrincipal()); UserInfo userInfo = principal.getUserInfo(); DateTime currentDateTime = DateTime.now(); @@ -75,7 +85,7 @@ public class AuthJwtService { JWTClaimsSet jwtClaims =new JWTClaimsSet.Builder() .issuer(authJwkConfig.getIssuer()) .subject(subject) - .jwtID(principal.getOnlineTicket().getFormattedTicketId()) + .jwtID(principal.getOnlineTicket().getTicketId()) .issueTime(currentDateTime.toDate()) .expirationTime(expirationTime) .claim("locale", userInfo.getLocale()) @@ -83,15 +93,54 @@ public class AuthJwtService { .claim("institution", userInfo.getInstId()) .build(); - _logger.trace("jwt Claims : {}" , jwtClaims); + return signedJWT(jwtClaims); + } + + /** + * JWT with subject + * @param subject subject + * @return + */ + public String genJwt(String subject) { + DateTime currentDateTime = DateTime.now(); + Date expirationTime = currentDateTime.plusSeconds(authJwkConfig.getExpires()).toDate(); + _logger.debug("expiration Time : {}" , expirationTime); + _logger.trace("jwt subject : {}" , subject); - SignedJWT jwtToken = new SignedJWT( - new JWSHeader(JWSAlgorithm.HS512), - jwtClaims); + JWTClaimsSet jwtClaims =new JWTClaimsSet.Builder() + .issuer(authJwkConfig.getIssuer()) + .subject(subject) + .jwtID(WebContext.genId()) + .issueTime(currentDateTime.toDate()) + .expirationTime(expirationTime) + .build(); + + return signedJWT(jwtClaims); + } + + /** + * Random JWT + * @return + */ + public String genJwt() { + DateTime currentDateTime = DateTime.now(); + Date expirationTime = currentDateTime.plusSeconds(authJwkConfig.getExpires()).toDate(); + _logger.debug("expiration Time : {}" , expirationTime); - token = hmac512Service.sign(jwtToken.getPayload()); + JWTClaimsSet jwtClaims =new JWTClaimsSet.Builder() + .jwtID(WebContext.genId()) + .expirationTime(expirationTime) + .build(); - return token ; + return signedJWT(jwtClaims); + } + + public String signedJWT(JWTClaimsSet jwtClaims) { + _logger.trace("jwt Claims : {}" , jwtClaims); + SignedJWT jwtToken = new SignedJWT( + new JWSHeader(JWSAlgorithm.HS512), + jwtClaims); + return hmac512Service.sign(jwtToken.getPayload()); } public boolean validateJwtToken(String authToken) { @@ -114,7 +163,7 @@ public class AuthJwtService { congressService.store( congress, new AuthJwt( - generateToken(authentication), + genJwt(authentication), authentication) ); return congress; diff --git a/maxkey-authentications/maxkey-authentication-social/src/main/java/org/maxkey/authn/support/socialsignon/AbstractSocialSignOnEndpoint.java b/maxkey-authentications/maxkey-authentication-social/src/main/java/org/maxkey/authn/support/socialsignon/AbstractSocialSignOnEndpoint.java index 8779e722b..4de538795 100644 --- a/maxkey-authentications/maxkey-authentication-social/src/main/java/org/maxkey/authn/support/socialsignon/AbstractSocialSignOnEndpoint.java +++ b/maxkey-authentications/maxkey-authentication-social/src/main/java/org/maxkey/authn/support/socialsignon/AbstractSocialSignOnEndpoint.java @@ -25,6 +25,7 @@ import org.maxkey.authn.jwt.AuthJwtService; import org.maxkey.authn.support.socialsignon.service.SocialSignOnProviderService; import org.maxkey.authn.support.socialsignon.service.SocialsAssociateService; import org.maxkey.configuration.ApplicationConfig; +import org.maxkey.entity.SocialsAssociate; import org.maxkey.entity.SocialsProvider; import org.maxkey.web.WebContext; import org.slf4j.Logger; @@ -42,34 +43,11 @@ import me.zhyd.oauth.request.AuthRequest; */ public class AbstractSocialSignOnEndpoint { final static Logger _logger = LoggerFactory.getLogger(AbstractSocialSignOnEndpoint.class); - - protected final static String SOCIALSIGNON_SESSION_REDIRECT_URI="socialsignon_session_redirect_uri"; - - protected final static String SOCIALSIGNON_REDIRECT_URI="redirect_uri"; - - public final static String SOCIALSIGNON_TYPE_SESSION="socialsignon_type_session"; - - public final static String SOCIALSIGNON_OAUTH_SERVICE_SESSION="socialsignon_oauth_service_session"; - - public final static String SOCIALSIGNON_PROVIDER_SESSION="socialsignon_provider_session"; - - - public final static class SOCIALSIGNON_TYPE{ - public final static String SOCIALSIGNON_TYPE_LOGON="socialsignon_type_logon"; - public final static String SOCIALSIGNON_TYPE_BIND="socialsignon_type_bind"; - } - - - protected SocialsProvider socialSignOnProvider; protected AuthRequest authRequest; protected String accountJsonString; - protected String accountId; - - protected String provider; - @Autowired protected SocialSignOnProviderService socialSignOnProviderService; @@ -86,15 +64,13 @@ public class AbstractSocialSignOnEndpoint { @Autowired ApplicationConfig applicationConfig; - protected AuthRequest buildAuthRequest(String provider){ + protected AuthRequest buildAuthRequest(String instId,String provider){ try { - SocialsProvider socialSignOnProvider = socialSignOnProviderService.get(provider); + SocialsProvider socialSignOnProvider = socialSignOnProviderService.get(instId,provider); _logger.debug("socialSignOn Provider : "+socialSignOnProvider); - if(socialSignOnProvider!=null){ - authRequest=socialSignOnProviderService.getAuthRequest(provider,applicationConfig); - WebContext.setAttribute(SOCIALSIGNON_OAUTH_SERVICE_SESSION, authRequest); - WebContext.setAttribute(SOCIALSIGNON_PROVIDER_SESSION, socialSignOnProvider); + if(socialSignOnProvider != null){ + authRequest = socialSignOnProviderService.getAuthRequest(instId,provider,WebContext.getBaseUri()); return authRequest; } }catch(Exception e) { @@ -103,7 +79,8 @@ public class AbstractSocialSignOnEndpoint { return null; } - protected String authCallback() throws Exception { + protected SocialsAssociate authCallback(String instId,String provider) throws Exception { + SocialsAssociate socialsAssociate = null; AuthCallback authCallback=new AuthCallback(); authCallback.setCode(WebContext.getRequest().getParameter("code")); authCallback.setAuth_code(WebContext.getRequest().getParameter("auth_code")); @@ -111,24 +88,16 @@ public class AbstractSocialSignOnEndpoint { authCallback.setAuthorization_code(WebContext.getRequest().getParameter("authorization_code")); authCallback.setOauth_verifier(WebContext.getRequest().getParameter("oauthVerifier")); authCallback.setState(WebContext.getRequest().getParameter("state")); - _logger.debug("Callback OAuth code {}, auth_code {}, oauthToken {}, authorization_code {}, oauthVerifier {}", + _logger.debug("Callback OAuth code {}, auth_code {}, oauthToken {}, authorization_code {}, oauthVerifier {} , state {}", authCallback.getCode(), authCallback.getAuth_code(), authCallback.getOauth_token(), authCallback.getAuthorization_code(), - authCallback.getOauth_verifier()); - _logger.debug("Callback state {} , sessionId {}", - authCallback.getState(),WebContext.getRequest().getSession().getId() - ); + authCallback.getOauth_verifier(), + authCallback.getState()); - authRequest=(AuthRequest)WebContext.getAttribute(SOCIALSIGNON_OAUTH_SERVICE_SESSION); - socialSignOnProvider=(SocialsProvider)WebContext.getAttribute(SOCIALSIGNON_PROVIDER_SESSION); - //clear session - WebContext.removeAttribute(SOCIALSIGNON_OAUTH_SERVICE_SESSION); - WebContext.removeAttribute(SOCIALSIGNON_PROVIDER_SESSION); - if(authRequest == null) {//if authRequest is null renew one - authRequest=socialSignOnProviderService.getAuthRequest(provider,applicationConfig); + authRequest=socialSignOnProviderService.getAuthRequest(instId,provider,WebContext.getBaseUri()); _logger.debug("session authRequest is null , renew one"); } @@ -139,10 +108,13 @@ public class AbstractSocialSignOnEndpoint { AuthResponse authResponse=authRequest.login(authCallback); _logger.debug("Response : " + authResponse.getData()); - accountId=socialSignOnProviderService.getAccountId(provider, authResponse); - - _logger.debug("getAccountId : " + accountId); - return accountId; + socialsAssociate =new SocialsAssociate(); + socialsAssociate.setProvider(provider); + socialsAssociate.setSocialUserId( + socialSignOnProviderService.getAccountId(provider, authResponse)); + socialsAssociate.setInstId(instId); + + return socialsAssociate; } } diff --git a/maxkey-authentications/maxkey-authentication-social/src/main/java/org/maxkey/authn/support/socialsignon/SocialSignOnEndpoint.java b/maxkey-authentications/maxkey-authentication-social/src/main/java/org/maxkey/authn/support/socialsignon/SocialSignOnEndpoint.java index e2e9c078c..2b052f89d 100644 --- a/maxkey-authentications/maxkey-authentication-social/src/main/java/org/maxkey/authn/support/socialsignon/SocialSignOnEndpoint.java +++ b/maxkey-authentications/maxkey-authentication-social/src/main/java/org/maxkey/authn/support/socialsignon/SocialSignOnEndpoint.java @@ -23,24 +23,23 @@ package org.maxkey.authn.support.socialsignon; import javax.servlet.http.HttpServletRequest; import org.maxkey.authn.LoginCredential; +import org.maxkey.authn.jwt.AuthJwt; import org.maxkey.authn.web.AuthorizationUtils; import org.maxkey.constants.ConstsLoginType; +import org.maxkey.entity.Message; import org.maxkey.entity.SocialsAssociate; import org.maxkey.entity.SocialsProvider; import org.maxkey.entity.UserInfo; import org.maxkey.web.WebContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; -import org.springframework.security.web.WebAttributes; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.servlet.ModelAndView; - import me.zhyd.oauth.request.AuthRequest; /** @@ -51,153 +50,99 @@ import me.zhyd.oauth.request.AuthRequest; @RequestMapping(value = "/logon/oauth20") public class SocialSignOnEndpoint extends AbstractSocialSignOnEndpoint{ final static Logger _logger = LoggerFactory.getLogger(SocialSignOnEndpoint.class); - - public ModelAndView socialSignOnAuthorize(HttpServletRequest request,String provider){ - _logger.trace("SocialSignOn provider : " + provider); - String authorizationUrl=buildAuthRequest(provider).authorize(request.getSession().getId()); - _logger.trace("authorize SocialSignOn : " + authorizationUrl); - return WebContext.redirect(authorizationUrl); - } @RequestMapping(value={"/authorize/{provider}"}, method = RequestMethod.GET) - public ModelAndView authorize(HttpServletRequest request, - @PathVariable String provider) { - WebContext.setAttribute(SOCIALSIGNON_TYPE_SESSION, SOCIALSIGNON_TYPE.SOCIALSIGNON_TYPE_LOGON); - return socialSignOnAuthorize(request,provider); - } - - @RequestMapping(value={"/bind/{provider}"}, method = RequestMethod.GET) - public ModelAndView bind(HttpServletRequest request, - @PathVariable String provider) { - WebContext.setAttribute(SOCIALSIGNON_SESSION_REDIRECT_URI, request.getParameter(SOCIALSIGNON_REDIRECT_URI)); - WebContext.setAttribute(SOCIALSIGNON_TYPE_SESSION, SOCIALSIGNON_TYPE.SOCIALSIGNON_TYPE_BIND); - return socialSignOnAuthorize(request,provider); - } - - @RequestMapping(value={"/authorize/{provider}/{appid}"}, method = RequestMethod.GET) - public ModelAndView authorize2AppId(HttpServletRequest request, - @PathVariable("provider") String provider, - @PathVariable("appid") String appid) { - WebContext.setAttribute(SOCIALSIGNON_SESSION_REDIRECT_URI, "/authorize/"+appid); - return authorize(request,provider); + @ResponseBody + public ResponseEntity authorize(HttpServletRequest request, + @PathVariable String provider + ) { + _logger.trace("SocialSignOn provider : " + provider); + String instId = WebContext.getInst().getId(); + String authorizationUrl = buildAuthRequest(instId,provider).authorize(authJwtService.genJwt()); + _logger.trace("authorize SocialSignOn : " + authorizationUrl); + return new Message((Object)authorizationUrl).buildResponse(); } - + @RequestMapping(value={"/scanqrcode/{provider}"}, method = RequestMethod.GET) @ResponseBody - public SocialsProvider scanQRCode( + public ResponseEntity scanQRCode( HttpServletRequest request, @PathVariable("provider") String provider) { - AuthRequest authRequest =buildAuthRequest(provider); + String instId = WebContext.getInst().getId(); + AuthRequest authRequest = buildAuthRequest(instId,provider); if(authRequest == null ) { _logger.error("build authRequest fail ."); } - String state = request.getSession().getId(); + String state = authJwtService.genJwt(); authRequest.authorize(state); - SocialsProvider socialSignOnProvider = socialSignOnProviderService.get(provider); - SocialsProvider scanQRCodeProvider = new SocialsProvider(); - - scanQRCodeProvider.setId(socialSignOnProvider.getId()); - scanQRCodeProvider.setProvider(socialSignOnProvider.getProvider()); - scanQRCodeProvider.setProviderName(socialSignOnProvider.getProviderName()); - scanQRCodeProvider.setState(state); - scanQRCodeProvider.setClientId(socialSignOnProvider.getClientId()); - scanQRCodeProvider.setRedirectUri(applicationConfig.getServerPrefix()+ - "/logon/oauth20/callback/"+provider); - scanQRCodeProvider.setAgentId(socialSignOnProvider.getAgentId()); + SocialsProvider socialSignOnProvider = socialSignOnProviderService.get(instId,provider); + SocialsProvider scanQrProvider = new SocialsProvider(socialSignOnProvider); + scanQrProvider.setState(state); + scanQrProvider.setRedirectUri( + socialSignOnProviderService.getRedirectUri(WebContext.getBaseUri(), provider)); - return scanQRCodeProvider; - } + return new Message(scanQrProvider).buildResponse(); + } - @RequestMapping(value={"/callback/{provider}"}, method = RequestMethod.GET) - public ModelAndView callback(@PathVariable String provider) { + @RequestMapping(value={"/bind/{provider}"}, method = RequestMethod.POST) + public ResponseEntity bind(@PathVariable String provider) { //auth call back may exception try { - SocialsAssociate socialsAssociate = null; - this.provider=provider; - this.authCallback(); - _logger.debug(this.accountId); - socialsAssociate =new SocialsAssociate(); - socialsAssociate.setProvider(provider); - socialsAssociate.setSocialUserId(this.accountId); - //socialsAssociate.setInstId(WebContext.getInst(WebContext.getRequest())); - - //for login - String socialSignOnType= - (WebContext.getAttribute(SOCIALSIGNON_TYPE_SESSION)!=null) ? - (WebContext.getAttribute(SOCIALSIGNON_TYPE_SESSION).toString()) : ""; - - - if(socialSignOnType.equals(SOCIALSIGNON_TYPE.SOCIALSIGNON_TYPE_LOGON) - ||socialSignOnType.equals("")){ - socialSignOn(socialsAssociate); - - return WebContext.redirect("/index"); - }else{ - socialBind(socialsAssociate); - } - Object redirect_uri = WebContext.getAttribute(SOCIALSIGNON_SESSION_REDIRECT_URI); - if(redirect_uri != null){ - return WebContext.redirect(redirect_uri.toString()); - }else{ - return WebContext.forward("/socialsignon/list"); - } - + String instId = WebContext.getInst().getId(); + SocialsAssociate socialsAssociate = this.authCallback(instId,provider); + UserInfo userInfo = AuthorizationUtils.getUserInfo(); + socialsAssociate.setSocialUserInfo(accountJsonString); + socialsAssociate.setUserId(userInfo.getId()); + socialsAssociate.setUsername(userInfo.getUsername()); + //socialsAssociate.setAccessToken(JsonUtils.object2Json(accessToken)); + //socialsAssociate.setExAttribute(JsonUtils.object2Json(accessToken.getResponseObject())); + _logger.debug("Social Bind : "+socialsAssociate); + this.socialsAssociateService.delete(socialsAssociate); + this.socialsAssociateService.insert(socialsAssociate); + return new Message().buildResponse(); }catch(Exception e) { _logger.error("callback Exception ",e); } - return WebContext.redirect("/login"); - } - - public boolean socialBind(SocialsAssociate socialsAssociate){ - if(null == socialsAssociate) { - return false; - } - - UserInfo userInfo = AuthorizationUtils.getUserInfo(); - socialsAssociate.setSocialUserInfo(accountJsonString); - socialsAssociate.setUserId(userInfo.getId()); - socialsAssociate.setUsername(userInfo.getUsername()); - //socialsAssociate.setAccessToken(JsonUtils.object2Json(accessToken)); - //socialsAssociate.setExAttribute(JsonUtils.object2Json(accessToken.getResponseObject())); - _logger.debug("Social Bind : "+socialsAssociate); - this.socialsAssociateService.delete(socialsAssociate); - this.socialsAssociateService.insert(socialsAssociate); - return true; + return new Message(Message.ERROR).buildResponse(); } - - public boolean socialSignOn(SocialsAssociate socialsAssociate){ + + @RequestMapping(value={"/callback/{provider}"}, method = RequestMethod.GET) + public ResponseEntity callback(@PathVariable String provider) { + //auth call back may exception + try { + String instId = WebContext.getInst().getId(); + SocialsAssociate socialsAssociate = this.authCallback(instId,provider); - socialsAssociate=this.socialsAssociateService.get(socialsAssociate); + socialsAssociate=this.socialsAssociateService.get(socialsAssociate); - _logger.debug("Loaded SocialSignOn Socials Associate : "+socialsAssociate); + _logger.debug("Loaded SocialSignOn Socials Associate : "+socialsAssociate); - if(null == socialsAssociate) { - WebContext.getRequest().getSession().setAttribute( - WebAttributes.AUTHENTICATION_EXCEPTION, - new BadCredentialsException(WebContext.getI18nValue("login.error.social")) - ); - return false; - } + if(null == socialsAssociate) { + return new Message(Message.ERROR).buildResponse(); + } - _logger.debug("Social Sign On from {} mapping to user {}", + _logger.debug("Social Sign On from {} mapping to user {}", socialsAssociate.getProvider(),socialsAssociate.getUsername()); - LoginCredential loginCredential =new LoginCredential( - socialsAssociate.getUsername(),"",ConstsLoginType.SOCIALSIGNON); - loginCredential.setProvider(this.socialSignOnProvider.getProviderName()); - Authentication authentication = authenticationProvider.authentication(loginCredential,true); - if(authentication == null) { - String congress = authJwtService.createCongress(authentication); - } - //socialsAssociate.setAccessToken(JsonUtils.object2Json(this.accessToken)); - socialsAssociate.setSocialUserInfo(accountJsonString); - //socialsAssociate.setExAttribute(JsonUtils.object2Json(accessToken.getResponseObject())); + LoginCredential loginCredential =new LoginCredential( + socialsAssociate.getUsername(),"",ConstsLoginType.SOCIALSIGNON); + SocialsProvider socialSignOnProvider = socialSignOnProviderService.get(instId,provider); + loginCredential.setProvider(socialSignOnProvider.getProviderName()); + + Authentication authentication = authenticationProvider.authentication(loginCredential,true); + //socialsAssociate.setAccessToken(JsonUtils.object2Json(this.accessToken)); + socialsAssociate.setSocialUserInfo(accountJsonString); + //socialsAssociate.setExAttribute(JsonUtils.object2Json(accessToken.getResponseObject())); - this.socialsAssociateService.update(socialsAssociate); - return true; + this.socialsAssociateService.update(socialsAssociate); + return new Message(authJwtService.genAuthJwt(authentication)).buildResponse(); + }catch(Exception e) { + _logger.error("callback Exception ",e); + return new Message(Message.ERROR).buildResponse(); + } } } diff --git a/maxkey-authentications/maxkey-authentication-social/src/main/java/org/maxkey/authn/support/socialsignon/service/SocialSignOnProviderService.java b/maxkey-authentications/maxkey-authentication-social/src/main/java/org/maxkey/authn/support/socialsignon/service/SocialSignOnProviderService.java index baab7e703..6439c877a 100644 --- a/maxkey-authentications/maxkey-authentication-social/src/main/java/org/maxkey/authn/support/socialsignon/service/SocialSignOnProviderService.java +++ b/maxkey-authentications/maxkey-authentication-social/src/main/java/org/maxkey/authn/support/socialsignon/service/SocialSignOnProviderService.java @@ -24,7 +24,6 @@ import java.util.HashMap; import java.util.List; import java.util.concurrent.TimeUnit; -import org.maxkey.configuration.ApplicationConfig; import org.maxkey.constants.ConstsTimeInterval; import org.maxkey.crypto.password.PasswordReciprocal; import org.maxkey.entity.SocialsProvider; @@ -47,12 +46,12 @@ public class SocialSignOnProviderService{ private static final String DEFAULT_SELECT_STATEMENT = "select * from mxk_socials_provider where instid = ? and status = 1 order by sortindex"; - protected static final Cache socialSignOnProvidersStore = + protected static final Cache socialsProviderLoginStore = Caffeine.newBuilder() .expireAfterWrite(ConstsTimeInterval.ONE_HOUR, TimeUnit.MINUTES) .build(); - HashMapsocialSignOnProviderMaps=new HashMap(); + HashMapsocialSignOnProviderMaps = new HashMap(); private final JdbcTemplate jdbcTemplate; @@ -60,16 +59,20 @@ public class SocialSignOnProviderService{ this.jdbcTemplate=jdbcTemplate; } - public SocialsProvider get(String provider){ - return socialSignOnProviderMaps.get(provider); + public SocialsProvider get(String instId,String provider){ + return socialSignOnProviderMaps.get(instId + "_" + provider); } - public AuthRequest getAuthRequest(String provider,ApplicationConfig applicationConfig) throws Exception { + public String getRedirectUri(String baseUri,String provider) { + return baseUri + "/passport/callback/"+provider; + } + + public AuthRequest getAuthRequest(String instId,String provider,String baseUri) throws Exception { AuthRequest authRequest = null; AuthConfig authConfig = AuthConfig.builder() - .clientId(this.get(provider).getClientId()) - .clientSecret(this.get(provider).getClientSecret()) - .redirectUri(applicationConfig.getServerPrefix()+ "/logon/oauth20/callback/"+provider) + .clientId(this.get(instId,provider).getClientId()) + .clientSecret(this.get(instId,provider).getClientSecret()) + .redirectUri(getRedirectUri(baseUri , provider)) .build(); if(provider.equalsIgnoreCase("WeChatOpen")) { @@ -175,42 +178,37 @@ public class SocialSignOnProviderService{ return null; } - public SocialsProviderLogin loadSocialsProviders(String instId) { - SocialsProviderLogin ssl = socialSignOnProvidersStore.getIfPresent(instId); - if(ssl == null) { - List listSocialsProvider=jdbcTemplate.query( + public SocialsProviderLogin loadSocials(String instId) { + SocialsProviderLogin socialsLogin = socialsProviderLoginStore.getIfPresent(instId); + if(socialsLogin == null) { + List listSocialsProvider = jdbcTemplate.query( DEFAULT_SELECT_STATEMENT, new SocialsProviderRowMapper(),instId); _logger.trace("query SocialsProvider " + listSocialsProvider); - List socialSignOnProviders = new ArrayList(); - ssl = new SocialsProviderLogin(socialSignOnProviders); - + socialsLogin = new SocialsProviderLogin(socialSignOnProviders); for(SocialsProvider socialsProvider : listSocialsProvider){ - socialSignOnProviderMaps.put(socialsProvider.getProvider(), socialsProvider); - _logger.debug("Social Provider " + socialsProvider.getProvider() - + "(" + socialsProvider.getProviderName()+")"); + _logger.debug("Social Provider {} ({})" , + socialsProvider.getProvider() ,socialsProvider.getProviderName()); + if(!socialsProvider.getHidden().equals("true")) { - socialSignOnProviders.add(socialsProvider); + socialSignOnProviders.add(new SocialsProvider(socialsProvider)); } - if(socialsProvider.getProvider().equalsIgnoreCase("workweixin")) { - ssl.setWorkWeixinLogin(socialsProvider.getScanCode()); - }else if(socialsProvider.getProvider().equalsIgnoreCase("dingtalk")) { - ssl.setDingTalkLogin(socialsProvider.getScanCode()); - }else if(socialsProvider.getProvider().equalsIgnoreCase("feishu")) { - ssl.setFeiShuLogin(socialsProvider.getScanCode()); - }else if(socialsProvider.getProvider().equalsIgnoreCase("welink")) { - ssl.setWeLinkLogin(socialsProvider.getScanCode()); + if(socialsProvider.getScanCode().equalsIgnoreCase("true")) { + socialsLogin.setQrScan(socialsProvider.getProvider()); } + + //add to socialSignOnProviderMaps + socialSignOnProviderMaps.put(instId + "_" + socialsProvider.getProvider() , socialsProvider); } - _logger.debug("social SignOn Providers Login {}" , ssl); + _logger.debug("social SignOn Providers Login {}" , socialsLogin); - socialSignOnProvidersStore.put(instId, ssl); + socialsProviderLoginStore.put(instId, socialsLogin); } - return ssl; + return socialsLogin; } @@ -232,6 +230,7 @@ public class SocialSignOnProviderService{ socialsProvider.setSortIndex(rs.getInt("sortindex")); socialsProvider.setScanCode(rs.getString("scancode")); socialsProvider.setStatus(rs.getInt("status")); + socialsProvider.setInstId(rs.getString("instid")); return socialsProvider; } } diff --git a/maxkey-authentications/maxkey-authentication-social/src/main/java/org/maxkey/autoconfigure/SocialSignOnAutoConfiguration.java b/maxkey-authentications/maxkey-authentication-social/src/main/java/org/maxkey/autoconfigure/SocialSignOnAutoConfiguration.java index afc1eb021..b4c6f7724 100644 --- a/maxkey-authentications/maxkey-authentication-social/src/main/java/org/maxkey/autoconfigure/SocialSignOnAutoConfiguration.java +++ b/maxkey-authentications/maxkey-authentication-social/src/main/java/org/maxkey/autoconfigure/SocialSignOnAutoConfiguration.java @@ -43,7 +43,7 @@ public class SocialSignOnAutoConfiguration implements InitializingBean { JdbcTemplate jdbcTemplate) throws IOException { SocialSignOnProviderService socialSignOnProviderService = new SocialSignOnProviderService(jdbcTemplate); //load default Social Providers from database - socialSignOnProviderService.loadSocialsProviders("1"); + socialSignOnProviderService.loadSocials("1"); _logger.debug("SocialSignOnProviderService inited."); return socialSignOnProviderService; } diff --git a/maxkey-common/src/test/java/org/maxkey/crypto/signature/HMAC512ServiceTest.java b/maxkey-common/src/test/java/org/maxkey/crypto/signature/HMAC512ServiceTest.java index aad22f705..d5c267615 100644 --- a/maxkey-common/src/test/java/org/maxkey/crypto/signature/HMAC512ServiceTest.java +++ b/maxkey-common/src/test/java/org/maxkey/crypto/signature/HMAC512ServiceTest.java @@ -27,8 +27,9 @@ public class HMAC512ServiceTest { // TODO Auto-generated method stub String key ="7heM-14BtxjyKPuH3ITIm7q2-ps5MuBirWCsrrdbzzSAOuSPrbQYiaJ54AeA0uH2XdkYy3hHAkTFIsieGkyqxOJZ_dQzrCbaYISH9rhUZAKYx8tUY0wkE4ArOC6LqHDJarR6UIcMsARakK9U4dhoOPO1cj74XytemI-w6ACYfzRUn_Rn4e-CQMcnD1C56oNEukwalf06xVgXl41h6K8IBEzLVod58y_VfvFn-NGWpNG0fy_Qxng6dg8Dgva2DobvzMN2eejHGLGB-x809MvC4zbG7CKNVlcrzMYDt2Gt2sOVDrt2l9YqJNfgaLFjrOEVw5cuXemGkX1MvHj6TAsbLg"; HMAC512Service HMAC512Service = new HMAC512Service(key); - String jwt = HMAC512Service.sign("hkkkk"); - boolean isverify = HMAC512Service.verify(jwt); + String sign = HMAC512Service.sign("hkkkk"); + System.out.println(sign); + boolean isverify = HMAC512Service.verify(sign); System.out.println(isverify); } diff --git a/maxkey-core/src/main/java/org/maxkey/entity/SocialsProvider.java b/maxkey-core/src/main/java/org/maxkey/entity/SocialsProvider.java index d0ce7e4f8..bf48c5fac 100644 --- a/maxkey-core/src/main/java/org/maxkey/entity/SocialsProvider.java +++ b/maxkey-core/src/main/java/org/maxkey/entity/SocialsProvider.java @@ -91,6 +91,16 @@ public class SocialsProvider extends JpaBaseEntity implements Serializable { public SocialsProvider() { } + + public SocialsProvider(SocialsProvider copy) { + this.clientId = copy.getClientId(); + this.id = copy.getId(); + this.provider = copy.getProvider(); + this.providerName = copy.getProviderName(); + this.agentId = copy.getAgentId(); + this.icon = copy.getIcon(); + this.scanCode = copy.getScanCode(); + } public String getProvider() { return provider; diff --git a/maxkey-core/src/main/java/org/maxkey/entity/SocialsProviderLogin.java b/maxkey-core/src/main/java/org/maxkey/entity/SocialsProviderLogin.java index dd08dbaee..16b6e786a 100644 --- a/maxkey-core/src/main/java/org/maxkey/entity/SocialsProviderLogin.java +++ b/maxkey-core/src/main/java/org/maxkey/entity/SocialsProviderLogin.java @@ -33,56 +33,28 @@ public class SocialsProviderLogin implements Serializable { */ private static final long serialVersionUID = -2672107566766342357L; - List socialSignOnProviders = new ArrayList(); + List providers = new ArrayList(); - String dingTalkLogin = "none"; - - String workWeixinLogin = "none"; - - String feiShuLogin = "none"; - - String weLinkLogin = "none"; + String qrScan = null; public SocialsProviderLogin(List socialSignOnProviders) { super(); - this.socialSignOnProviders = socialSignOnProviders; - } - - public String getDingTalkLogin() { - return dingTalkLogin; - } - - public void setDingTalkLogin(String dingTalkLogin) { - this.dingTalkLogin = dingTalkLogin; + this.providers = socialSignOnProviders; } - public String getWorkWeixinLogin() { - return workWeixinLogin; + public String getQrScan() { + return qrScan; } - public void setWorkWeixinLogin(String workWeixinLogin) { - this.workWeixinLogin = workWeixinLogin; + public void setQrScan(String qrScan) { + this.qrScan = qrScan; } - public String getFeiShuLogin() { - return feiShuLogin; + public List getProviders() { + return providers; } - public void setFeiShuLogin(String feiShuLogin) { - this.feiShuLogin = feiShuLogin; + public void setProviders(List providers) { + this.providers = providers; } - - public String getWeLinkLogin() { - return weLinkLogin; - } - - public void setWeLinkLogin(String weLinkLogin) { - this.weLinkLogin = weLinkLogin; - } - - public List getSocialSignOnProviders() { - return socialSignOnProviders; - } - - } diff --git a/maxkey-core/src/main/java/org/maxkey/persistence/repository/InstitutionsRepository.java b/maxkey-core/src/main/java/org/maxkey/persistence/repository/InstitutionsRepository.java index 0ac7a5b3b..6677d1268 100644 --- a/maxkey-core/src/main/java/org/maxkey/persistence/repository/InstitutionsRepository.java +++ b/maxkey-core/src/main/java/org/maxkey/persistence/repository/InstitutionsRepository.java @@ -36,10 +36,7 @@ public class InstitutionsRepository { private static Logger _logger = LoggerFactory.getLogger(InstitutionsRepository.class); private static final String SELECT_STATEMENT = - "select * from mxk_institutions where domain = ? " ; - - private static final String SELECT_STATEMENT_BY_ID = - "select * from mxk_institutions where id = ? " ; + "select * from mxk_institutions where id = ? or domain = ? " ; protected static final Cache institutionsStore = Caffeine.newBuilder() @@ -54,33 +51,13 @@ public class InstitutionsRepository { public InstitutionsRepository(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } - - public Institutions findByDomain(String domain) { - _logger.trace(" domain {}" , domain); - Institutions inst = institutionsStore.getIfPresent(domain); - if(inst == null) { - List institutions = - jdbcTemplate.query(SELECT_STATEMENT,new InstitutionsRowMapper(),domain); - - if (institutions != null && institutions.size() > 0) { - inst = institutions.get(0); - institutionsStore.put(domain, inst); - mapper.put(inst.getId(), domain); - }else { - //default institution - inst = get("1"); - } - } - - return inst; - } - public Institutions get(String instId) { - _logger.trace(" instId {}" , instId); - Institutions inst = institutionsStore.getIfPresent(mapper.get(instId)==null ? "1" : mapper.get(instId) ); + public Institutions get(String instIdOrDomain) { + _logger.trace(" instId {}" , instIdOrDomain); + Institutions inst = institutionsStore.getIfPresent(mapper.get(instIdOrDomain)==null ? "1" : mapper.get(instIdOrDomain) ); if(inst == null) { List institutions = - jdbcTemplate.query(SELECT_STATEMENT_BY_ID,new InstitutionsRowMapper(),instId); + jdbcTemplate.query(SELECT_STATEMENT,new InstitutionsRowMapper(),instIdOrDomain,instIdOrDomain); if (institutions != null && institutions.size() > 0) { inst = institutions.get(0); diff --git a/maxkey-core/src/main/java/org/maxkey/web/WebConstants.java b/maxkey-core/src/main/java/org/maxkey/web/WebConstants.java index 445966cf8..af16d9ee6 100644 --- a/maxkey-core/src/main/java/org/maxkey/web/WebConstants.java +++ b/maxkey-core/src/main/java/org/maxkey/web/WebConstants.java @@ -49,6 +49,8 @@ public class WebConstants { public static final String CURRENT_INST = "current_inst"; public final static String INST_COOKIE_NAME = "mxk_inst"; + + public final static String FRONTEND_BASE_URI = "mxk_frontend_base_uri"; // SPRING_SECURITY_SAVED_REQUEST public static final String FIRST_SAVED_REQUEST_PARAMETER diff --git a/maxkey-core/src/main/java/org/maxkey/web/WebContext.java b/maxkey-core/src/main/java/org/maxkey/web/WebContext.java index 5b544d5be..a1302048b 100644 --- a/maxkey-core/src/main/java/org/maxkey/web/WebContext.java +++ b/maxkey-core/src/main/java/org/maxkey/web/WebContext.java @@ -31,6 +31,7 @@ import javax.servlet.http.HttpSession; import org.apache.commons.logging.LogFactory; import org.maxkey.configuration.ApplicationConfig; +import org.maxkey.entity.Institutions; import org.maxkey.util.DateUtils; import org.maxkey.util.IdGenerator; import org.maxkey.web.message.Message; @@ -309,6 +310,15 @@ public final class WebContext { public static String getParameter(String name) { return getRequest().getParameter(name); } + + public static Institutions getInst() { + return (Institutions)getAttribute(WebConstants.CURRENT_INST); + } + + public static String getBaseUri() { + return (String)getAttribute(WebConstants.FRONTEND_BASE_URI); + } + /** * encoding encodingString by ApplicationConfig. diff --git a/maxkey-core/src/main/java/org/maxkey/web/WebInstRequestFilter.java b/maxkey-core/src/main/java/org/maxkey/web/WebInstRequestFilter.java index 31be77b84..3c8c86769 100644 --- a/maxkey-core/src/main/java/org/maxkey/web/WebInstRequestFilter.java +++ b/maxkey-core/src/main/java/org/maxkey/web/WebInstRequestFilter.java @@ -24,7 +24,6 @@ import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.maxkey.configuration.ApplicationConfig; @@ -37,7 +36,9 @@ import org.springframework.web.filter.GenericFilterBean; public class WebInstRequestFilter extends GenericFilterBean { final static Logger _logger = LoggerFactory.getLogger(GenericFilterBean.class); - public final static String HEADER_HOST = "host"; + public final static String HEADER_HOST = "host"; + public final static String HEADER_HOSTNAME = "hostname"; + public final static String HEADER_ORIGIN = "Origin"; InstitutionsRepository institutionsRepository; @@ -51,17 +52,29 @@ public class WebInstRequestFilter extends GenericFilterBean { if(request.getSession().getAttribute(WebConstants.CURRENT_INST) == null) { WebContext.printRequest(request); - String host = request.getHeader(HEADER_HOST); + String host = request.getHeader(HEADER_HOSTNAME); + _logger.trace("hostname {}",host); + if(StringUtils.isEmpty(host)) { + host = request.getHeader(HEADER_HOST); + _logger.trace("host {}",host); + } if(StringUtils.isEmpty(host)) { host = applicationConfig.getDomainName(); + _logger.trace("config domain {}",host); } if(host.indexOf(":")> -1 ) { host = host.split(":")[0]; + _logger.trace("domain split {}",host); } - Institutions institution = institutionsRepository.findByDomain(host); + Institutions institution = institutionsRepository.get(host); _logger.trace("{}" ,institution); request.getSession().setAttribute(WebConstants.CURRENT_INST, institution); - WebContext.setCookie((HttpServletResponse)servletResponse, host, WebConstants.INST_COOKIE_NAME, institution.getId()); + + String origin = request.getHeader(HEADER_ORIGIN); + if(StringUtils.isEmpty(origin)) { + origin = applicationConfig.getFrontendUri(); + } + request.getSession().setAttribute(WebConstants.FRONTEND_BASE_URI, origin); } chain.doFilter(servletRequest, servletResponse); } diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/endpoint/LoginEntryPoint.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/endpoint/LoginEntryPoint.java index 71d40cece..8b72a0fd8 100644 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/endpoint/LoginEntryPoint.java +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/endpoint/LoginEntryPoint.java @@ -17,14 +17,9 @@ package org.maxkey.web.endpoint; -import java.io.IOException; import java.util.HashMap; import java.util.regex.Pattern; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import org.apache.commons.lang3.StringUtils; import org.maxkey.authn.AbstractAuthenticationProvider; import org.maxkey.authn.LoginCredential; @@ -32,7 +27,6 @@ import org.maxkey.authn.jwt.AuthJwt; import org.maxkey.authn.jwt.AuthJwtService; import org.maxkey.authn.support.kerberos.KerberosService; import org.maxkey.authn.support.socialsignon.service.SocialSignOnProviderService; -import org.maxkey.authn.web.AuthorizationUtils; import org.maxkey.configuration.ApplicationConfig; import org.maxkey.entity.Institutions; import org.maxkey.entity.Message; @@ -50,13 +44,9 @@ import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.servlet.ModelAndView; - import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; @@ -66,6 +56,7 @@ import io.swagger.v3.oas.annotations.tags.Tag; */ @Tag(name = "1-1-登录接口文档模块") @Controller +@RequestMapping(value = "/login") public class LoginEntryPoint { private static Logger _logger = LoggerFactory.getLogger(LoginEntryPoint.class); @@ -109,106 +100,74 @@ public class LoginEntryPoint { * @return */ @Operation(summary = "登录接口", description = "用户登录地址",method="GET") - @RequestMapping(value={"/login"}) - public ModelAndView login(HttpServletRequest request) { - _logger.debug("LoginController /login."); - - boolean isAuthenticated= AuthorizationUtils.isAuthenticated(); - - if(isAuthenticated){ - return WebContext.redirect("/forwardindex"); - } - - _logger.trace("Session Timeout MaxInactiveInterval " + WebContext.getRequest().getSession().getMaxInactiveInterval()); - + @RequestMapping(value={"/get"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public ResponseEntity get() { + _logger.debug("LoginController /get."); //for normal login - ModelAndView modelAndView = new ModelAndView("login"); - modelAndView.addObject("isRemeberMe", applicationConfig.getLoginConfig().isRemeberMe()); - modelAndView.addObject("isKerberos", applicationConfig.getLoginConfig().isKerberos()); - modelAndView.addObject("isMfa", applicationConfig.getLoginConfig().isMfa()); + HashMap model = new HashMap(); + model.put("isRemeberMe", applicationConfig.getLoginConfig().isRemeberMe()); + model.put("isKerberos", applicationConfig.getLoginConfig().isKerberos()); if(applicationConfig.getLoginConfig().isMfa()) { - modelAndView.addObject("otpType", tfaOtpAuthn.getOtpType()); - modelAndView.addObject("otpInterval", tfaOtpAuthn.getInterval()); + model.put("otpType", tfaOtpAuthn.getOtpType()); + model.put("otpInterval", tfaOtpAuthn.getInterval()); } if( applicationConfig.getLoginConfig().isKerberos()){ - modelAndView.addObject("userDomainUrlJson", kerberosService.buildKerberosProxys()); + model.put("userDomainUrlJson", kerberosService.buildKerberosProxys()); } + Institutions inst = (Institutions)WebContext.getAttribute(WebConstants.CURRENT_INST); - modelAndView.addObject("captchaSupport", inst.getCaptchaSupport()); - modelAndView.addObject("captchaType", inst.getCaptchaType()); - modelAndView.addObject("sessionid", WebContext.getSession().getId()); - //modelAndView.addObject("jwtToken",jwtLoginService.buildLoginJwt()); + model.put("inst", inst); + model.put("captcha", inst.getCaptchaSupport()); + model.put("captchaType", inst.getCaptchaType()); + model.put("state", authJwtService.genJwt()); //load Social Sign On Providers - modelAndView.addObject("sspLogin", socialSignOnProviderService.loadSocialsProviders(inst.getId())); + model.put("socials", socialSignOnProviderService.loadSocials(inst.getId())); - Object loginErrorMessage=WebContext.getAttribute(WebConstants.LOGIN_ERROR_SESSION_MESSAGE); - modelAndView.addObject("loginErrorMessage", loginErrorMessage==null?"":loginErrorMessage); - WebContext.removeAttribute(WebConstants.LOGIN_ERROR_SESSION_MESSAGE); - return modelAndView; + return new Message>(model).buildResponse(); } - @RequestMapping(value={"/logon.do"}) - public ModelAndView logon( - HttpServletRequest request, - HttpServletResponse response, - @ModelAttribute("loginCredential") LoginCredential loginCredential) throws ServletException, IOException { - - authenticationProvider.authenticate(loginCredential); - if (AuthorizationUtils.isAuthenticated()) { - return WebContext.redirect("/forwardindex"); - } else { - return WebContext.redirect("/login"); - } - - } - - - @RequestMapping("/login/{username}") - @ResponseBody - public HashMap queryLoginUserAuth(@PathVariable("username") String username) { - UserInfo userInfo=userInfoService.findByUsername(username); - - HashMap authnType=new HashMap (); - authnType.put("authnType", userInfo.getAuthnType()); - authnType.put("appLoginAuthnType", userInfo.getAppLoginAuthnType()); - - return authnType; - } - - @RequestMapping("/login/sendsms/{mobile}") - @ResponseBody - public String produceOtp(@PathVariable("mobile") String mobile,HttpServletRequest request) { - UserInfo queryUserInfo=userInfoService.findByEmailMobile(mobile); - if(queryUserInfo!=null) { - //otpAuthnService.getByInstId(WebContext.getInst(request)).produce(queryUserInfo); - return "ok"; + @RequestMapping(value={"/sendotp/{mobile}"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public ResponseEntity produceOtp(@PathVariable("mobile") String mobile) { + UserInfo userInfo=userInfoService.findByEmailMobile(mobile); + if(userInfo != null) { + otpAuthnService.getByInstId(WebContext.getInst().getId()).produce(userInfo); + return new Message(Message.SUCCESS).buildResponse(); } - return "fail"; + return new Message(Message.FAIL).buildResponse(); } - - - //////////////////// - + /** + * normal + * @param loginCredential + * @return + */ @RequestMapping(value={"/signin"}, produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity signin( @RequestBody LoginCredential loginCredential) { - //for congress + + Authentication authentication = authenticationProvider.authenticate(loginCredential); + if(authentication == null) { + return new Message(Message.FAIL).buildResponse(); + } + return new Message(authJwtService.genAuthJwt(authentication)).buildResponse(); + } + + /** + * for congress + * @param loginCredential + * @return + */ + @RequestMapping(value={"/congress"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public ResponseEntity congress( @RequestBody LoginCredential loginCredential) { if(StringUtils.isNotBlank(loginCredential.getCongress())){ AuthJwt authJwt = authJwtService.consumeCongress(loginCredential.getCongress()); if(authJwt != null) { return new Message(authJwt).buildResponse(); } } - - //normal - Authentication authentication = authenticationProvider.authenticate(loginCredential); - if(authentication == null) { - return new Message(Message.FAIL).buildResponse(); - } - return new Message(authJwtService.generateAuthJwt(authentication)).buildResponse(); + return new Message(Message.FAIL).buildResponse(); } } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/contorller/LoginEntryPoint.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/contorller/LoginEntryPoint.java index f06b646de..42ac00b7e 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/contorller/LoginEntryPoint.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/contorller/LoginEntryPoint.java @@ -90,8 +90,8 @@ public class LoginEntryPoint { @RequestMapping(value={"/signin"}, produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity signin( @RequestBody LoginCredential loginCredential) { Authentication authentication = authenticationProvider.authenticate(loginCredential); - String jwt = authJwtService.generateToken(authentication); - return new Message(new AuthJwt(jwt, authentication)).buildResponse(); + AuthJwt authJwt = authJwtService.genAuthJwt(authentication); + return new Message(authJwt).buildResponse(); } } -- GitLab