This commit is contained in:
MaxKey
2022-04-20 17:06:18 +08:00
parent d9af91de4a
commit 586e473e48
16 changed files with 356 additions and 464 deletions

View File

@@ -25,6 +25,7 @@ import org.maxkey.authn.jwt.AuthJwtService;
import org.maxkey.authn.support.socialsignon.service.SocialSignOnProviderService;
import org.maxkey.authn.support.socialsignon.service.SocialsAssociateService;
import org.maxkey.configuration.ApplicationConfig;
import org.maxkey.entity.SocialsAssociate;
import org.maxkey.entity.SocialsProvider;
import org.maxkey.web.WebContext;
import org.slf4j.Logger;
@@ -42,34 +43,11 @@ import me.zhyd.oauth.request.AuthRequest;
*/
public class AbstractSocialSignOnEndpoint {
final static Logger _logger = LoggerFactory.getLogger(AbstractSocialSignOnEndpoint.class);
protected final static String SOCIALSIGNON_SESSION_REDIRECT_URI="socialsignon_session_redirect_uri";
protected final static String SOCIALSIGNON_REDIRECT_URI="redirect_uri";
public final static String SOCIALSIGNON_TYPE_SESSION="socialsignon_type_session";
public final static String SOCIALSIGNON_OAUTH_SERVICE_SESSION="socialsignon_oauth_service_session";
public final static String SOCIALSIGNON_PROVIDER_SESSION="socialsignon_provider_session";
public final static class SOCIALSIGNON_TYPE{
public final static String SOCIALSIGNON_TYPE_LOGON="socialsignon_type_logon";
public final static String SOCIALSIGNON_TYPE_BIND="socialsignon_type_bind";
}
protected SocialsProvider socialSignOnProvider;
protected AuthRequest authRequest;
protected String accountJsonString;
protected String accountId;
protected String provider;
@Autowired
protected SocialSignOnProviderService socialSignOnProviderService;
@@ -86,15 +64,13 @@ public class AbstractSocialSignOnEndpoint {
@Autowired
ApplicationConfig applicationConfig;
protected AuthRequest buildAuthRequest(String provider){
protected AuthRequest buildAuthRequest(String instId,String provider){
try {
SocialsProvider socialSignOnProvider = socialSignOnProviderService.get(provider);
SocialsProvider socialSignOnProvider = socialSignOnProviderService.get(instId,provider);
_logger.debug("socialSignOn Provider : "+socialSignOnProvider);
if(socialSignOnProvider!=null){
authRequest=socialSignOnProviderService.getAuthRequest(provider,applicationConfig);
WebContext.setAttribute(SOCIALSIGNON_OAUTH_SERVICE_SESSION, authRequest);
WebContext.setAttribute(SOCIALSIGNON_PROVIDER_SESSION, socialSignOnProvider);
if(socialSignOnProvider != null){
authRequest = socialSignOnProviderService.getAuthRequest(instId,provider,WebContext.getBaseUri());
return authRequest;
}
}catch(Exception e) {
@@ -103,7 +79,8 @@ public class AbstractSocialSignOnEndpoint {
return null;
}
protected String authCallback() throws Exception {
protected SocialsAssociate authCallback(String instId,String provider) throws Exception {
SocialsAssociate socialsAssociate = null;
AuthCallback authCallback=new AuthCallback();
authCallback.setCode(WebContext.getRequest().getParameter("code"));
authCallback.setAuth_code(WebContext.getRequest().getParameter("auth_code"));
@@ -111,24 +88,16 @@ public class AbstractSocialSignOnEndpoint {
authCallback.setAuthorization_code(WebContext.getRequest().getParameter("authorization_code"));
authCallback.setOauth_verifier(WebContext.getRequest().getParameter("oauthVerifier"));
authCallback.setState(WebContext.getRequest().getParameter("state"));
_logger.debug("Callback OAuth code {}, auth_code {}, oauthToken {}, authorization_code {}, oauthVerifier {}",
_logger.debug("Callback OAuth code {}, auth_code {}, oauthToken {}, authorization_code {}, oauthVerifier {} , state {}",
authCallback.getCode(),
authCallback.getAuth_code(),
authCallback.getOauth_token(),
authCallback.getAuthorization_code(),
authCallback.getOauth_verifier());
_logger.debug("Callback state {} , sessionId {}",
authCallback.getState(),WebContext.getRequest().getSession().getId()
);
authCallback.getOauth_verifier(),
authCallback.getState());
authRequest=(AuthRequest)WebContext.getAttribute(SOCIALSIGNON_OAUTH_SERVICE_SESSION);
socialSignOnProvider=(SocialsProvider)WebContext.getAttribute(SOCIALSIGNON_PROVIDER_SESSION);
//clear session
WebContext.removeAttribute(SOCIALSIGNON_OAUTH_SERVICE_SESSION);
WebContext.removeAttribute(SOCIALSIGNON_PROVIDER_SESSION);
if(authRequest == null) {//if authRequest is null renew one
authRequest=socialSignOnProviderService.getAuthRequest(provider,applicationConfig);
authRequest=socialSignOnProviderService.getAuthRequest(instId,provider,WebContext.getBaseUri());
_logger.debug("session authRequest is null , renew one");
}
@@ -139,10 +108,13 @@ public class AbstractSocialSignOnEndpoint {
AuthResponse<?> authResponse=authRequest.login(authCallback);
_logger.debug("Response : " + authResponse.getData());
accountId=socialSignOnProviderService.getAccountId(provider, authResponse);
_logger.debug("getAccountId : " + accountId);
return accountId;
socialsAssociate =new SocialsAssociate();
socialsAssociate.setProvider(provider);
socialsAssociate.setSocialUserId(
socialSignOnProviderService.getAccountId(provider, authResponse));
socialsAssociate.setInstId(instId);
return socialsAssociate;
}
}

View File

@@ -23,24 +23,23 @@ package org.maxkey.authn.support.socialsignon;
import javax.servlet.http.HttpServletRequest;
import org.maxkey.authn.LoginCredential;
import org.maxkey.authn.jwt.AuthJwt;
import org.maxkey.authn.web.AuthorizationUtils;
import org.maxkey.constants.ConstsLoginType;
import org.maxkey.entity.Message;
import org.maxkey.entity.SocialsAssociate;
import org.maxkey.entity.SocialsProvider;
import org.maxkey.entity.UserInfo;
import org.maxkey.web.WebContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import me.zhyd.oauth.request.AuthRequest;
/**
@@ -51,153 +50,99 @@ import me.zhyd.oauth.request.AuthRequest;
@RequestMapping(value = "/logon/oauth20")
public class SocialSignOnEndpoint extends AbstractSocialSignOnEndpoint{
final static Logger _logger = LoggerFactory.getLogger(SocialSignOnEndpoint.class);
public ModelAndView socialSignOnAuthorize(HttpServletRequest request,String provider){
_logger.trace("SocialSignOn provider : " + provider);
String authorizationUrl=buildAuthRequest(provider).authorize(request.getSession().getId());
_logger.trace("authorize SocialSignOn : " + authorizationUrl);
return WebContext.redirect(authorizationUrl);
}
@RequestMapping(value={"/authorize/{provider}"}, method = RequestMethod.GET)
public ModelAndView authorize(HttpServletRequest request,
@PathVariable String provider) {
WebContext.setAttribute(SOCIALSIGNON_TYPE_SESSION, SOCIALSIGNON_TYPE.SOCIALSIGNON_TYPE_LOGON);
return socialSignOnAuthorize(request,provider);
@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={"/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);
}
@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");
}
String instId = WebContext.getInst().getId();
SocialsAssociate socialsAssociate = this.authCallback(instId,provider);
UserInfo userInfo = AuthorizationUtils.getUserInfo();
socialsAssociate.setSocialUserInfo(accountJsonString);
socialsAssociate.setUserId(userInfo.getId());
socialsAssociate.setUsername(userInfo.getUsername());
//socialsAssociate.setAccessToken(JsonUtils.object2Json(accessToken));
//socialsAssociate.setExAttribute(JsonUtils.object2Json(accessToken.getResponseObject()));
_logger.debug("Social Bind : "+socialsAssociate);
this.socialsAssociateService.delete(socialsAssociate);
this.socialsAssociateService.insert(socialsAssociate);
return new Message<AuthJwt>().buildResponse();
}catch(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) {
WebContext.getRequest().getSession().setAttribute(
WebAttributes.AUTHENTICATION_EXCEPTION,
new BadCredentialsException(WebContext.getI18nValue("login.error.social"))
);
return false;
}
if(null == socialsAssociate) {
return new Message<AuthJwt>(Message.ERROR).buildResponse();
}
_logger.debug("Social Sign On from {} mapping to user {}",
_logger.debug("Social Sign On from {} mapping to user {}",
socialsAssociate.getProvider(),socialsAssociate.getUsername());
LoginCredential loginCredential =new LoginCredential(
socialsAssociate.getUsername(),"",ConstsLoginType.SOCIALSIGNON);
loginCredential.setProvider(this.socialSignOnProvider.getProviderName());
Authentication authentication = authenticationProvider.authentication(loginCredential,true);
if(authentication == null) {
String congress = authJwtService.createCongress(authentication);
}
//socialsAssociate.setAccessToken(JsonUtils.object2Json(this.accessToken));
socialsAssociate.setSocialUserInfo(accountJsonString);
//socialsAssociate.setExAttribute(JsonUtils.object2Json(accessToken.getResponseObject()));
LoginCredential loginCredential =new LoginCredential(
socialsAssociate.getUsername(),"",ConstsLoginType.SOCIALSIGNON);
SocialsProvider socialSignOnProvider = socialSignOnProviderService.get(instId,provider);
loginCredential.setProvider(socialSignOnProvider.getProviderName());
Authentication authentication = authenticationProvider.authentication(loginCredential,true);
//socialsAssociate.setAccessToken(JsonUtils.object2Json(this.accessToken));
socialsAssociate.setSocialUserInfo(accountJsonString);
//socialsAssociate.setExAttribute(JsonUtils.object2Json(accessToken.getResponseObject()));
this.socialsAssociateService.update(socialsAssociate);
return true;
this.socialsAssociateService.update(socialsAssociate);
return new Message<AuthJwt>(authJwtService.genAuthJwt(authentication)).buildResponse();
}catch(Exception e) {
_logger.error("callback Exception ",e);
return new Message<AuthJwt>(Message.ERROR).buildResponse();
}
}
}

View File

@@ -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());
}
//add to socialSignOnProviderMaps
socialSignOnProviderMaps.put(instId + "_" + socialsProvider.getProvider() , socialsProvider);
}
_logger.debug("social SignOn Providers Login {}" , ssl);
_logger.debug("social SignOn Providers Login {}" , socialsLogin);
socialSignOnProvidersStore.put(instId, ssl);
socialsProviderLoginStore.put(instId, socialsLogin);
}
return ssl;
return socialsLogin;
}
@@ -232,6 +230,7 @@ public class SocialSignOnProviderService{
socialsProvider.setSortIndex(rs.getInt("sortindex"));
socialsProvider.setScanCode(rs.getString("scancode"));
socialsProvider.setStatus(rs.getInt("status"));
socialsProvider.setInstId(rs.getString("instid"));
return socialsProvider;
}
}

View File

@@ -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;
}