提交 586e473e 编写于 作者: M MaxKey

sso

上级 d9af91de
...@@ -35,7 +35,6 @@ import org.slf4j.LoggerFactory; ...@@ -35,7 +35,6 @@ import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
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;
/** /**
...@@ -71,59 +70,15 @@ public abstract class AbstractAuthenticationProvider { ...@@ -71,59 +70,15 @@ public abstract class AbstractAuthenticationProvider {
protected abstract String getProviderName(); 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") @SuppressWarnings("rawtypes")
public boolean supports(Class authentication) { public boolean supports(Class authentication) {
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(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) { protected void changeSession(Authentication authentication) {
HashMap<String,Object> sessionAttributeMap = new HashMap<String,Object>(); HashMap<String,Object> sessionAttributeMap = new HashMap<String,Object>();
......
...@@ -24,6 +24,7 @@ import org.maxkey.authn.online.OnlineTicketService; ...@@ -24,6 +24,7 @@ import org.maxkey.authn.online.OnlineTicketService;
import org.maxkey.authn.realm.AbstractAuthenticationRealm; import org.maxkey.authn.realm.AbstractAuthenticationRealm;
import org.maxkey.authn.web.AuthorizationUtils; import org.maxkey.authn.web.AuthorizationUtils;
import org.maxkey.configuration.ApplicationConfig; import org.maxkey.configuration.ApplicationConfig;
import org.maxkey.constants.ConstsLoginType;
import org.maxkey.entity.Institutions; import org.maxkey.entity.Institutions;
import org.maxkey.entity.UserInfo; import org.maxkey.entity.UserInfo;
import org.maxkey.password.onetimepwd.AbstractOtpAuthn; import org.maxkey.password.onetimepwd.AbstractOtpAuthn;
...@@ -35,6 +36,7 @@ import org.slf4j.LoggerFactory; ...@@ -35,6 +36,7 @@ import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.security.web.authentication.WebAuthenticationDetails;
...@@ -71,47 +73,73 @@ public class RealmAuthenticationProvider extends AbstractAuthenticationProvider ...@@ -71,47 +73,73 @@ public class RealmAuthenticationProvider extends AbstractAuthenticationProvider
this.onlineTicketServices = onlineTicketServices; this.onlineTicketServices = onlineTicketServices;
} }
@Override @Override
protected Authentication doInternalAuthenticate(LoginCredential loginCredential) { public Authentication authenticate(LoginCredential loginCredential) {
UsernamePasswordAuthenticationToken authenticationToken = null;
_logger.debug("authentication " + loginCredential); _logger.debug("Trying to authenticate user '{}' via {}",
loginCredential.getPrincipal(), getProviderName());
//sessionValid(loginCredential.getSessionId()); try {
//jwtTokenValid(j_jwtToken); _logger.debug("authentication " + loginCredential);
authTypeValid(loginCredential.getAuthType()); //sessionValid(loginCredential.getSessionId());
Institutions inst = (Institutions)WebContext.getAttribute(WebConstants.CURRENT_INST); //jwtTokenValid(j_jwtToken);
if(inst.getCaptchaSupport().equalsIgnoreCase("YES")) {
captchaValid(loginCredential.getCaptcha(),loginCredential.getAuthType()); authTypeValid(loginCredential.getAuthType());
}
Institutions inst = (Institutions)WebContext.getAttribute(WebConstants.CURRENT_INST);
emptyPasswordValid(loginCredential.getPassword()); if(inst.getCaptchaSupport().equalsIgnoreCase("YES")) {
captchaValid(loginCredential.getCaptcha(),loginCredential.getAuthType());
UserInfo userInfo = null; }
emptyUsernameValid(loginCredential.getUsername()); emptyPasswordValid(loginCredential.getPassword());
userInfo = loadUserInfo(loginCredential.getUsername(),loginCredential.getPassword()); UserInfo userInfo = null;
statusValid(loginCredential , userInfo); emptyUsernameValid(loginCredential.getUsername());
//mfa
tftcaptchaValid(loginCredential.getOtpCaptcha(),loginCredential.getAuthType(),userInfo); userInfo = loadUserInfo(loginCredential.getUsername(),loginCredential.getPassword());
//Validate PasswordPolicy statusValid(loginCredential , userInfo);
authenticationRealm.getPasswordPolicyValidator().passwordPolicyValid(userInfo); //mfa
if(loginCredential.getAuthType().equalsIgnoreCase(AuthType.MOBILE)) { tftcaptchaValid(loginCredential.getOtpCaptcha(),loginCredential.getAuthType(),userInfo);
mobilecaptchaValid(loginCredential.getPassword(),loginCredential.getAuthType(),userInfo);
}else { //Validate PasswordPolicy
//Match password authenticationRealm.getPasswordPolicyValidator().passwordPolicyValid(userInfo);
authenticationRealm.passwordMatches(userInfo, loginCredential.getPassword()); 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; return authenticationToken;
} }
......
...@@ -58,12 +58,22 @@ public class AuthJwtService { ...@@ -58,12 +58,22 @@ public class AuthJwtService {
this.hmac512Service = new HMAC512Service(authJwkConfig.getSecret()); 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()); SigninPrincipal principal = ((SigninPrincipal)authentication.getPrincipal());
UserInfo userInfo = principal.getUserInfo(); UserInfo userInfo = principal.getUserInfo();
DateTime currentDateTime = DateTime.now(); DateTime currentDateTime = DateTime.now();
...@@ -75,7 +85,7 @@ public class AuthJwtService { ...@@ -75,7 +85,7 @@ public class AuthJwtService {
JWTClaimsSet jwtClaims =new JWTClaimsSet.Builder() JWTClaimsSet jwtClaims =new JWTClaimsSet.Builder()
.issuer(authJwkConfig.getIssuer()) .issuer(authJwkConfig.getIssuer())
.subject(subject) .subject(subject)
.jwtID(principal.getOnlineTicket().getFormattedTicketId()) .jwtID(principal.getOnlineTicket().getTicketId())
.issueTime(currentDateTime.toDate()) .issueTime(currentDateTime.toDate())
.expirationTime(expirationTime) .expirationTime(expirationTime)
.claim("locale", userInfo.getLocale()) .claim("locale", userInfo.getLocale())
...@@ -83,15 +93,54 @@ public class AuthJwtService { ...@@ -83,15 +93,54 @@ public class AuthJwtService {
.claim("institution", userInfo.getInstId()) .claim("institution", userInfo.getInstId())
.build(); .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( JWTClaimsSet jwtClaims =new JWTClaimsSet.Builder()
new JWSHeader(JWSAlgorithm.HS512), .issuer(authJwkConfig.getIssuer())
jwtClaims); .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) { public boolean validateJwtToken(String authToken) {
...@@ -114,7 +163,7 @@ public class AuthJwtService { ...@@ -114,7 +163,7 @@ public class AuthJwtService {
congressService.store( congressService.store(
congress, congress,
new AuthJwt( new AuthJwt(
generateToken(authentication), genJwt(authentication),
authentication) authentication)
); );
return congress; return congress;
......
...@@ -25,6 +25,7 @@ import org.maxkey.authn.jwt.AuthJwtService; ...@@ -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.SocialSignOnProviderService;
import org.maxkey.authn.support.socialsignon.service.SocialsAssociateService; import org.maxkey.authn.support.socialsignon.service.SocialsAssociateService;
import org.maxkey.configuration.ApplicationConfig; import org.maxkey.configuration.ApplicationConfig;
import org.maxkey.entity.SocialsAssociate;
import org.maxkey.entity.SocialsProvider; import org.maxkey.entity.SocialsProvider;
import org.maxkey.web.WebContext; import org.maxkey.web.WebContext;
import org.slf4j.Logger; import org.slf4j.Logger;
...@@ -42,34 +43,11 @@ import me.zhyd.oauth.request.AuthRequest; ...@@ -42,34 +43,11 @@ import me.zhyd.oauth.request.AuthRequest;
*/ */
public class AbstractSocialSignOnEndpoint { public class AbstractSocialSignOnEndpoint {
final static Logger _logger = LoggerFactory.getLogger(AbstractSocialSignOnEndpoint.class); 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 AuthRequest authRequest;
protected String accountJsonString; protected String accountJsonString;
protected String accountId;
protected String provider;
@Autowired @Autowired
protected SocialSignOnProviderService socialSignOnProviderService; protected SocialSignOnProviderService socialSignOnProviderService;
...@@ -86,15 +64,13 @@ public class AbstractSocialSignOnEndpoint { ...@@ -86,15 +64,13 @@ public class AbstractSocialSignOnEndpoint {
@Autowired @Autowired
ApplicationConfig applicationConfig; ApplicationConfig applicationConfig;
protected AuthRequest buildAuthRequest(String provider){ protected AuthRequest buildAuthRequest(String instId,String provider){
try { try {
SocialsProvider socialSignOnProvider = socialSignOnProviderService.get(provider); SocialsProvider socialSignOnProvider = socialSignOnProviderService.get(instId,provider);
_logger.debug("socialSignOn Provider : "+socialSignOnProvider); _logger.debug("socialSignOn Provider : "+socialSignOnProvider);
if(socialSignOnProvider!=null){ if(socialSignOnProvider != null){
authRequest=socialSignOnProviderService.getAuthRequest(provider,applicationConfig); authRequest = socialSignOnProviderService.getAuthRequest(instId,provider,WebContext.getBaseUri());
WebContext.setAttribute(SOCIALSIGNON_OAUTH_SERVICE_SESSION, authRequest);
WebContext.setAttribute(SOCIALSIGNON_PROVIDER_SESSION, socialSignOnProvider);
return authRequest; return authRequest;
} }
}catch(Exception e) { }catch(Exception e) {
...@@ -103,7 +79,8 @@ public class AbstractSocialSignOnEndpoint { ...@@ -103,7 +79,8 @@ public class AbstractSocialSignOnEndpoint {
return null; return null;
} }
protected String authCallback() throws Exception { protected SocialsAssociate authCallback(String instId,String provider) throws Exception {
SocialsAssociate socialsAssociate = null;
AuthCallback authCallback=new AuthCallback(); AuthCallback authCallback=new AuthCallback();
authCallback.setCode(WebContext.getRequest().getParameter("code")); authCallback.setCode(WebContext.getRequest().getParameter("code"));
authCallback.setAuth_code(WebContext.getRequest().getParameter("auth_code")); authCallback.setAuth_code(WebContext.getRequest().getParameter("auth_code"));
...@@ -111,24 +88,16 @@ public class AbstractSocialSignOnEndpoint { ...@@ -111,24 +88,16 @@ public class AbstractSocialSignOnEndpoint {
authCallback.setAuthorization_code(WebContext.getRequest().getParameter("authorization_code")); authCallback.setAuthorization_code(WebContext.getRequest().getParameter("authorization_code"));
authCallback.setOauth_verifier(WebContext.getRequest().getParameter("oauthVerifier")); authCallback.setOauth_verifier(WebContext.getRequest().getParameter("oauthVerifier"));
authCallback.setState(WebContext.getRequest().getParameter("state")); 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.getCode(),
authCallback.getAuth_code(), authCallback.getAuth_code(),
authCallback.getOauth_token(), authCallback.getOauth_token(),
authCallback.getAuthorization_code(), authCallback.getAuthorization_code(),
authCallback.getOauth_verifier()); authCallback.getOauth_verifier(),
_logger.debug("Callback state {} , sessionId {}", authCallback.getState());
authCallback.getState(),WebContext.getRequest().getSession().getId()
);
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 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"); _logger.debug("session authRequest is null , renew one");
} }
...@@ -139,10 +108,13 @@ public class AbstractSocialSignOnEndpoint { ...@@ -139,10 +108,13 @@ public class AbstractSocialSignOnEndpoint {
AuthResponse<?> authResponse=authRequest.login(authCallback); AuthResponse<?> authResponse=authRequest.login(authCallback);
_logger.debug("Response : " + authResponse.getData()); _logger.debug("Response : " + authResponse.getData());
accountId=socialSignOnProviderService.getAccountId(provider, authResponse); socialsAssociate =new SocialsAssociate();
socialsAssociate.setProvider(provider);
_logger.debug("getAccountId : " + accountId); socialsAssociate.setSocialUserId(
return accountId; socialSignOnProviderService.getAccountId(provider, authResponse));
socialsAssociate.setInstId(instId);
return socialsAssociate;
} }
} }
...@@ -23,24 +23,23 @@ package org.maxkey.authn.support.socialsignon; ...@@ -23,24 +23,23 @@ package org.maxkey.authn.support.socialsignon;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import org.maxkey.authn.LoginCredential; import org.maxkey.authn.LoginCredential;
import org.maxkey.authn.jwt.AuthJwt;
import org.maxkey.authn.web.AuthorizationUtils; import org.maxkey.authn.web.AuthorizationUtils;
import org.maxkey.constants.ConstsLoginType; import org.maxkey.constants.ConstsLoginType;
import org.maxkey.entity.Message;
import org.maxkey.entity.SocialsAssociate; import org.maxkey.entity.SocialsAssociate;
import org.maxkey.entity.SocialsProvider; import org.maxkey.entity.SocialsProvider;
import org.maxkey.entity.UserInfo; import org.maxkey.entity.UserInfo;
import org.maxkey.web.WebContext; import org.maxkey.web.WebContext;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; 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.core.Authentication;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import me.zhyd.oauth.request.AuthRequest; import me.zhyd.oauth.request.AuthRequest;
/** /**
...@@ -51,153 +50,99 @@ import me.zhyd.oauth.request.AuthRequest; ...@@ -51,153 +50,99 @@ import me.zhyd.oauth.request.AuthRequest;
@RequestMapping(value = "/logon/oauth20") @RequestMapping(value = "/logon/oauth20")
public class SocialSignOnEndpoint extends AbstractSocialSignOnEndpoint{ public class SocialSignOnEndpoint extends AbstractSocialSignOnEndpoint{
final static Logger _logger = LoggerFactory.getLogger(SocialSignOnEndpoint.class); 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) @RequestMapping(value={"/authorize/{provider}"}, method = RequestMethod.GET)
public ModelAndView authorize(HttpServletRequest request, @ResponseBody
@PathVariable String provider) { public ResponseEntity<?> authorize(HttpServletRequest request,
WebContext.setAttribute(SOCIALSIGNON_TYPE_SESSION, SOCIALSIGNON_TYPE.SOCIALSIGNON_TYPE_LOGON); @PathVariable String provider
return socialSignOnAuthorize(request,provider); ) {
} _logger.trace("SocialSignOn provider : " + provider);
String instId = WebContext.getInst().getId();
@RequestMapping(value={"/bind/{provider}"}, method = RequestMethod.GET) String authorizationUrl = buildAuthRequest(instId,provider).authorize(authJwtService.genJwt());
public ModelAndView bind(HttpServletRequest request, _logger.trace("authorize SocialSignOn : " + authorizationUrl);
@PathVariable String provider) { return new Message<Object>((Object)authorizationUrl).buildResponse();
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);
} }
@RequestMapping(value={"/scanqrcode/{provider}"}, method = RequestMethod.GET) @RequestMapping(value={"/scanqrcode/{provider}"}, method = RequestMethod.GET)
@ResponseBody @ResponseBody
public SocialsProvider scanQRCode( public ResponseEntity<?> scanQRCode(
HttpServletRequest request, HttpServletRequest request,
@PathVariable("provider") String provider) { @PathVariable("provider") String provider) {
AuthRequest authRequest =buildAuthRequest(provider); String instId = WebContext.getInst().getId();
AuthRequest authRequest = buildAuthRequest(instId,provider);
if(authRequest == null ) { if(authRequest == null ) {
_logger.error("build authRequest fail ."); _logger.error("build authRequest fail .");
} }
String state = request.getSession().getId(); String state = authJwtService.genJwt();
authRequest.authorize(state); authRequest.authorize(state);
SocialsProvider socialSignOnProvider = socialSignOnProviderService.get(provider); SocialsProvider socialSignOnProvider = socialSignOnProviderService.get(instId,provider);
SocialsProvider scanQRCodeProvider = new SocialsProvider(); SocialsProvider scanQrProvider = new SocialsProvider(socialSignOnProvider);
scanQrProvider.setState(state);
scanQRCodeProvider.setId(socialSignOnProvider.getId()); scanQrProvider.setRedirectUri(
scanQRCodeProvider.setProvider(socialSignOnProvider.getProvider()); socialSignOnProviderService.getRedirectUri(WebContext.getBaseUri(), provider));
scanQRCodeProvider.setProviderName(socialSignOnProvider.getProviderName());
scanQRCodeProvider.setState(state);
scanQRCodeProvider.setClientId(socialSignOnProvider.getClientId());
scanQRCodeProvider.setRedirectUri(applicationConfig.getServerPrefix()+
"/logon/oauth20/callback/"+provider);
scanQRCodeProvider.setAgentId(socialSignOnProvider.getAgentId());
return scanQRCodeProvider; return new Message<SocialsProvider>(scanQrProvider).buildResponse();
} }
@RequestMapping(value={"/callback/{provider}"}, method = RequestMethod.GET) @RequestMapping(value={"/bind/{provider}"}, method = RequestMethod.POST)
public ModelAndView callback(@PathVariable String provider) { public ResponseEntity<?> bind(@PathVariable String provider) {
//auth call back may exception //auth call back may exception
try { try {
SocialsAssociate socialsAssociate = null; String instId = WebContext.getInst().getId();
this.provider=provider; SocialsAssociate socialsAssociate = this.authCallback(instId,provider);
this.authCallback(); UserInfo userInfo = AuthorizationUtils.getUserInfo();
_logger.debug(this.accountId); socialsAssociate.setSocialUserInfo(accountJsonString);
socialsAssociate =new SocialsAssociate(); socialsAssociate.setUserId(userInfo.getId());
socialsAssociate.setProvider(provider); socialsAssociate.setUsername(userInfo.getUsername());
socialsAssociate.setSocialUserId(this.accountId); //socialsAssociate.setAccessToken(JsonUtils.object2Json(accessToken));
//socialsAssociate.setInstId(WebContext.getInst(WebContext.getRequest())); //socialsAssociate.setExAttribute(JsonUtils.object2Json(accessToken.getResponseObject()));
_logger.debug("Social Bind : "+socialsAssociate);
//for login this.socialsAssociateService.delete(socialsAssociate);
String socialSignOnType= this.socialsAssociateService.insert(socialsAssociate);
(WebContext.getAttribute(SOCIALSIGNON_TYPE_SESSION)!=null) ? return new Message<AuthJwt>().buildResponse();
(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");
}
}catch(Exception e) { }catch(Exception e) {
_logger.error("callback Exception ",e); _logger.error("callback Exception ",e);
} }
return WebContext.redirect("/login"); return new Message<AuthJwt>(Message.ERROR).buildResponse();
}
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;
} }
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) { if(null == socialsAssociate) {
WebContext.getRequest().getSession().setAttribute( return new Message<AuthJwt>(Message.ERROR).buildResponse();
WebAttributes.AUTHENTICATION_EXCEPTION, }
new BadCredentialsException(WebContext.getI18nValue("login.error.social"))
);
return false;
}
_logger.debug("Social Sign On from {} mapping to user {}", _logger.debug("Social Sign On from {} mapping to user {}",
socialsAssociate.getProvider(),socialsAssociate.getUsername()); socialsAssociate.getProvider(),socialsAssociate.getUsername());
LoginCredential loginCredential =new LoginCredential( LoginCredential loginCredential =new LoginCredential(
socialsAssociate.getUsername(),"",ConstsLoginType.SOCIALSIGNON); socialsAssociate.getUsername(),"",ConstsLoginType.SOCIALSIGNON);
loginCredential.setProvider(this.socialSignOnProvider.getProviderName()); SocialsProvider socialSignOnProvider = socialSignOnProviderService.get(instId,provider);
Authentication authentication = authenticationProvider.authentication(loginCredential,true); loginCredential.setProvider(socialSignOnProvider.getProviderName());
if(authentication == null) {
String congress = authJwtService.createCongress(authentication); Authentication authentication = authenticationProvider.authentication(loginCredential,true);
} //socialsAssociate.setAccessToken(JsonUtils.object2Json(this.accessToken));
//socialsAssociate.setAccessToken(JsonUtils.object2Json(this.accessToken)); socialsAssociate.setSocialUserInfo(accountJsonString);
socialsAssociate.setSocialUserInfo(accountJsonString); //socialsAssociate.setExAttribute(JsonUtils.object2Json(accessToken.getResponseObject()));
//socialsAssociate.setExAttribute(JsonUtils.object2Json(accessToken.getResponseObject()));
this.socialsAssociateService.update(socialsAssociate); this.socialsAssociateService.update(socialsAssociate);
return true; return new Message<AuthJwt>(authJwtService.genAuthJwt(authentication)).buildResponse();
}catch(Exception e) {
_logger.error("callback Exception ",e);
return new Message<AuthJwt>(Message.ERROR).buildResponse();
}
} }
} }
...@@ -24,7 +24,6 @@ import java.util.HashMap; ...@@ -24,7 +24,6 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.maxkey.configuration.ApplicationConfig;
import org.maxkey.constants.ConstsTimeInterval; import org.maxkey.constants.ConstsTimeInterval;
import org.maxkey.crypto.password.PasswordReciprocal; import org.maxkey.crypto.password.PasswordReciprocal;
import org.maxkey.entity.SocialsProvider; import org.maxkey.entity.SocialsProvider;
...@@ -47,12 +46,12 @@ public class SocialSignOnProviderService{ ...@@ -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"; private static final String DEFAULT_SELECT_STATEMENT = "select * from mxk_socials_provider where instid = ? and status = 1 order by sortindex";
protected static final Cache<String, SocialsProviderLogin> socialSignOnProvidersStore = protected static final Cache<String, SocialsProviderLogin> socialsProviderLoginStore =
Caffeine.newBuilder() Caffeine.newBuilder()
.expireAfterWrite(ConstsTimeInterval.ONE_HOUR, TimeUnit.MINUTES) .expireAfterWrite(ConstsTimeInterval.ONE_HOUR, TimeUnit.MINUTES)
.build(); .build();
HashMap<String ,SocialsProvider>socialSignOnProviderMaps=new HashMap<String ,SocialsProvider>(); HashMap<String ,SocialsProvider>socialSignOnProviderMaps = new HashMap<String ,SocialsProvider>();
private final JdbcTemplate jdbcTemplate; private final JdbcTemplate jdbcTemplate;
...@@ -60,16 +59,20 @@ public class SocialSignOnProviderService{ ...@@ -60,16 +59,20 @@ public class SocialSignOnProviderService{
this.jdbcTemplate=jdbcTemplate; this.jdbcTemplate=jdbcTemplate;
} }
public SocialsProvider get(String provider){ public SocialsProvider get(String instId,String provider){
return socialSignOnProviderMaps.get(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; AuthRequest authRequest = null;
AuthConfig authConfig = AuthConfig.builder() AuthConfig authConfig = AuthConfig.builder()
.clientId(this.get(provider).getClientId()) .clientId(this.get(instId,provider).getClientId())
.clientSecret(this.get(provider).getClientSecret()) .clientSecret(this.get(instId,provider).getClientSecret())
.redirectUri(applicationConfig.getServerPrefix()+ "/logon/oauth20/callback/"+provider) .redirectUri(getRedirectUri(baseUri , provider))
.build(); .build();
if(provider.equalsIgnoreCase("WeChatOpen")) { if(provider.equalsIgnoreCase("WeChatOpen")) {
...@@ -175,42 +178,37 @@ public class SocialSignOnProviderService{ ...@@ -175,42 +178,37 @@ public class SocialSignOnProviderService{
return null; return null;
} }
public SocialsProviderLogin loadSocialsProviders(String instId) { public SocialsProviderLogin loadSocials(String instId) {
SocialsProviderLogin ssl = socialSignOnProvidersStore.getIfPresent(instId); SocialsProviderLogin socialsLogin = socialsProviderLoginStore.getIfPresent(instId);
if(ssl == null) { if(socialsLogin == null) {
List<SocialsProvider> listSocialsProvider=jdbcTemplate.query( List<SocialsProvider> listSocialsProvider = jdbcTemplate.query(
DEFAULT_SELECT_STATEMENT, DEFAULT_SELECT_STATEMENT,
new SocialsProviderRowMapper(),instId); new SocialsProviderRowMapper(),instId);
_logger.trace("query SocialsProvider " + listSocialsProvider); _logger.trace("query SocialsProvider " + listSocialsProvider);
List<SocialsProvider> socialSignOnProviders = new ArrayList<SocialsProvider>(); List<SocialsProvider> socialSignOnProviders = new ArrayList<SocialsProvider>();
ssl = new SocialsProviderLogin(socialSignOnProviders); socialsLogin = new SocialsProviderLogin(socialSignOnProviders);
for(SocialsProvider socialsProvider : listSocialsProvider){ for(SocialsProvider socialsProvider : listSocialsProvider){
socialSignOnProviderMaps.put(socialsProvider.getProvider(), socialsProvider); _logger.debug("Social Provider {} ({})" ,
_logger.debug("Social Provider " + socialsProvider.getProvider() socialsProvider.getProvider() ,socialsProvider.getProviderName());
+ "(" + socialsProvider.getProviderName()+")");
if(!socialsProvider.getHidden().equals("true")) { if(!socialsProvider.getHidden().equals("true")) {
socialSignOnProviders.add(socialsProvider); socialSignOnProviders.add(new SocialsProvider(socialsProvider));
} }
if(socialsProvider.getProvider().equalsIgnoreCase("workweixin")) { if(socialsProvider.getScanCode().equalsIgnoreCase("true")) {
ssl.setWorkWeixinLogin(socialsProvider.getScanCode()); socialsLogin.setQrScan(socialsProvider.getProvider());
}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());
} }
//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{ ...@@ -232,6 +230,7 @@ public class SocialSignOnProviderService{
socialsProvider.setSortIndex(rs.getInt("sortindex")); socialsProvider.setSortIndex(rs.getInt("sortindex"));
socialsProvider.setScanCode(rs.getString("scancode")); socialsProvider.setScanCode(rs.getString("scancode"));
socialsProvider.setStatus(rs.getInt("status")); socialsProvider.setStatus(rs.getInt("status"));
socialsProvider.setInstId(rs.getString("instid"));
return socialsProvider; return socialsProvider;
} }
} }
......
...@@ -43,7 +43,7 @@ public class SocialSignOnAutoConfiguration implements InitializingBean { ...@@ -43,7 +43,7 @@ public class SocialSignOnAutoConfiguration implements InitializingBean {
JdbcTemplate jdbcTemplate) throws IOException { JdbcTemplate jdbcTemplate) throws IOException {
SocialSignOnProviderService socialSignOnProviderService = new SocialSignOnProviderService(jdbcTemplate); SocialSignOnProviderService socialSignOnProviderService = new SocialSignOnProviderService(jdbcTemplate);
//load default Social Providers from database //load default Social Providers from database
socialSignOnProviderService.loadSocialsProviders("1"); socialSignOnProviderService.loadSocials("1");
_logger.debug("SocialSignOnProviderService inited."); _logger.debug("SocialSignOnProviderService inited.");
return socialSignOnProviderService; return socialSignOnProviderService;
} }
......
...@@ -27,8 +27,9 @@ public class HMAC512ServiceTest { ...@@ -27,8 +27,9 @@ public class HMAC512ServiceTest {
// TODO Auto-generated method stub // TODO Auto-generated method stub
String key ="7heM-14BtxjyKPuH3ITIm7q2-ps5MuBirWCsrrdbzzSAOuSPrbQYiaJ54AeA0uH2XdkYy3hHAkTFIsieGkyqxOJZ_dQzrCbaYISH9rhUZAKYx8tUY0wkE4ArOC6LqHDJarR6UIcMsARakK9U4dhoOPO1cj74XytemI-w6ACYfzRUn_Rn4e-CQMcnD1C56oNEukwalf06xVgXl41h6K8IBEzLVod58y_VfvFn-NGWpNG0fy_Qxng6dg8Dgva2DobvzMN2eejHGLGB-x809MvC4zbG7CKNVlcrzMYDt2Gt2sOVDrt2l9YqJNfgaLFjrOEVw5cuXemGkX1MvHj6TAsbLg"; String key ="7heM-14BtxjyKPuH3ITIm7q2-ps5MuBirWCsrrdbzzSAOuSPrbQYiaJ54AeA0uH2XdkYy3hHAkTFIsieGkyqxOJZ_dQzrCbaYISH9rhUZAKYx8tUY0wkE4ArOC6LqHDJarR6UIcMsARakK9U4dhoOPO1cj74XytemI-w6ACYfzRUn_Rn4e-CQMcnD1C56oNEukwalf06xVgXl41h6K8IBEzLVod58y_VfvFn-NGWpNG0fy_Qxng6dg8Dgva2DobvzMN2eejHGLGB-x809MvC4zbG7CKNVlcrzMYDt2Gt2sOVDrt2l9YqJNfgaLFjrOEVw5cuXemGkX1MvHj6TAsbLg";
HMAC512Service HMAC512Service = new HMAC512Service(key); HMAC512Service HMAC512Service = new HMAC512Service(key);
String jwt = HMAC512Service.sign("hkkkk"); String sign = HMAC512Service.sign("hkkkk");
boolean isverify = HMAC512Service.verify(jwt); System.out.println(sign);
boolean isverify = HMAC512Service.verify(sign);
System.out.println(isverify); System.out.println(isverify);
} }
......
...@@ -91,6 +91,16 @@ public class SocialsProvider extends JpaBaseEntity implements Serializable { ...@@ -91,6 +91,16 @@ public class SocialsProvider extends JpaBaseEntity implements Serializable {
public SocialsProvider() { 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() { public String getProvider() {
return provider; return provider;
......
...@@ -33,56 +33,28 @@ public class SocialsProviderLogin implements Serializable { ...@@ -33,56 +33,28 @@ public class SocialsProviderLogin implements Serializable {
*/ */
private static final long serialVersionUID = -2672107566766342357L; private static final long serialVersionUID = -2672107566766342357L;
List<SocialsProvider> socialSignOnProviders = new ArrayList<SocialsProvider>(); List<SocialsProvider> providers = new ArrayList<SocialsProvider>();
String dingTalkLogin = "none"; String qrScan = null;
String workWeixinLogin = "none";
String feiShuLogin = "none";
String weLinkLogin = "none";
public SocialsProviderLogin(List<SocialsProvider> socialSignOnProviders) { public SocialsProviderLogin(List<SocialsProvider> socialSignOnProviders) {
super(); super();
this.socialSignOnProviders = socialSignOnProviders; this.providers = socialSignOnProviders;
}
public String getDingTalkLogin() {
return dingTalkLogin;
}
public void setDingTalkLogin(String dingTalkLogin) {
this.dingTalkLogin = dingTalkLogin;
} }
public String getWorkWeixinLogin() { public String getQrScan() {
return workWeixinLogin; return qrScan;
} }
public void setWorkWeixinLogin(String workWeixinLogin) { public void setQrScan(String qrScan) {
this.workWeixinLogin = workWeixinLogin; this.qrScan = qrScan;
} }
public String getFeiShuLogin() { public List<SocialsProvider> getProviders() {
return feiShuLogin; return providers;
} }
public void setFeiShuLogin(String feiShuLogin) { public void setProviders(List<SocialsProvider> providers) {
this.feiShuLogin = feiShuLogin; this.providers = providers;
} }
public String getWeLinkLogin() {
return weLinkLogin;
}
public void setWeLinkLogin(String weLinkLogin) {
this.weLinkLogin = weLinkLogin;
}
public List<SocialsProvider> getSocialSignOnProviders() {
return socialSignOnProviders;
}
} }
...@@ -36,10 +36,7 @@ public class InstitutionsRepository { ...@@ -36,10 +36,7 @@ public class InstitutionsRepository {
private static Logger _logger = LoggerFactory.getLogger(InstitutionsRepository.class); private static Logger _logger = LoggerFactory.getLogger(InstitutionsRepository.class);
private static final String SELECT_STATEMENT = private static final String SELECT_STATEMENT =
"select * from mxk_institutions where domain = ? " ; "select * from mxk_institutions where id = ? or domain = ? " ;
private static final String SELECT_STATEMENT_BY_ID =
"select * from mxk_institutions where id = ? " ;
protected static final Cache<String, Institutions> institutionsStore = protected static final Cache<String, Institutions> institutionsStore =
Caffeine.newBuilder() Caffeine.newBuilder()
...@@ -54,33 +51,13 @@ public class InstitutionsRepository { ...@@ -54,33 +51,13 @@ public class InstitutionsRepository {
public InstitutionsRepository(JdbcTemplate jdbcTemplate) { public InstitutionsRepository(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate; this.jdbcTemplate = jdbcTemplate;
} }
public Institutions findByDomain(String domain) {
_logger.trace(" domain {}" , domain);
Institutions inst = institutionsStore.getIfPresent(domain);
if(inst == null) {
List<Institutions> 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) { public Institutions get(String instIdOrDomain) {
_logger.trace(" instId {}" , instId); _logger.trace(" instId {}" , instIdOrDomain);
Institutions inst = institutionsStore.getIfPresent(mapper.get(instId)==null ? "1" : mapper.get(instId) ); Institutions inst = institutionsStore.getIfPresent(mapper.get(instIdOrDomain)==null ? "1" : mapper.get(instIdOrDomain) );
if(inst == null) { if(inst == null) {
List<Institutions> institutions = List<Institutions> institutions =
jdbcTemplate.query(SELECT_STATEMENT_BY_ID,new InstitutionsRowMapper(),instId); jdbcTemplate.query(SELECT_STATEMENT,new InstitutionsRowMapper(),instIdOrDomain,instIdOrDomain);
if (institutions != null && institutions.size() > 0) { if (institutions != null && institutions.size() > 0) {
inst = institutions.get(0); inst = institutions.get(0);
......
...@@ -49,6 +49,8 @@ public class WebConstants { ...@@ -49,6 +49,8 @@ public class WebConstants {
public static final String CURRENT_INST = "current_inst"; public static final String CURRENT_INST = "current_inst";
public final static String INST_COOKIE_NAME = "mxk_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 // SPRING_SECURITY_SAVED_REQUEST
public static final String FIRST_SAVED_REQUEST_PARAMETER public static final String FIRST_SAVED_REQUEST_PARAMETER
......
...@@ -31,6 +31,7 @@ import javax.servlet.http.HttpSession; ...@@ -31,6 +31,7 @@ import javax.servlet.http.HttpSession;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.maxkey.configuration.ApplicationConfig; import org.maxkey.configuration.ApplicationConfig;
import org.maxkey.entity.Institutions;
import org.maxkey.util.DateUtils; import org.maxkey.util.DateUtils;
import org.maxkey.util.IdGenerator; import org.maxkey.util.IdGenerator;
import org.maxkey.web.message.Message; import org.maxkey.web.message.Message;
...@@ -309,6 +310,15 @@ public final class WebContext { ...@@ -309,6 +310,15 @@ public final class WebContext {
public static String getParameter(String name) { public static String getParameter(String name) {
return getRequest().getParameter(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. * encoding encodingString by ApplicationConfig.
......
...@@ -24,7 +24,6 @@ import javax.servlet.ServletException; ...@@ -24,7 +24,6 @@ import javax.servlet.ServletException;
import javax.servlet.ServletRequest; import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse; import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.maxkey.configuration.ApplicationConfig; import org.maxkey.configuration.ApplicationConfig;
...@@ -37,7 +36,9 @@ import org.springframework.web.filter.GenericFilterBean; ...@@ -37,7 +36,9 @@ import org.springframework.web.filter.GenericFilterBean;
public class WebInstRequestFilter extends GenericFilterBean { public class WebInstRequestFilter extends GenericFilterBean {
final static Logger _logger = LoggerFactory.getLogger(GenericFilterBean.class); 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; InstitutionsRepository institutionsRepository;
...@@ -51,17 +52,29 @@ public class WebInstRequestFilter extends GenericFilterBean { ...@@ -51,17 +52,29 @@ public class WebInstRequestFilter extends GenericFilterBean {
if(request.getSession().getAttribute(WebConstants.CURRENT_INST) == null) { if(request.getSession().getAttribute(WebConstants.CURRENT_INST) == null) {
WebContext.printRequest(request); 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)) { if(StringUtils.isEmpty(host)) {
host = applicationConfig.getDomainName(); host = applicationConfig.getDomainName();
_logger.trace("config domain {}",host);
} }
if(host.indexOf(":")> -1 ) { if(host.indexOf(":")> -1 ) {
host = host.split(":")[0]; host = host.split(":")[0];
_logger.trace("domain split {}",host);
} }
Institutions institution = institutionsRepository.findByDomain(host); Institutions institution = institutionsRepository.get(host);
_logger.trace("{}" ,institution); _logger.trace("{}" ,institution);
request.getSession().setAttribute(WebConstants.CURRENT_INST, 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); chain.doFilter(servletRequest, servletResponse);
} }
......
...@@ -17,14 +17,9 @@ ...@@ -17,14 +17,9 @@
package org.maxkey.web.endpoint; package org.maxkey.web.endpoint;
import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.regex.Pattern; 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.apache.commons.lang3.StringUtils;
import org.maxkey.authn.AbstractAuthenticationProvider; import org.maxkey.authn.AbstractAuthenticationProvider;
import org.maxkey.authn.LoginCredential; import org.maxkey.authn.LoginCredential;
...@@ -32,7 +27,6 @@ import org.maxkey.authn.jwt.AuthJwt; ...@@ -32,7 +27,6 @@ import org.maxkey.authn.jwt.AuthJwt;
import org.maxkey.authn.jwt.AuthJwtService; import org.maxkey.authn.jwt.AuthJwtService;
import org.maxkey.authn.support.kerberos.KerberosService; import org.maxkey.authn.support.kerberos.KerberosService;
import org.maxkey.authn.support.socialsignon.service.SocialSignOnProviderService; import org.maxkey.authn.support.socialsignon.service.SocialSignOnProviderService;
import org.maxkey.authn.web.AuthorizationUtils;
import org.maxkey.configuration.ApplicationConfig; import org.maxkey.configuration.ApplicationConfig;
import org.maxkey.entity.Institutions; import org.maxkey.entity.Institutions;
import org.maxkey.entity.Message; import org.maxkey.entity.Message;
...@@ -50,13 +44,9 @@ import org.springframework.http.MediaType; ...@@ -50,13 +44,9 @@ import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller; 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.PathVariable;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; 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.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
...@@ -66,6 +56,7 @@ import io.swagger.v3.oas.annotations.tags.Tag; ...@@ -66,6 +56,7 @@ import io.swagger.v3.oas.annotations.tags.Tag;
*/ */
@Tag(name = "1-1-登录接口文档模块") @Tag(name = "1-1-登录接口文档模块")
@Controller @Controller
@RequestMapping(value = "/login")
public class LoginEntryPoint { public class LoginEntryPoint {
private static Logger _logger = LoggerFactory.getLogger(LoginEntryPoint.class); private static Logger _logger = LoggerFactory.getLogger(LoginEntryPoint.class);
...@@ -109,106 +100,74 @@ public class LoginEntryPoint { ...@@ -109,106 +100,74 @@ public class LoginEntryPoint {
* @return * @return
*/ */
@Operation(summary = "登录接口", description = "用户登录地址",method="GET") @Operation(summary = "登录接口", description = "用户登录地址",method="GET")
@RequestMapping(value={"/login"}) @RequestMapping(value={"/get"}, produces = {MediaType.APPLICATION_JSON_VALUE})
public ModelAndView login(HttpServletRequest request) { public ResponseEntity<?> get() {
_logger.debug("LoginController /login."); _logger.debug("LoginController /get.");
boolean isAuthenticated= AuthorizationUtils.isAuthenticated();
if(isAuthenticated){
return WebContext.redirect("/forwardindex");
}
_logger.trace("Session Timeout MaxInactiveInterval " + WebContext.getRequest().getSession().getMaxInactiveInterval());
//for normal login //for normal login
ModelAndView modelAndView = new ModelAndView("login"); HashMap<String , Object> model = new HashMap<String , Object>();
modelAndView.addObject("isRemeberMe", applicationConfig.getLoginConfig().isRemeberMe()); model.put("isRemeberMe", applicationConfig.getLoginConfig().isRemeberMe());
modelAndView.addObject("isKerberos", applicationConfig.getLoginConfig().isKerberos()); model.put("isKerberos", applicationConfig.getLoginConfig().isKerberos());
modelAndView.addObject("isMfa", applicationConfig.getLoginConfig().isMfa());
if(applicationConfig.getLoginConfig().isMfa()) { if(applicationConfig.getLoginConfig().isMfa()) {
modelAndView.addObject("otpType", tfaOtpAuthn.getOtpType()); model.put("otpType", tfaOtpAuthn.getOtpType());
modelAndView.addObject("otpInterval", tfaOtpAuthn.getInterval()); model.put("otpInterval", tfaOtpAuthn.getInterval());
} }
if( applicationConfig.getLoginConfig().isKerberos()){ if( applicationConfig.getLoginConfig().isKerberos()){
modelAndView.addObject("userDomainUrlJson", kerberosService.buildKerberosProxys()); model.put("userDomainUrlJson", kerberosService.buildKerberosProxys());
} }
Institutions inst = (Institutions)WebContext.getAttribute(WebConstants.CURRENT_INST); Institutions inst = (Institutions)WebContext.getAttribute(WebConstants.CURRENT_INST);
modelAndView.addObject("captchaSupport", inst.getCaptchaSupport()); model.put("inst", inst);
modelAndView.addObject("captchaType", inst.getCaptchaType()); model.put("captcha", inst.getCaptchaSupport());
modelAndView.addObject("sessionid", WebContext.getSession().getId()); model.put("captchaType", inst.getCaptchaType());
//modelAndView.addObject("jwtToken",jwtLoginService.buildLoginJwt()); model.put("state", authJwtService.genJwt());
//load Social Sign On Providers //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); return new Message<HashMap<String , Object>>(model).buildResponse();
modelAndView.addObject("loginErrorMessage", loginErrorMessage==null?"":loginErrorMessage);
WebContext.removeAttribute(WebConstants.LOGIN_ERROR_SESSION_MESSAGE);
return modelAndView;
} }
@RequestMapping(value={"/logon.do"})
public ModelAndView logon(
HttpServletRequest request,
HttpServletResponse response,
@ModelAttribute("loginCredential") LoginCredential loginCredential) throws ServletException, IOException {
authenticationProvider.authenticate(loginCredential);
if (AuthorizationUtils.isAuthenticated()) { @RequestMapping(value={"/sendotp/{mobile}"}, produces = {MediaType.APPLICATION_JSON_VALUE})
return WebContext.redirect("/forwardindex"); public ResponseEntity<?> produceOtp(@PathVariable("mobile") String mobile) {
} else { UserInfo userInfo=userInfoService.findByEmailMobile(mobile);
return WebContext.redirect("/login"); if(userInfo != null) {
} otpAuthnService.getByInstId(WebContext.getInst().getId()).produce(userInfo);
return new Message<AuthJwt>(Message.SUCCESS).buildResponse();
}
@RequestMapping("/login/{username}")
@ResponseBody
public HashMap <String,Object> queryLoginUserAuth(@PathVariable("username") String username) {
UserInfo userInfo=userInfoService.findByUsername(username);
HashMap <String,Object> authnType=new HashMap <String,Object>();
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";
} }
return "fail"; return new Message<AuthJwt>(Message.FAIL).buildResponse();
} }
/**
* normal
//////////////////// * @param loginCredential
* @return
*/
@RequestMapping(value={"/signin"}, produces = {MediaType.APPLICATION_JSON_VALUE}) @RequestMapping(value={"/signin"}, produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<?> signin( @RequestBody LoginCredential loginCredential) { public ResponseEntity<?> signin( @RequestBody LoginCredential loginCredential) {
//for congress
Authentication authentication = authenticationProvider.authenticate(loginCredential);
if(authentication == null) {
return new Message<AuthJwt>(Message.FAIL).buildResponse();
}
return new Message<AuthJwt>(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())){ if(StringUtils.isNotBlank(loginCredential.getCongress())){
AuthJwt authJwt = authJwtService.consumeCongress(loginCredential.getCongress()); AuthJwt authJwt = authJwtService.consumeCongress(loginCredential.getCongress());
if(authJwt != null) { if(authJwt != null) {
return new Message<AuthJwt>(authJwt).buildResponse(); return new Message<AuthJwt>(authJwt).buildResponse();
} }
} }
return new Message<AuthJwt>(Message.FAIL).buildResponse();
//normal
Authentication authentication = authenticationProvider.authenticate(loginCredential);
if(authentication == null) {
return new Message<AuthJwt>(Message.FAIL).buildResponse();
}
return new Message<AuthJwt>(authJwtService.generateAuthJwt(authentication)).buildResponse();
} }
} }
...@@ -90,8 +90,8 @@ public class LoginEntryPoint { ...@@ -90,8 +90,8 @@ public class LoginEntryPoint {
@RequestMapping(value={"/signin"}, produces = {MediaType.APPLICATION_JSON_VALUE}) @RequestMapping(value={"/signin"}, produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<?> signin( @RequestBody LoginCredential loginCredential) { public ResponseEntity<?> signin( @RequestBody LoginCredential loginCredential) {
Authentication authentication = authenticationProvider.authenticate(loginCredential); Authentication authentication = authenticationProvider.authenticate(loginCredential);
String jwt = authJwtService.generateToken(authentication); AuthJwt authJwt = authJwtService.genAuthJwt(authentication);
return new Message<AuthJwt>(new AuthJwt(jwt, authentication)).buildResponse(); return new Message<AuthJwt>(authJwt).buildResponse();
} }
} }
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册