mirror of
https://gitee.com/dromara/MaxKey.git
synced 2025-12-06 17:08:29 +08:00
sso
This commit is contained in:
parent
d9af91de4a
commit
586e473e48
@ -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,7 +70,7 @@ 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);
|
||||
|
||||
@ -80,50 +79,6 @@ public abstract class AbstractAuthenticationProvider {
|
||||
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<String,Object> sessionAttributeMap = new HashMap<String,Object>();
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -72,7 +74,11 @@ public class RealmAuthenticationProvider extends AbstractAuthenticationProvider
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Authentication doInternalAuthenticate(LoginCredential loginCredential) {
|
||||
public Authentication authenticate(LoginCredential loginCredential) {
|
||||
UsernamePasswordAuthenticationToken authenticationToken = null;
|
||||
_logger.debug("Trying to authenticate user '{}' via {}",
|
||||
loginCredential.getPrincipal(), getProviderName());
|
||||
try {
|
||||
|
||||
_logger.debug("authentication " + loginCredential);
|
||||
|
||||
@ -110,7 +116,29 @@ public class RealmAuthenticationProvider extends AbstractAuthenticationProvider
|
||||
//apply PasswordSetType and resetBadPasswordCount
|
||||
authenticationRealm.getPasswordPolicyValidator().applyPasswordPolicy(userInfo);
|
||||
|
||||
UsernamePasswordAuthenticationToken authenticationToken = createOnlineSession(loginCredential,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());
|
||||
}
|
||||
|
||||
return authenticationToken;
|
||||
}
|
||||
|
||||
@ -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);
|
||||
|
||||
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);
|
||||
|
||||
JWTClaimsSet jwtClaims =new JWTClaimsSet.Builder()
|
||||
.jwtID(WebContext.genId())
|
||||
.expirationTime(expirationTime)
|
||||
.build();
|
||||
|
||||
return signedJWT(jwtClaims);
|
||||
}
|
||||
|
||||
public String signedJWT(JWTClaimsSet jwtClaims) {
|
||||
_logger.trace("jwt Claims : {}" , jwtClaims);
|
||||
SignedJWT jwtToken = new SignedJWT(
|
||||
new JWSHeader(JWSAlgorithm.HS512),
|
||||
jwtClaims);
|
||||
|
||||
token = hmac512Service.sign(jwtToken.getPayload());
|
||||
|
||||
return token ;
|
||||
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;
|
||||
|
||||
@ -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;
|
||||
@ -43,33 +44,10 @@ 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()
|
||||
);
|
||||
|
||||
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);
|
||||
authCallback.getOauth_verifier(),
|
||||
authCallback.getState());
|
||||
|
||||
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);
|
||||
socialsAssociate =new SocialsAssociate();
|
||||
socialsAssociate.setProvider(provider);
|
||||
socialsAssociate.setSocialUserId(
|
||||
socialSignOnProviderService.getAccountId(provider, authResponse));
|
||||
socialsAssociate.setInstId(instId);
|
||||
|
||||
_logger.debug("getAccountId : " + accountId);
|
||||
return accountId;
|
||||
return socialsAssociate;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -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;
|
||||
|
||||
/**
|
||||
@ -52,111 +51,48 @@ import me.zhyd.oauth.request.AuthRequest;
|
||||
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>((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();
|
||||
SocialsProvider socialSignOnProvider = socialSignOnProviderService.get(instId,provider);
|
||||
SocialsProvider scanQrProvider = new SocialsProvider(socialSignOnProvider);
|
||||
scanQrProvider.setState(state);
|
||||
scanQrProvider.setRedirectUri(
|
||||
socialSignOnProviderService.getRedirectUri(WebContext.getBaseUri(), provider));
|
||||
|
||||
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());
|
||||
|
||||
return scanQRCodeProvider;
|
||||
return new Message<SocialsProvider>(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");
|
||||
}
|
||||
|
||||
}catch(Exception e) {
|
||||
_logger.error("callback Exception ",e);
|
||||
}
|
||||
|
||||
return WebContext.redirect("/login");
|
||||
}
|
||||
|
||||
public boolean socialBind(SocialsAssociate socialsAssociate){
|
||||
if(null == socialsAssociate) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String instId = WebContext.getInst().getId();
|
||||
SocialsAssociate socialsAssociate = this.authCallback(instId,provider);
|
||||
UserInfo userInfo = AuthorizationUtils.getUserInfo();
|
||||
socialsAssociate.setSocialUserInfo(accountJsonString);
|
||||
socialsAssociate.setUserId(userInfo.getId());
|
||||
@ -166,21 +102,27 @@ public class SocialSignOnEndpoint extends AbstractSocialSignOnEndpoint{
|
||||
_logger.debug("Social Bind : "+socialsAssociate);
|
||||
this.socialsAssociateService.delete(socialsAssociate);
|
||||
this.socialsAssociateService.insert(socialsAssociate);
|
||||
return true;
|
||||
return new Message<AuthJwt>().buildResponse();
|
||||
}catch(Exception e) {
|
||||
_logger.error("callback Exception ",e);
|
||||
}
|
||||
|
||||
public boolean socialSignOn(SocialsAssociate socialsAssociate){
|
||||
return new Message<AuthJwt>(Message.ERROR).buildResponse();
|
||||
}
|
||||
|
||||
@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);
|
||||
|
||||
_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;
|
||||
return new Message<AuthJwt>(Message.ERROR).buildResponse();
|
||||
}
|
||||
|
||||
_logger.debug("Social Sign On from {} mapping to user {}",
|
||||
@ -188,16 +130,19 @@ public class SocialSignOnEndpoint extends AbstractSocialSignOnEndpoint{
|
||||
|
||||
LoginCredential loginCredential =new LoginCredential(
|
||||
socialsAssociate.getUsername(),"",ConstsLoginType.SOCIALSIGNON);
|
||||
loginCredential.setProvider(this.socialSignOnProvider.getProviderName());
|
||||
SocialsProvider socialSignOnProvider = socialSignOnProviderService.get(instId,provider);
|
||||
loginCredential.setProvider(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()));
|
||||
|
||||
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;
|
||||
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<String, SocialsProviderLogin> socialSignOnProvidersStore =
|
||||
protected static final Cache<String, SocialsProviderLogin> socialsProviderLoginStore =
|
||||
Caffeine.newBuilder()
|
||||
.expireAfterWrite(ConstsTimeInterval.ONE_HOUR, TimeUnit.MINUTES)
|
||||
.build();
|
||||
|
||||
HashMap<String ,SocialsProvider>socialSignOnProviderMaps=new HashMap<String ,SocialsProvider>();
|
||||
HashMap<String ,SocialsProvider>socialSignOnProviderMaps = new HashMap<String ,SocialsProvider>();
|
||||
|
||||
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<SocialsProvider> listSocialsProvider=jdbcTemplate.query(
|
||||
public SocialsProviderLogin loadSocials(String instId) {
|
||||
SocialsProviderLogin socialsLogin = socialsProviderLoginStore.getIfPresent(instId);
|
||||
if(socialsLogin == null) {
|
||||
List<SocialsProvider> listSocialsProvider = jdbcTemplate.query(
|
||||
DEFAULT_SELECT_STATEMENT,
|
||||
new SocialsProviderRowMapper(),instId);
|
||||
_logger.trace("query SocialsProvider " + listSocialsProvider);
|
||||
|
||||
|
||||
List<SocialsProvider> socialSignOnProviders = new ArrayList<SocialsProvider>();
|
||||
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());
|
||||
}
|
||||
|
||||
_logger.debug("social SignOn Providers Login {}" , ssl);
|
||||
|
||||
socialSignOnProvidersStore.put(instId, ssl);
|
||||
//add to socialSignOnProviderMaps
|
||||
socialSignOnProviderMaps.put(instId + "_" + socialsProvider.getProvider() , socialsProvider);
|
||||
}
|
||||
return ssl;
|
||||
|
||||
_logger.debug("social SignOn Providers Login {}" , socialsLogin);
|
||||
|
||||
socialsProviderLoginStore.put(instId, socialsLogin);
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@ -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;
|
||||
}
|
||||
|
||||
@ -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);
|
||||
}
|
||||
|
||||
|
||||
@ -92,6 +92,16 @@ public class SocialsProvider extends JpaBaseEntity implements Serializable {
|
||||
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@ -33,56 +33,28 @@ public class SocialsProviderLogin implements Serializable {
|
||||
*/
|
||||
private static final long serialVersionUID = -2672107566766342357L;
|
||||
|
||||
List<SocialsProvider> socialSignOnProviders = new ArrayList<SocialsProvider>();
|
||||
List<SocialsProvider> providers = new ArrayList<SocialsProvider>();
|
||||
|
||||
String dingTalkLogin = "none";
|
||||
|
||||
String workWeixinLogin = "none";
|
||||
|
||||
String feiShuLogin = "none";
|
||||
|
||||
String weLinkLogin = "none";
|
||||
String qrScan = null;
|
||||
|
||||
public SocialsProviderLogin(List<SocialsProvider> socialSignOnProviders) {
|
||||
super();
|
||||
this.socialSignOnProviders = socialSignOnProviders;
|
||||
this.providers = socialSignOnProviders;
|
||||
}
|
||||
|
||||
public String getDingTalkLogin() {
|
||||
return dingTalkLogin;
|
||||
public String getQrScan() {
|
||||
return qrScan;
|
||||
}
|
||||
|
||||
public void setDingTalkLogin(String dingTalkLogin) {
|
||||
this.dingTalkLogin = dingTalkLogin;
|
||||
public void setQrScan(String qrScan) {
|
||||
this.qrScan = qrScan;
|
||||
}
|
||||
|
||||
public String getWorkWeixinLogin() {
|
||||
return workWeixinLogin;
|
||||
public List<SocialsProvider> getProviders() {
|
||||
return providers;
|
||||
}
|
||||
|
||||
public void setWorkWeixinLogin(String workWeixinLogin) {
|
||||
this.workWeixinLogin = workWeixinLogin;
|
||||
public void setProviders(List<SocialsProvider> providers) {
|
||||
this.providers = providers;
|
||||
}
|
||||
|
||||
public String getFeiShuLogin() {
|
||||
return feiShuLogin;
|
||||
}
|
||||
|
||||
public void setFeiShuLogin(String feiShuLogin) {
|
||||
this.feiShuLogin = feiShuLogin;
|
||||
}
|
||||
|
||||
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 {
|
||||
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<String, Institutions> institutionsStore =
|
||||
Caffeine.newBuilder()
|
||||
@ -55,32 +52,12 @@ public class InstitutionsRepository {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
}
|
||||
|
||||
public Institutions findByDomain(String domain) {
|
||||
_logger.trace(" domain {}" , domain);
|
||||
Institutions inst = institutionsStore.getIfPresent(domain);
|
||||
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> 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) );
|
||||
if(inst == null) {
|
||||
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) {
|
||||
inst = institutions.get(0);
|
||||
|
||||
@ -50,6 +50,8 @@ public class WebConstants {
|
||||
|
||||
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
|
||||
= "SPRING_SECURITY_SAVED_REQUEST";
|
||||
|
||||
@ -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;
|
||||
@ -310,6 +311,15 @@ public final class WebContext {
|
||||
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.
|
||||
*
|
||||
|
||||
@ -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;
|
||||
@ -38,6 +37,8 @@ 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_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);
|
||||
}
|
||||
|
||||
@ -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<String , Object> model = new HashMap<String , Object>();
|
||||
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()));
|
||||
|
||||
Object loginErrorMessage=WebContext.getAttribute(WebConstants.LOGIN_ERROR_SESSION_MESSAGE);
|
||||
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()) {
|
||||
return WebContext.redirect("/forwardindex");
|
||||
} else {
|
||||
return WebContext.redirect("/login");
|
||||
}
|
||||
model.put("socials", socialSignOnProviderService.loadSocials(inst.getId()));
|
||||
|
||||
return new Message<HashMap<String , Object>>(model).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(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<AuthJwt>(Message.SUCCESS).buildResponse();
|
||||
}
|
||||
|
||||
@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 new Message<AuthJwt>(Message.FAIL).buildResponse();
|
||||
}
|
||||
|
||||
return "fail";
|
||||
}
|
||||
|
||||
|
||||
|
||||
////////////////////
|
||||
|
||||
/**
|
||||
* 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<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())){
|
||||
AuthJwt authJwt = authJwtService.consumeCongress(loginCredential.getCongress());
|
||||
if(authJwt != null) {
|
||||
return new Message<AuthJwt>(authJwt).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 {
|
||||
@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<AuthJwt>(new AuthJwt(jwt, authentication)).buildResponse();
|
||||
AuthJwt authJwt = authJwtService.genAuthJwt(authentication);
|
||||
return new Message<AuthJwt>(authJwt).buildResponse();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user