tab to 4 space

This commit is contained in:
MaxKey 2025-11-01 11:17:01 +08:00
parent e823cb1fec
commit dc5e773726
834 changed files with 43445 additions and 43445 deletions

View File

@ -17,44 +17,44 @@ public enum AuthCustomSource implements AuthSource {
* 自己搭建的gitlab私服
*/
MAXKEY {
/**
* 授权的api
*
* @return url
*/
@Override
public String authorize() {
return AuthMaxKeyJeeGitRequest.BASE_HOST + "/sign/authz/oauth/v20/authorize";
}
/**
* 授权的api
*
* @return url
*/
@Override
public String authorize() {
return AuthMaxKeyJeeGitRequest.BASE_HOST + "/sign/authz/oauth/v20/authorize";
}
/**
* 获取accessToken的api
*
* @return url
*/
@Override
public String accessToken() {
return AuthMaxKeyJeeGitRequest.BASE_HOST + "/sign/authz/oauth/v20/token";
}
/**
* 获取accessToken的api
*
* @return url
*/
@Override
public String accessToken() {
return AuthMaxKeyJeeGitRequest.BASE_HOST + "/sign/authz/oauth/v20/token";
}
/**
* 获取用户信息的api
*
* @return url
*/
@Override
public String userInfo() {
return AuthMaxKeyJeeGitRequest.BASE_HOST + "/sign/api/oauth/v20/me";
}
/**
* 获取用户信息的api
*
* @return url
*/
@Override
public String userInfo() {
return AuthMaxKeyJeeGitRequest.BASE_HOST + "/sign/api/oauth/v20/me";
}
/**
* 平台对应的 AuthRequest 实现类必须继承自 {@link AuthDefaultRequest}
*
* @return class
*/
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthMaxKeyJeeGitRequest.class;
}
/**
* 平台对应的 AuthRequest 实现类必须继承自 {@link AuthDefaultRequest}
*
* @return class
*/
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthMaxKeyJeeGitRequest.class;
}
}
}

View File

@ -24,32 +24,32 @@ public class AuthMaxKeyJeeGitRequest extends AuthDefaultRequest {
* @param config
*/
public AuthMaxKeyJeeGitRequest(AuthConfig config) {
super(config, AuthCustomSource.MAXKEY);
super(config, AuthCustomSource.MAXKEY);
}
public AuthMaxKeyJeeGitRequest(AuthConfig config, AuthSource source) {
super(config, source);
super(config, source);
}
public AuthMaxKeyJeeGitRequest(AuthConfig config, AuthStateCache authStateCache) {
super(config, AuthCustomSource.MAXKEY, authStateCache);
super(config, AuthCustomSource.MAXKEY, authStateCache);
}
@Override
protected AuthToken getAccessToken(AuthCallback authCallback) {
String body = doPostAuthorizationCode(authCallback.getCode());
JSONObject object = JSONObject.parseObject(body);
System.out.println("getAccessToken:"+JsonMapper.toJson(object));
AuthCustomExceptionUtils.checkResponse(object);
return AuthToken.builder().accessToken(object.getString("access_token")).refreshToken(object.getString("refresh_token")).idToken(object.getString("id_token")).tokenType(object.getString("token_type")).scope(object.getString("scope")).build();
String body = doPostAuthorizationCode(authCallback.getCode());
JSONObject object = JSONObject.parseObject(body);
System.out.println("getAccessToken:"+JsonMapper.toJson(object));
AuthCustomExceptionUtils.checkResponse(object);
return AuthToken.builder().accessToken(object.getString("access_token")).refreshToken(object.getString("refresh_token")).idToken(object.getString("id_token")).tokenType(object.getString("token_type")).scope(object.getString("scope")).build();
}
@Override
protected AuthUser getUserInfo(AuthToken authToken) {
String body = doGetUserInfo(authToken);
JSONObject object = JSONObject.parseObject(body);
AuthCustomExceptionUtils.checkResponse(object);
return AuthUser.builder().uuid(object.getString("id")).username(object.getString("username")).nickname(object.getString("name")).avatar(object.getString("avatar_url")).blog(object.getString("web_url")).company(object.getString("organization")).location(object.getString("location")).email(object.getString("email")).remark(object.getString("bio")).token(authToken).source(source.toString()).build();
String body = doGetUserInfo(authToken);
JSONObject object = JSONObject.parseObject(body);
AuthCustomExceptionUtils.checkResponse(object);
return AuthUser.builder().uuid(object.getString("id")).username(object.getString("username")).nickname(object.getString("name")).avatar(object.getString("avatar_url")).blog(object.getString("web_url")).company(object.getString("organization")).location(object.getString("location")).email(object.getString("email")).remark(object.getString("bio")).token(authToken).source(source.toString()).build();
}
}

View File

@ -34,25 +34,25 @@ public class Oauth2UserLoginUtils{
private static final String DEFAULT_USER_CODE="system";
public static String getAuthUserToSysUserCode(String oauthUserId) {
//自行实现第三方用户到jeesite用户之间逻辑转换关系
if(DEMO_MODE) {
return DEFAULT_USER_CODE;
}
return oauthUserId;
//自行实现第三方用户到jeesite用户之间逻辑转换关系
if(DEMO_MODE) {
return DEFAULT_USER_CODE;
}
return oauthUserId;
}
public static void loginByOauthUserId(String oauthUserId) {
HttpServletRequest request = ServletUtils.getRequest();
HttpServletResponse response = ServletUtils.getResponse();
try {
// FormToken 构造方法的三个参数登录名是否内部登录无条件请求对象
UserUtils.getSubject().login(new FormToken(getAuthUserToSysUserCode(oauthUserId), true, request));
System.out.println("登录成功__sid=" + UserUtils.getSession().getId());
FormFilter.onLoginSuccess(request, response);
} catch (AuthenticationException e) {
FormFilter.onLoginFailure(e, request, response);
}
HttpServletRequest request = ServletUtils.getRequest();
HttpServletResponse response = ServletUtils.getResponse();
try {
// FormToken 构造方法的三个参数登录名是否内部登录无条件请求对象
UserUtils.getSubject().login(new FormToken(getAuthUserToSysUserCode(oauthUserId), true, request));
System.out.println("登录成功__sid=" + UserUtils.getSession().getId());
FormFilter.onLoginSuccess(request, response);
} catch (AuthenticationException e) {
FormFilter.onLoginFailure(e, request, response);
}
}
@ -71,11 +71,11 @@ public class Oauth2UserLoginUtils{
// jeegit:
// clientId: 823874316692094976
// clientSecret: t74BMTcwMjIwMjMwODIzNTA4NDQFLu
// serverUrl: http://sso.maxkey.top
// redirectUri: http://localhost:8980/js/oauth2/callback/jeegit
// className: com.jeesite.modules.oauth2.request.AuthMaxKeyRequest
// clientId: 823874316692094976
// clientSecret: t74BMTcwMjIwMjMwODIzNTA4NDQFLu
// serverUrl: http://sso.maxkey.top
// redirectUri: http://localhost:8980/js/oauth2/callback/jeegit
// className: com.jeesite.modules.oauth2.request.AuthMaxKeyRequest
authRequest = new AuthMaxKeyJeeGitRequest(AuthConfig.builder()
.clientId(Global.getProperty("oauth2." + source + ".clientId"))
.clientSecret(Global.getProperty("oauth2." + source + ".clientSecret"))

View File

@ -36,47 +36,47 @@ public class JustOauth2Controller extends BaseController implements IBaseJustOau
@Override
@RequestMapping({"/login/{source}"})
public String login(String source, HttpServletRequest request) {
// TODO Auto-generated method stub
logger.debug(source);
return "redirect:" + Oauth2UserLoginUtils.getAuthRequest(source).authorize((request.getParameter("state") == null ? AuthStateUtils.createState() : request.getParameter("state")));
// TODO Auto-generated method stub
logger.debug(source);
return "redirect:" + Oauth2UserLoginUtils.getAuthRequest(source).authorize((request.getParameter("state") == null ? AuthStateUtils.createState() : request.getParameter("state")));
}
@Override
@RequestMapping({"/callback/{source}"})
public String callback(String source, AuthCallback callback, RedirectAttributes redirectAttributes, Model model, HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
logger.debug(source);
// TODO Auto-generated method stub
logger.debug(source);
AuthRequest authRequest = Oauth2UserLoginUtils.getAuthRequest(source);
AuthResponse<?> rauthResponse = authRequest.login(callback);
if(rauthResponse.getData() instanceof AuthUser) {
AuthUser authUser = (AuthUser) rauthResponse.getData();
//处理相关的绑定业务该处仅做简单集成与演示专用
logger.debug("authUser:"+JsonMapper.toJson(authUser));
Oauth2UserLoginUtils.loginByOauthUserId(authUser.getUsername());
return renderResult(Global.TRUE, text("回调信息获取成功!"));
} else {
return null;
}
AuthRequest authRequest = Oauth2UserLoginUtils.getAuthRequest(source);
AuthResponse<?> rauthResponse = authRequest.login(callback);
if(rauthResponse.getData() instanceof AuthUser) {
AuthUser authUser = (AuthUser) rauthResponse.getData();
//处理相关的绑定业务该处仅做简单集成与演示专用
logger.debug("authUser:"+JsonMapper.toJson(authUser));
Oauth2UserLoginUtils.loginByOauthUserId(authUser.getUsername());
return renderResult(Global.TRUE, text("回调信息获取成功!"));
} else {
return null;
}
}
@Override
@PostMapping({"/binder"})
@ResponseBody
public String binder(String id, String username, String password, String validCode, HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
logger.debug(id, username);
return null;
// TODO Auto-generated method stub
logger.debug(id, username);
return null;
}
@Override
@RequestMapping({"/unbind"})
@ResponseBody
public String unbind(String id, HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
logger.debug(id);
return null;
// TODO Auto-generated method stub
logger.debug(id);
return null;
}
}

View File

@ -6,9 +6,9 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootOauthClientApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootOauthClientApplication.class, args);
}
public static void main(String[] args) {
SpringApplication.run(SpringBootOauthClientApplication.class, args);
}
}

View File

@ -12,31 +12,31 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur
@Configuration
@EnableOAuth2Sso
public class ResourceServerConfiguration extends WebSecurityConfigurerAdapter {
Logger log = LoggerFactory.getLogger(ResourceServerConfiguration.class);
@Value("${maxkey-auth-url}")
String maxkeyAuthUrl;
@Value("${security.oauth2.client.user-authorization-uri}")
String userAuthorizationUri;
@Value("${security.oauth2.client.access-token-uri}")
String accessTokenUri;
@Value("${security.oauth2.resource.user-info-uri}")
String userInfoUri;
Logger log = LoggerFactory.getLogger(ResourceServerConfiguration.class);
@Value("${maxkey-auth-url}")
String maxkeyAuthUrl;
@Value("${security.oauth2.client.user-authorization-uri}")
String userAuthorizationUri;
@Value("${security.oauth2.client.access-token-uri}")
String accessTokenUri;
@Value("${security.oauth2.resource.user-info-uri}")
String userInfoUri;
@Override
public void configure(HttpSecurity http) throws Exception {
//http.antMatcher("/orgs/**").antMatcher("/userinfo").antMatcher("/login").authorizeRequests().anyRequest().authenticated();
http.authorizeRequests().anyRequest().authenticated().and().csrf().disable();
log.info("UserAuthorizationUri {}" ,userAuthorizationUri);
log.info("AccessTokenUri {}" ,accessTokenUri);
log.info("UserInfoUri {}" ,userInfoUri);
if(accessTokenUri.startsWith("https")) {
HttpsTrusts.beforeConnection();
}
log.debug("ResourceServerConfiguration");
http.authorizeRequests().anyRequest().authenticated().and().csrf().disable();
log.info("UserAuthorizationUri {}" ,userAuthorizationUri);
log.info("AccessTokenUri {}" ,accessTokenUri);
log.info("UserInfoUri {}" ,userInfoUri);
if(accessTokenUri.startsWith("https")) {
HttpsTrusts.beforeConnection();
}
log.debug("ResourceServerConfiguration");
}
}

View File

@ -10,11 +10,11 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
public class ResourceController {
Logger log = LoggerFactory.getLogger(ResourceController.class);
Logger log = LoggerFactory.getLogger(ResourceController.class);
@GetMapping("/")
public String index() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication.getPrincipal().toString();
}
}

View File

@ -24,52 +24,52 @@ import javax.net.ssl.SSLSession;
public class HttpsTrusts {
private static void trustAllHttpsCertificates() throws Exception {
javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
javax.net.ssl.TrustManager tm = new HttpsTrustsTM();
trustAllCerts[0] = tm;
javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
javax.net.ssl.TrustManager tm = new HttpsTrustsTM();
trustAllCerts[0] = tm;
javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
/*
* https ssl auto trust
*/
public static void beforeConnection() {
try {
trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
return true;
}
});
} catch(Exception e) {
e.printStackTrace();
}
}
static class HttpsTrustsTM implements javax.net.ssl.TrustManager,javax.net.ssl.X509TrustManager {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public static void beforeConnection() {
try {
trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
return true;
}
});
} catch(Exception e) {
e.printStackTrace();
}
}
static class HttpsTrustsTM implements javax.net.ssl.TrustManager,javax.net.ssl.X509TrustManager {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
return true;
}
public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
return true;
}
public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
return true;
}
public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
return true;
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
}
}

View File

@ -9,17 +9,17 @@ import java.util.Map;
@Controller
public class AppController {
@GetMapping("hello")
public ModelAndView welcome() {
ModelAndView mav = new ModelAndView();
mav.setViewName("welcome");
return mav;
@GetMapping("hello")
public ModelAndView welcome() {
ModelAndView mav = new ModelAndView();
mav.setViewName("welcome");
return mav;
}
@GetMapping("error")
public ModelAndView error() {
Map<String, String> model = new HashMap<>();
ModelAndView mav = new ModelAndView();
mav.setViewName("error");
return mav;
}
@GetMapping("error")
public ModelAndView error() {
Map<String, String> model = new HashMap<>();
ModelAndView mav = new ModelAndView();
mav.setViewName("error");
return mav;
}
}

View File

@ -5,7 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MainClient1 {
public static void main(String[] args) {
SpringApplication.run(MainClient1.class, args);
}
public static void main(String[] args) {
SpringApplication.run(MainClient1.class, args);
}
}

View File

@ -8,14 +8,14 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur
@Configuration
@EnableOAuth2Sso
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/error**").permitAll()
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/error**").permitAll()
.anyRequest().authenticated()
.and().logout().logoutUrl("/logout")
.logoutSuccessUrl("http://sso.maxkey.top/sign/force/logout");
.logoutSuccessUrl("http://sso.maxkey.top/sign/force/logout");
}
}
}

View File

@ -9,17 +9,17 @@ import java.util.Map;
@Controller
public class AppController {
@GetMapping("hello")
public ModelAndView welcome() {
ModelAndView mav = new ModelAndView();
mav.setViewName("welcome");
return mav;
@GetMapping("hello")
public ModelAndView welcome() {
ModelAndView mav = new ModelAndView();
mav.setViewName("welcome");
return mav;
}
@GetMapping("error")
public ModelAndView error() {
Map<String, String> model = new HashMap<>();
ModelAndView mav = new ModelAndView();
mav.setViewName("error");
return mav;
}
@GetMapping("error")
public ModelAndView error() {
Map<String, String> model = new HashMap<>();
ModelAndView mav = new ModelAndView();
mav.setViewName("error");
return mav;
}
}

View File

@ -5,7 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MainClient2 {
public static void main(String[] args) {
SpringApplication.run(MainClient2.class, args);
}
public static void main(String[] args) {
SpringApplication.run(MainClient2.class, args);
}
}

View File

@ -8,14 +8,14 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur
@Configuration
@EnableOAuth2Sso
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/error**").permitAll()
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/error**").permitAll()
.anyRequest().authenticated()
.and().logout().logoutUrl("/logout")
.logoutSuccessUrl("http://sso.maxkey.top/sign/force/logout");
.logoutSuccessUrl("http://sso.maxkey.top/sign/force/logout");
}
}
}

View File

@ -37,7 +37,7 @@ public class SignPrincipal implements UserDetails {
String sessionId;
int twoFactor;
int twoFactor;
List<GrantedAuthority> grantedAuthority;
@ -47,13 +47,13 @@ public class SignPrincipal implements UserDetails {
boolean roleAdministrators;
private boolean accountNonExpired;
private boolean accountNonExpired;
private boolean accountNonLocked;
private boolean accountNonLocked;
private boolean credentialsNonExpired;
private boolean credentialsNonExpired;
private boolean enabled;
private boolean enabled;
/**
* SigninPrincipal.
@ -160,22 +160,22 @@ public class SignPrincipal implements UserDetails {
public String getSessionId() {
return sessionId;
}
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public String getInstId() {
return instId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public String getInstId() {
return instId;
}
public String getUserId() {
return userId;
}
public String getUserId() {
return userId;
}
@Override
@Override
public boolean isEnabled() {
return this.enabled;
}
@ -207,45 +207,45 @@ public class SignPrincipal implements UserDetails {
}
public int getTwoFactor() {
return twoFactor;
}
return twoFactor;
}
public void setTwoFactor(int twoFactor) {
this.twoFactor = twoFactor;
}
public void clearTwoFactor() {
this.twoFactor = 0;
}
public void setTwoFactor(int twoFactor) {
this.twoFactor = twoFactor;
}
public void clearTwoFactor() {
this.twoFactor = 0;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Principal [username=");
builder.append(getUsername());
builder.append(", userInfo=");
builder.append(userInfo);
builder.append(", userDetails=");
builder.append(userDetails);
builder.append(", grantedAuthority=");
builder.append(grantedAuthority);
builder.append(", grantedAuthorityApps=");
builder.append(grantedAuthorityApps);
builder.append(", authenticated=");
builder.append(authenticated);
builder.append(", roleAdministrators=");
builder.append(roleAdministrators);
builder.append(", accountNonExpired=");
builder.append(accountNonExpired);
builder.append(", accountNonLocked=");
builder.append(accountNonLocked);
builder.append(", credentialsNonExpired=");
builder.append(credentialsNonExpired);
builder.append(", enabled=");
builder.append(enabled);
builder.append("]");
return builder.toString();
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Principal [username=");
builder.append(getUsername());
builder.append(", userInfo=");
builder.append(userInfo);
builder.append(", userDetails=");
builder.append(userDetails);
builder.append(", grantedAuthority=");
builder.append(grantedAuthority);
builder.append(", grantedAuthorityApps=");
builder.append(grantedAuthorityApps);
builder.append(", authenticated=");
builder.append(authenticated);
builder.append(", roleAdministrators=");
builder.append(roleAdministrators);
builder.append(", accountNonExpired=");
builder.append(accountNonExpired);
builder.append(", accountNonLocked=");
builder.append(accountNonLocked);
builder.append(", credentialsNonExpired=");
builder.append(credentialsNonExpired);
builder.append(", enabled=");
builder.append(enabled);
builder.append("]");
return builder.toString();
}

View File

@ -31,218 +31,218 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema;
public class AuthJwt implements Serializable {
private static final long serialVersionUID = -914373258878811144L;
public static final String ACCESS_TOKEN = "access_token";
public static final String REFRESH_TOKEN = "refresh_token";
public static final String EXPIRES_IN = "expired";
private String ticket;
private String type = "Bearer";
private String token;
@JsonProperty(REFRESH_TOKEN)
private String refreshToken;
@JsonProperty(EXPIRES_IN)
private int expiresIn;
@JsonFormat(shape = JsonFormat.Shape.STRING)
@Schema(name = "twoFactor", description = "二次认证类型")
int twoFactor;
private static final long serialVersionUID = -914373258878811144L;
public static final String ACCESS_TOKEN = "access_token";
public static final String REFRESH_TOKEN = "refresh_token";
public static final String EXPIRES_IN = "expired";
private String ticket;
private String type = "Bearer";
private String token;
@JsonProperty(REFRESH_TOKEN)
private String refreshToken;
@JsonProperty(EXPIRES_IN)
private int expiresIn;
@JsonFormat(shape = JsonFormat.Shape.STRING)
@Schema(name = "twoFactor", description = "二次认证类型")
int twoFactor;
private String remeberMe;
private String id;
private String name;
private String username;
private String displayName;
private String email;
private String instId;
private String instName;
private int passwordSetType;
private List<String> authorities;
public AuthJwt(String ticket, String type, String token, String refreshToken, int expiresIn, String remeberMe,
String id, String name, String username, String displayName, String email, String instId, String instName,
int passwordSetType, List<String> authorities) {
super();
this.ticket = ticket;
this.type = type;
this.token = token;
this.refreshToken = refreshToken;
this.expiresIn = expiresIn;
this.remeberMe = remeberMe;
this.id = id;
this.name = name;
this.username = username;
this.displayName = displayName;
this.email = email;
this.instId = instId;
this.instName = instName;
this.passwordSetType = passwordSetType;
this.authorities = authorities;
}
private String remeberMe;
private String id;
private String name;
private String username;
private String displayName;
private String email;
private String instId;
private String instName;
private int passwordSetType;
private List<String> authorities;
public AuthJwt(String ticket, String type, String token, String refreshToken, int expiresIn, String remeberMe,
String id, String name, String username, String displayName, String email, String instId, String instName,
int passwordSetType, List<String> authorities) {
super();
this.ticket = ticket;
this.type = type;
this.token = token;
this.refreshToken = refreshToken;
this.expiresIn = expiresIn;
this.remeberMe = remeberMe;
this.id = id;
this.name = name;
this.username = username;
this.displayName = displayName;
this.email = email;
this.instId = instId;
this.instName = instName;
this.passwordSetType = passwordSetType;
this.authorities = authorities;
}
public AuthJwt(String token, Authentication authentication,int expiresIn,String refreshToken) {
SignPrincipal principal = ((SignPrincipal)authentication.getPrincipal());
this.token = token;
this.expiresIn = expiresIn;
this.refreshToken = refreshToken;
this.ticket = principal.getSessionId();
this.id = principal.getUserInfo().getId();
this.username = principal.getUserInfo().getUsername();
this.name = this.username;
this.displayName = principal.getUserInfo().getDisplayName();
this.email = principal.getUserInfo().getEmail();
this.instId = principal.getUserInfo().getInstId();
this.instName = principal.getUserInfo().getInstName();
this.twoFactor =principal.getTwoFactor();
this.authorities = new ArrayList<>();
for(GrantedAuthority grantedAuthority :authentication.getAuthorities()) {
this.authorities.add(grantedAuthority.getAuthority());
}
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public AuthJwt(String token, Authentication authentication,int expiresIn,String refreshToken) {
SignPrincipal principal = ((SignPrincipal)authentication.getPrincipal());
this.token = token;
this.expiresIn = expiresIn;
this.refreshToken = refreshToken;
this.ticket = principal.getSessionId();
this.id = principal.getUserInfo().getId();
this.username = principal.getUserInfo().getUsername();
this.name = this.username;
this.displayName = principal.getUserInfo().getDisplayName();
this.email = principal.getUserInfo().getEmail();
this.instId = principal.getUserInfo().getInstId();
this.instName = principal.getUserInfo().getInstName();
this.twoFactor =principal.getTwoFactor();
this.authorities = new ArrayList<>();
for(GrantedAuthority grantedAuthority :authentication.getAuthorities()) {
this.authorities.add(grantedAuthority.getAuthority());
}
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getInstId() {
return instId;
}
public void setInstId(String instId) {
this.instId = instId;
}
public String getInstName() {
return instName;
}
public void setInstName(String instName) {
this.instName = instName;
}
public List<String> getAuthorities() {
return authorities;
}
public void setAuthorities(List<String> authorities) {
this.authorities = authorities;
}
public String getTicket() {
return ticket;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getInstId() {
return instId;
}
public void setInstId(String instId) {
this.instId = instId;
}
public String getInstName() {
return instName;
}
public void setInstName(String instName) {
this.instName = instName;
}
public List<String> getAuthorities() {
return authorities;
}
public void setAuthorities(List<String> authorities) {
this.authorities = authorities;
}
public String getTicket() {
return ticket;
}
public void setTicket(String ticket) {
this.ticket = ticket;
}
public int getPasswordSetType() {
return passwordSetType;
}
public void setTicket(String ticket) {
this.ticket = ticket;
}
public int getPasswordSetType() {
return passwordSetType;
}
public void setPasswordSetType(int passwordSetType) {
this.passwordSetType = passwordSetType;
}
public String getRemeberMe() {
return remeberMe;
}
public void setPasswordSetType(int passwordSetType) {
this.passwordSetType = passwordSetType;
}
public String getRemeberMe() {
return remeberMe;
}
public void setRemeberMe(String remeberMe) {
this.remeberMe = remeberMe;
}
public void setRemeberMe(String remeberMe) {
this.remeberMe = remeberMe;
}
public String getRefreshToken() {
return refreshToken;
}
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
public int getExpiresIn() {
return expiresIn;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
public int getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(int expiresIn) {
this.expiresIn = expiresIn;
}
public void setExpiresIn(int expiresIn) {
this.expiresIn = expiresIn;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("AuthJwt [token=");
builder.append(token);
builder.append(", type=");
builder.append(type);
builder.append(", id=");
builder.append(id);
builder.append(", username=");
builder.append(username);
builder.append(", displayName=");
builder.append(displayName);
builder.append(", email=");
builder.append(email);
builder.append(", instId=");
builder.append(instId);
builder.append(", instName=");
builder.append(instName);
builder.append(", authorities=");
builder.append(authorities);
builder.append("]");
return builder.toString();
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("AuthJwt [token=");
builder.append(token);
builder.append(", type=");
builder.append(type);
builder.append(", id=");
builder.append(id);
builder.append(", username=");
builder.append(username);
builder.append(", displayName=");
builder.append(displayName);
builder.append(", email=");
builder.append(email);
builder.append(", instId=");
builder.append(instId);
builder.append(", instName=");
builder.append(instName);
builder.append(", authorities=");
builder.append(authorities);
builder.append("]");
return builder.toString();
}
}

View File

@ -37,116 +37,116 @@ import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
public class AuthJwtService {
private static final Logger _logger = LoggerFactory.getLogger(AuthJwtService.class);
Hmac512Service hmac512Service;
/**
* JWT with Authentication
* @param authentication
* @return
*/
public String genJwt(Authentication authentication,String issuer,int expires) {
SignPrincipal principal = ((SignPrincipal)authentication.getPrincipal());
UserInfo userInfo = principal.getUserInfo();
DateTime currentDateTime = DateTime.now();
String subject = principal.getUsername();
Date expirationTime = currentDateTime.plusSeconds(expires).toDate();
_logger.trace("jwt subject : {} , expiration Time : {}" , subject,expirationTime);
JWTClaimsSet jwtClaims =new JWTClaimsSet.Builder()
.issuer(issuer)
.subject(subject)
.jwtID(principal.getSessionId())
.issueTime(currentDateTime.toDate())
.expirationTime(expirationTime)
.claim("locale", userInfo.getLocale())
.claim("kid", Hmac512Service.MXK_AUTH_JWK)
.claim(ConstsJwt.USER_ID, userInfo.getId())
.claim(ConstsJwt.INST_ID, userInfo.getInstId())
.build();
return signedJWT(jwtClaims);
}
/**
* JWT with subject
* @param subject subject
* @return
*/
public String genJwt(String subject,String issuer,int expires) {
DateTime currentDateTime = DateTime.now();
Date expirationTime = currentDateTime.plusSeconds(expires).toDate();
_logger.trace("jwt subject : {} , expiration Time : {}" , subject,expirationTime);
JWTClaimsSet jwtClaims =new JWTClaimsSet.Builder()
.issuer(issuer)
.subject(subject)
.jwtID(WebContext.genId())
.issueTime(currentDateTime.toDate())
.expirationTime(expirationTime)
.build();
return signedJWT(jwtClaims);
}
/**
* Random JWT
* @return
*/
public String genRandomJwt(int expires) {
Date expirationTime = DateTime.now().plusSeconds(expires).toDate();
_logger.trace("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);
return hmac512Service.sign(jwtToken.getPayload());
}
/**
* Verify with HMAC512 and check ExpirationTime
*
* @param authToken
* @return true or false
*/
public boolean validateJwtToken(String authToken) {
if(StringUtils.isNotBlank(authToken) && authToken.length() > 20) {
try {
JWTClaimsSet claims = resolve(authToken);
boolean isExpiration = claims.getExpirationTime().after(DateTime.now().toDate());
boolean isVerify = hmac512Service.verify(authToken);
boolean isValidate = isVerify && isExpiration;
_logger.trace("JWT Validate {} " , isValidate);
_logger.debug("HMAC Verify {} , now {} , ExpirationTime {} , is not Expiration : {}" ,
isVerify,DateTime.now().toDate(),claims.getExpirationTime(),isExpiration);
return isValidate;
} catch (ParseException e) {
_logger.error("authToken {}",authToken);
_logger.error("ParseException ",e);
}
}
return false;
}
public JWTClaimsSet resolve(String authToken) throws ParseException {
SignedJWT signedJWT = SignedJWT.parse(authToken);
_logger.trace("jwt Claims : {}" , signedJWT.getJWTClaimsSet());
return signedJWT.getJWTClaimsSet();
}
public String resolveJWTID(String authToken) throws ParseException {
JWTClaimsSet claims = resolve(authToken);
return claims.getJWTID();
}
private static final Logger _logger = LoggerFactory.getLogger(AuthJwtService.class);
Hmac512Service hmac512Service;
/**
* JWT with Authentication
* @param authentication
* @return
*/
public String genJwt(Authentication authentication,String issuer,int expires) {
SignPrincipal principal = ((SignPrincipal)authentication.getPrincipal());
UserInfo userInfo = principal.getUserInfo();
DateTime currentDateTime = DateTime.now();
String subject = principal.getUsername();
Date expirationTime = currentDateTime.plusSeconds(expires).toDate();
_logger.trace("jwt subject : {} , expiration Time : {}" , subject,expirationTime);
JWTClaimsSet jwtClaims =new JWTClaimsSet.Builder()
.issuer(issuer)
.subject(subject)
.jwtID(principal.getSessionId())
.issueTime(currentDateTime.toDate())
.expirationTime(expirationTime)
.claim("locale", userInfo.getLocale())
.claim("kid", Hmac512Service.MXK_AUTH_JWK)
.claim(ConstsJwt.USER_ID, userInfo.getId())
.claim(ConstsJwt.INST_ID, userInfo.getInstId())
.build();
return signedJWT(jwtClaims);
}
/**
* JWT with subject
* @param subject subject
* @return
*/
public String genJwt(String subject,String issuer,int expires) {
DateTime currentDateTime = DateTime.now();
Date expirationTime = currentDateTime.plusSeconds(expires).toDate();
_logger.trace("jwt subject : {} , expiration Time : {}" , subject,expirationTime);
JWTClaimsSet jwtClaims =new JWTClaimsSet.Builder()
.issuer(issuer)
.subject(subject)
.jwtID(WebContext.genId())
.issueTime(currentDateTime.toDate())
.expirationTime(expirationTime)
.build();
return signedJWT(jwtClaims);
}
/**
* Random JWT
* @return
*/
public String genRandomJwt(int expires) {
Date expirationTime = DateTime.now().plusSeconds(expires).toDate();
_logger.trace("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);
return hmac512Service.sign(jwtToken.getPayload());
}
/**
* Verify with HMAC512 and check ExpirationTime
*
* @param authToken
* @return true or false
*/
public boolean validateJwtToken(String authToken) {
if(StringUtils.isNotBlank(authToken) && authToken.length() > 20) {
try {
JWTClaimsSet claims = resolve(authToken);
boolean isExpiration = claims.getExpirationTime().after(DateTime.now().toDate());
boolean isVerify = hmac512Service.verify(authToken);
boolean isValidate = isVerify && isExpiration;
_logger.trace("JWT Validate {} " , isValidate);
_logger.debug("HMAC Verify {} , now {} , ExpirationTime {} , is not Expiration : {}" ,
isVerify,DateTime.now().toDate(),claims.getExpirationTime(),isExpiration);
return isValidate;
} catch (ParseException e) {
_logger.error("authToken {}",authToken);
_logger.error("ParseException ",e);
}
}
return false;
}
public JWTClaimsSet resolve(String authToken) throws ParseException {
SignedJWT signedJWT = SignedJWT.parse(authToken);
_logger.trace("jwt Claims : {}" , signedJWT.getJWTClaimsSet());
return signedJWT.getJWTClaimsSet();
}
public String resolveJWTID(String authToken) throws ParseException {
JWTClaimsSet claims = resolve(authToken);
return claims.getJWTID();
}
}

View File

@ -26,26 +26,26 @@ import org.springframework.security.core.Authentication;
import com.nimbusds.jose.JOSEException;
public class AuthRefreshTokenService extends AuthJwtService{
private static final Logger _logger = LoggerFactory.getLogger(AuthRefreshTokenService.class);
AuthJwkConfig authJwkConfig;
public AuthRefreshTokenService(AuthJwkConfig authJwkConfig) throws JOSEException {
this.authJwkConfig = authJwkConfig;
this.hmac512Service = new Hmac512Service(authJwkConfig.getRefreshSecret());
}
/**
* JWT Refresh Token with Authentication
* @param authentication
* @return
*/
public String genRefreshToken(Authentication authentication) {
_logger.trace("generate Refresh JWT Token");
return genJwt(
authentication,
authJwkConfig.getIssuer(),
authJwkConfig.getRefreshExpires());
}
private static final Logger _logger = LoggerFactory.getLogger(AuthRefreshTokenService.class);
AuthJwkConfig authJwkConfig;
public AuthRefreshTokenService(AuthJwkConfig authJwkConfig) throws JOSEException {
this.authJwkConfig = authJwkConfig;
this.hmac512Service = new Hmac512Service(authJwkConfig.getRefreshSecret());
}
/**
* JWT Refresh Token with Authentication
* @param authentication
* @return
*/
public String genRefreshToken(Authentication authentication) {
_logger.trace("generate Refresh JWT Token");
return genJwt(
authentication,
authJwkConfig.getIssuer(),
authJwkConfig.getRefreshExpires());
}
}

View File

@ -30,112 +30,112 @@ import org.springframework.security.core.Authentication;
import com.nimbusds.jose.JOSEException;
public class AuthTokenService extends AuthJwtService{
private static final Logger _logger = LoggerFactory.getLogger(AuthTokenService.class);
AuthJwkConfig authJwkConfig;
CongressService congressService;
MomentaryService momentaryService;
AuthRefreshTokenService refreshTokenService;
public AuthTokenService(
AuthJwkConfig authJwkConfig,
CongressService congressService,
MomentaryService momentaryService,
AuthRefreshTokenService refreshTokenService) throws JOSEException {
this.authJwkConfig = authJwkConfig;
this.congressService = congressService;
this.momentaryService = momentaryService;
this.refreshTokenService = refreshTokenService;
this.hmac512Service = new Hmac512Service(authJwkConfig.getSecret());
}
/**
* create AuthJwt use Authentication JWT
* @param authentication
* @return AuthJwt
*/
public AuthJwt genAuthJwt(Authentication authentication) {
if(authentication != null) {
String refreshToken = refreshTokenService.genRefreshToken(authentication);
_logger.trace("generate JWT Token");
String accessToken = genJwt(authentication);
return new AuthJwt(
accessToken,
authentication,
authJwkConfig.getExpires(),
refreshToken);
}
return null;
}
public String genJwt(Authentication authentication) {
return genJwt(
authentication,
authJwkConfig.getIssuer(),
authJwkConfig.getExpires());
}
/**
* JWT with subject
* @param subject subject
* @return
*/
public String genJwt(String subject) {
return genJwt(subject,authJwkConfig.getIssuer(),authJwkConfig.getExpires());
}
/**
* Random JWT
* @return
*/
public String genRandomJwt() {
return genRandomJwt(authJwkConfig.getExpires());
}
public String createCongress(Authentication authentication) {
String congress = WebContext.genId();
String refreshToken = refreshTokenService.genRefreshToken(authentication);
congressService.store(
congress,
new AuthJwt(
genJwt(authentication),
authentication,
authJwkConfig.getExpires(),
refreshToken)
);
return congress;
}
public AuthJwt consumeCongress(String congress) {
return congressService.consume(congress);
}
public boolean validateCaptcha(String state,String captcha) {
try {
String jwtId = resolveJWTID(state);
if(StringUtils.isNotBlank(jwtId) &&StringUtils.isNotBlank(captcha)) {
Object momentaryCaptcha = momentaryService.get("", jwtId);
_logger.debug("captcha : {}, momentary Captcha : {}" ,captcha, momentaryCaptcha);
if (!StringUtils.isBlank(captcha) &&momentaryCaptcha != null && captcha.equals(momentaryCaptcha.toString())) {
momentaryService.remove("", jwtId);
return true;
}
}
} catch (ParseException e) {
_logger.debug("Exception ",e);
}
return false;
private static final Logger _logger = LoggerFactory.getLogger(AuthTokenService.class);
AuthJwkConfig authJwkConfig;
CongressService congressService;
MomentaryService momentaryService;
AuthRefreshTokenService refreshTokenService;
public AuthTokenService(
AuthJwkConfig authJwkConfig,
CongressService congressService,
MomentaryService momentaryService,
AuthRefreshTokenService refreshTokenService) throws JOSEException {
this.authJwkConfig = authJwkConfig;
this.congressService = congressService;
this.momentaryService = momentaryService;
this.refreshTokenService = refreshTokenService;
this.hmac512Service = new Hmac512Service(authJwkConfig.getSecret());
}
/**
* create AuthJwt use Authentication JWT
* @param authentication
* @return AuthJwt
*/
public AuthJwt genAuthJwt(Authentication authentication) {
if(authentication != null) {
String refreshToken = refreshTokenService.genRefreshToken(authentication);
_logger.trace("generate JWT Token");
String accessToken = genJwt(authentication);
return new AuthJwt(
accessToken,
authentication,
authJwkConfig.getExpires(),
refreshToken);
}
return null;
}
public String genJwt(Authentication authentication) {
return genJwt(
authentication,
authJwkConfig.getIssuer(),
authJwkConfig.getExpires());
}
/**
* JWT with subject
* @param subject subject
* @return
*/
public String genJwt(String subject) {
return genJwt(subject,authJwkConfig.getIssuer(),authJwkConfig.getExpires());
}
/**
* Random JWT
* @return
*/
public String genRandomJwt() {
return genRandomJwt(authJwkConfig.getExpires());
}
public String createCongress(Authentication authentication) {
String congress = WebContext.genId();
String refreshToken = refreshTokenService.genRefreshToken(authentication);
congressService.store(
congress,
new AuthJwt(
genJwt(authentication),
authentication,
authJwkConfig.getExpires(),
refreshToken)
);
return congress;
}
public AuthJwt consumeCongress(String congress) {
return congressService.consume(congress);
}
public boolean validateCaptcha(String state,String captcha) {
try {
String jwtId = resolveJWTID(state);
if(StringUtils.isNotBlank(jwtId) &&StringUtils.isNotBlank(captcha)) {
Object momentaryCaptcha = momentaryService.get("", jwtId);
_logger.debug("captcha : {}, momentary Captcha : {}" ,captcha, momentaryCaptcha);
if (!StringUtils.isBlank(captcha) &&momentaryCaptcha != null && captcha.equals(momentaryCaptcha.toString())) {
momentaryService.remove("", jwtId);
return true;
}
}
} catch (ParseException e) {
_logger.debug("Exception ",e);
}
return false;
}
}

View File

@ -19,10 +19,10 @@ package org.dromara.maxkey.authn.jwt;
public interface CongressService {
public void store(String congress, AuthJwt authJwt);
public void store(String congress, AuthJwt authJwt);
public AuthJwt consume(String congress);
public AuthJwt consume(String congress);
public AuthJwt remove(String congress);
public AuthJwt get(String congress);

View File

@ -28,38 +28,38 @@ import com.github.benmanes.caffeine.cache.Caffeine;
public class InMemoryCongressService implements CongressService{
private static final Logger logger = LoggerFactory.getLogger(InMemoryCongressService.class);
protected static Cache<String, AuthJwt> congressStore =
Caffeine.newBuilder()
.expireAfterWrite(3, TimeUnit.MINUTES)
.maximumSize(200000)
.build();
public InMemoryCongressService() {
protected static Cache<String, AuthJwt> congressStore =
Caffeine.newBuilder()
.expireAfterWrite(3, TimeUnit.MINUTES)
.maximumSize(200000)
.build();
public InMemoryCongressService() {
super();
}
@Override
public void store(String congress, AuthJwt authJwt) {
congressStore.put(congress, authJwt);
}
public void store(String congress, AuthJwt authJwt) {
congressStore.put(congress, authJwt);
}
@Override
public AuthJwt remove(String congress) {
AuthJwt authJwt = congressStore.getIfPresent(congress);
congressStore.invalidate(congress);
return authJwt;
}
@Override
public AuthJwt remove(String congress) {
AuthJwt authJwt = congressStore.getIfPresent(congress);
congressStore.invalidate(congress);
return authJwt;
}
@Override
public AuthJwt get(String congress) {
return congressStore.getIfPresent(congress);
return congressStore.getIfPresent(congress);
}
@Override
public AuthJwt consume(String congress) {
AuthJwt authJwt = congressStore.getIfPresent(congress);
congressStore.invalidate(congress);
return authJwt;
}
@Override
public AuthJwt consume(String congress) {
AuthJwt authJwt = congressStore.getIfPresent(congress);
congressStore.invalidate(congress);
return authJwt;
}
}

View File

@ -25,47 +25,47 @@ import org.slf4j.LoggerFactory;
public class RedisCongressService implements CongressService {
private static final Logger logger = LoggerFactory.getLogger(RedisCongressService.class);
protected int validitySeconds = 60 * 3; //default 3 minutes.
RedisConnectionFactory connectionFactory;
public static final String PREFIX = "REDIS:CONGRESS:";
/**
* @param connectionFactory
*/
public RedisCongressService(
RedisConnectionFactory connectionFactory) {
super();
this.connectionFactory = connectionFactory;
}
/**
*
*/
public RedisCongressService() {
}
protected int validitySeconds = 60 * 3; //default 3 minutes.
RedisConnectionFactory connectionFactory;
public static final String PREFIX = "REDIS:CONGRESS:";
/**
* @param connectionFactory
*/
public RedisCongressService(
RedisConnectionFactory connectionFactory) {
super();
this.connectionFactory = connectionFactory;
}
/**
*
*/
public RedisCongressService() {
}
public void setConnectionFactory(RedisConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
public void setConnectionFactory(RedisConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
@Override
public void store(String congress, AuthJwt authJwt) {
RedisConnection conn = connectionFactory.getConnection();
conn.setexObject(PREFIX + congress, validitySeconds, authJwt);
conn.close();
}
@Override
public void store(String congress, AuthJwt authJwt) {
RedisConnection conn = connectionFactory.getConnection();
conn.setexObject(PREFIX + congress, validitySeconds, authJwt);
conn.close();
}
@Override
public AuthJwt remove(String congress) {
RedisConnection conn=connectionFactory.getConnection();
AuthJwt authJwt = conn.getObject(PREFIX + congress);
conn.delete(PREFIX+congress);
conn.close();
return authJwt;
}
@Override
public AuthJwt remove(String congress) {
RedisConnection conn=connectionFactory.getConnection();
AuthJwt authJwt = conn.getObject(PREFIX + congress);
conn.delete(PREFIX+congress);
conn.close();
return authJwt;
}
@Override
public AuthJwt get(String congress) {
@ -75,14 +75,14 @@ public class RedisCongressService implements CongressService {
return authJwt;
}
@Override
public AuthJwt consume(String congress) {
RedisConnection conn=connectionFactory.getConnection();
AuthJwt authJwt = conn.getObject(PREFIX + congress);
conn.delete(PREFIX+congress);
conn.close();
return authJwt;
}
@Override
public AuthJwt consume(String congress) {
RedisConnection conn=connectionFactory.getConnection();
AuthJwt authJwt = conn.getObject(PREFIX + congress);
conn.delete(PREFIX+congress);
conn.close();
return authJwt;
}
}

View File

@ -30,49 +30,49 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SessionListenerAdapter extends ScheduleAdapter implements Job , Serializable {
static final Logger logger = LoggerFactory.getLogger(SessionListenerAdapter.class);
private static final long serialVersionUID = 4782358765969474833L;
transient SessionManager sessionManager;
static final Logger logger = LoggerFactory.getLogger(SessionListenerAdapter.class);
private static final long serialVersionUID = 4782358765969474833L;
transient SessionManager sessionManager;
Integer category;
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
if(jobStatus == JOBSTATUS.RUNNING) {return;}
init(context);
logger.debug("running ... " );
Integer category;
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
if(jobStatus == JOBSTATUS.RUNNING) {return;}
init(context);
logger.debug("running ... " );
jobStatus = JOBSTATUS.RUNNING;
try {
if(sessionManager != null) {
int sessionCount = 0;
for (HistoryLogin login : sessionManager.querySessions(category)) {
Session session = sessionManager.get(login.getSessionId());
if(session == null) {
logger.debug("TimeOut user {} session {} Login at {} and at {} ." ,
login.getUsername(),
login.getId(),
login.getLoginTime(),
DateUtils.formatDateTime(new Date())
);
sessionManager.terminate(
login.getSessionId(),
login.getUserId(),
login.getUsername());
}else {
logger.debug("user {} session {} Login at {} , Last Access at {} will Expired at {}." ,
login.getUsername(),
login.getId(),
session.getStartTimestamp(),
session.getLastAccessTime(),
session.getExpiredTime()
);
sessionCount ++ ;
}
}
logger.debug("current session count {} ." ,sessionCount);
int sessionCount = 0;
for (HistoryLogin login : sessionManager.querySessions(category)) {
Session session = sessionManager.get(login.getSessionId());
if(session == null) {
logger.debug("TimeOut user {} session {} Login at {} and at {} ." ,
login.getUsername(),
login.getId(),
login.getLoginTime(),
DateUtils.formatDateTime(new Date())
);
sessionManager.terminate(
login.getSessionId(),
login.getUserId(),
login.getUsername());
}else {
logger.debug("user {} session {} Login at {} , Last Access at {} will Expired at {}." ,
login.getUsername(),
login.getId(),
session.getStartTimestamp(),
session.getLastAccessTime(),
session.getExpiredTime()
);
sessionCount ++ ;
}
}
logger.debug("current session count {} ." ,sessionCount);
}
logger.debug("finished " );
jobStatus = JOBSTATUS.FINISHED;
@ -80,15 +80,15 @@ public class SessionListenerAdapter extends ScheduleAdapter implements Job , S
jobStatus = JOBSTATUS.ERROR;
logger.error("Exception " ,e);
}
}
}
@Override
protected void init(JobExecutionContext context){
super.init(context);
if(sessionManager == null) {
sessionManager = getParameter("sessionManager",SessionManager.class);
category = getParameter("category",Integer.class);
@Override
protected void init(JobExecutionContext context){
super.init(context);
if(sessionManager == null) {
sessionManager = getParameter("sessionManager",SessionManager.class);
category = getParameter("category",Integer.class);
}
}
}

View File

@ -26,7 +26,7 @@ import org.dromara.maxkey.web.WebContext;
import org.springframework.security.core.Authentication;
public class Session implements Serializable{
private static final long serialVersionUID = 9008067569150338296L;
private static final long serialVersionUID = 9008067569150338296L;
public static final int MAX_EXPIRY_DURATION = 60 * 5; //default 5 minutes.
@ -65,8 +65,8 @@ public class Session implements Serializable{
}
public String getId() {
return id;
}
return id;
}
public void setId(String sessionId) {
this.id = sessionId;
@ -74,30 +74,30 @@ public class Session implements Serializable{
public LocalDateTime getStartTimestamp() {
return startTimestamp;
}
return startTimestamp;
}
public void setStartTimestamp(LocalDateTime startTimestamp) {
this.startTimestamp = startTimestamp;
}
public void setStartTimestamp(LocalDateTime startTimestamp) {
this.startTimestamp = startTimestamp;
}
public LocalDateTime getLastAccessTime() {
return lastAccessTime;
}
public LocalDateTime getLastAccessTime() {
return lastAccessTime;
}
public void setLastAccessTime(LocalDateTime lastAccessTime) {
this.lastAccessTime = lastAccessTime;
}
public void setLastAccessTime(LocalDateTime lastAccessTime) {
this.lastAccessTime = lastAccessTime;
}
public LocalDateTime getExpiredTime() {
return expiredTime;
}
public LocalDateTime getExpiredTime() {
return expiredTime;
}
public void setExpiredTime(LocalDateTime expiredTime) {
this.expiredTime = expiredTime;
}
public void setExpiredTime(LocalDateTime expiredTime) {
this.expiredTime = expiredTime;
}
public Authentication getAuthentication() {
public Authentication getAuthentication() {
return authentication;
}
@ -110,25 +110,25 @@ public class Session implements Serializable{
}
public Map<String, VisitedDto> getVisited() {
return visited;
}
return visited;
}
public void setVisited(Map<String, VisitedDto> visited) {
this.visited = visited;
}
public void setVisited(Map<String, VisitedDto> visited) {
this.visited = visited;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Session [id=");
builder.append(id);
builder.append(", startTimestamp=");
builder.append(startTimestamp);
builder.append(", lastAccessTime=");
builder.append(lastAccessTime);
builder.append("]");
return builder.toString();
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Session [id=");
builder.append(id);
builder.append(", startTimestamp=");
builder.append(startTimestamp);
builder.append(", lastAccessTime=");
builder.append(lastAccessTime);
builder.append("]");
return builder.toString();
}
}

View File

@ -18,13 +18,13 @@
package org.dromara.maxkey.authn.session;
public class SessionCategory {
/**
* 认证端
*/
public static final int SIGN = 1;
/**
* 管理端
*/
public static final int MGMT = 5;
/**
* 认证端
*/
public static final int SIGN = 1;
/**
* 管理端
*/
public static final int MGMT = 5;
}

View File

@ -24,7 +24,7 @@ import org.dromara.maxkey.entity.history.HistoryLogin;
public interface SessionManager {
public void create(String sessionId, Session session);
public void create(String sessionId, Session session);
public Session remove(String sessionId);

View File

@ -24,133 +24,133 @@ import org.dromara.maxkey.entity.apps.AppsCasDetails;
public class VisitedDto implements Serializable{
/**
*
*/
private static final long serialVersionUID = -6694914707659511202L;
/**
*
*/
private static final long serialVersionUID = -6694914707659511202L;
/**
* appId or client id
*/
String appId;
/**
* protocol
*/
String protocol;
/**
* ticket
*/
String ticket;
/**
* token
*/
String token;
/**
* refreshToken
*/
String refreshToken;
/**
* logoutType
*/
int logoutType;
/**
* logoutUrl
*/
String logoutUrl;
public VisitedDto(AppsCasDetails app,String ticket ) {
this.appId = app.getId();
this.protocol = app.getProtocol();
this.logoutType = app.getLogoutType();
this.logoutUrl = app.getLogoutUrl();
this.ticket = ticket;
}
public VisitedDto(Apps app,String ticket ) {
this.appId = app.getId();
this.protocol = app.getProtocol();
this.logoutType = app.getLogoutType();
this.logoutUrl = app.getLogoutUrl();
this.ticket = ticket;
}
/**
* appId or client id
*/
String appId;
/**
* protocol
*/
String protocol;
/**
* ticket
*/
String ticket;
/**
* token
*/
String token;
/**
* refreshToken
*/
String refreshToken;
/**
* logoutType
*/
int logoutType;
/**
* logoutUrl
*/
String logoutUrl;
public VisitedDto(AppsCasDetails app,String ticket ) {
this.appId = app.getId();
this.protocol = app.getProtocol();
this.logoutType = app.getLogoutType();
this.logoutUrl = app.getLogoutUrl();
this.ticket = ticket;
}
public VisitedDto(Apps app,String ticket ) {
this.appId = app.getId();
this.protocol = app.getProtocol();
this.logoutType = app.getLogoutType();
this.logoutUrl = app.getLogoutUrl();
this.ticket = ticket;
}
public String getAppId() {
return appId;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getProtocol() {
return protocol;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public String getTicket() {
return ticket;
}
public String getTicket() {
return ticket;
}
public void setTicket(String ticket) {
this.ticket = ticket;
}
public void setTicket(String ticket) {
this.ticket = ticket;
}
public String getToken() {
return token;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public void setToken(String token) {
this.token = token;
}
public String getRefreshToken() {
return refreshToken;
}
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
public int getLogoutType() {
return logoutType;
}
public int getLogoutType() {
return logoutType;
}
public void setLogoutType(int logoutType) {
this.logoutType = logoutType;
}
public void setLogoutType(int logoutType) {
this.logoutType = logoutType;
}
public String getLogoutUrl() {
return logoutUrl;
}
public String getLogoutUrl() {
return logoutUrl;
}
public void setLogoutUrl(String logoutUrl) {
this.logoutUrl = logoutUrl;
}
public void setLogoutUrl(String logoutUrl) {
this.logoutUrl = logoutUrl;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("VisitedDto [appId=");
builder.append(appId);
builder.append(", protocol=");
builder.append(protocol);
builder.append(", ticket=");
builder.append(ticket);
builder.append(", token=");
builder.append(token);
builder.append(", refreshToken=");
builder.append(refreshToken);
builder.append(", logoutType=");
builder.append(logoutType);
builder.append(", logoutUrl=");
builder.append(logoutUrl);
builder.append("]");
return builder.toString();
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("VisitedDto [appId=");
builder.append(appId);
builder.append(", protocol=");
builder.append(protocol);
builder.append(", ticket=");
builder.append(ticket);
builder.append(", token=");
builder.append(token);
builder.append(", refreshToken=");
builder.append(refreshToken);
builder.append(", logoutType=");
builder.append(logoutType);
builder.append(", logoutUrl=");
builder.append(logoutUrl);
builder.append("]");
return builder.toString();
}
}

View File

@ -35,14 +35,14 @@ import com.github.benmanes.caffeine.cache.Caffeine;
public class InMemorySessionManager implements SessionManager{
private static final Logger _logger = LoggerFactory.getLogger(InMemorySessionManager.class);
static final long CACHE_MAXIMUM_SIZE = 2000000;
protected int validitySeconds = 60 * 30; //default 30 minutes.
static final long CACHE_MAXIMUM_SIZE = 2000000;
protected int validitySeconds = 60 * 30; //default 30 minutes.
Cache<String, Session> sessionStore;
Cache<String, Session> sessionTwoFactorStore;
public InMemorySessionManager(int validitySeconds) {
Cache<String, Session> sessionStore;
Cache<String, Session> sessionTwoFactorStore;
public InMemorySessionManager(int validitySeconds) {
super();
this.validitySeconds = validitySeconds;
if(validitySeconds > 0) {
@ -52,30 +52,30 @@ public class InMemorySessionManager implements SessionManager{
.maximumSize(CACHE_MAXIMUM_SIZE)
.build();
}else {
sessionStore = Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.maximumSize(CACHE_MAXIMUM_SIZE)
.build();
sessionStore = Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.maximumSize(CACHE_MAXIMUM_SIZE)
.build();
}
sessionTwoFactorStore = Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.maximumSize(CACHE_MAXIMUM_SIZE)
.build();
.expireAfterWrite(10, TimeUnit.MINUTES)
.maximumSize(CACHE_MAXIMUM_SIZE)
.build();
}
@Override
public void create(String sessionId, Session session) {
session.setExpiredTime(session.getLastAccessTime().plusSeconds(validitySeconds));
sessionStore.put(sessionId, session);
}
public void create(String sessionId, Session session) {
session.setExpiredTime(session.getLastAccessTime().plusSeconds(validitySeconds));
sessionStore.put(sessionId, session);
}
@Override
public Session remove(String sessionId) {
Session session = sessionStore.getIfPresent(sessionId);
sessionStore.invalidate(sessionId);
return session;
}
@Override
public Session remove(String sessionId) {
Session session = sessionStore.getIfPresent(sessionId);
sessionStore.invalidate(sessionId);
return session;
}
@Override
public Session get(String sessionId) {
@ -87,10 +87,10 @@ public class InMemorySessionManager implements SessionManager{
public Session refresh(String sessionId,LocalDateTime refreshTime) {
Session session = get(sessionId);
if(session != null) {
_logger.debug("refresh session Id {} at refreshTime {}",sessionId,refreshTime);
session.setLastAccessTime(refreshTime);
//put new session
create(sessionId , session);
_logger.debug("refresh session Id {} at refreshTime {}",sessionId,refreshTime);
session.setLastAccessTime(refreshTime);
//put new session
create(sessionId , session);
}
return session;
}
@ -100,60 +100,60 @@ public class InMemorySessionManager implements SessionManager{
Session session = get(sessionId);
if(session != null) {
LocalDateTime currentTime = LocalDateTime.now();
_logger.debug("refresh session Id {} at time {}",sessionId,currentTime);
session.setLastAccessTime(currentTime);
//sessionId then renew one
create(sessionId , session);
LocalDateTime currentTime = LocalDateTime.now();
_logger.debug("refresh session Id {} at time {}",sessionId,currentTime);
session.setLastAccessTime(currentTime);
//sessionId then renew one
create(sessionId , session);
}
return session;
}
@Override
public int getValiditySeconds() {
return validitySeconds;
}
public int getValiditySeconds() {
return validitySeconds;
}
@Override
public List<HistoryLogin> querySessions(Integer category) {
// not need implement
return null;
}
@Override
public List<HistoryLogin> querySessions(Integer category) {
// not need implement
return null;
}
@Override
public void terminate(String sessionId, String userId, String username) {
// not need implement
}
@Override
public void terminate(String sessionId, String userId, String username) {
// not need implement
}
@Override
public void visited(String sessionId, VisitedDto visited) {
Session session = this.get(sessionId);
if(session != null) {
//set token or ticket to Visited , bind user session
session.visited(visited);
//override the session
this.create(sessionId, session);
_logger.debug("session {} store visited {} ." , sessionId , visited);
}
}
@Override
public void createTwoFactor(String sessionId, Session session) {
session.setExpiredTime(session.getLastAccessTime().plusSeconds(validitySeconds));
sessionTwoFactorStore.put(sessionId, session);
}
@Override
public void visited(String sessionId, VisitedDto visited) {
Session session = this.get(sessionId);
if(session != null) {
//set token or ticket to Visited , bind user session
session.visited(visited);
//override the session
this.create(sessionId, session);
_logger.debug("session {} store visited {} ." , sessionId , visited);
}
}
@Override
public void createTwoFactor(String sessionId, Session session) {
session.setExpiredTime(session.getLastAccessTime().plusSeconds(validitySeconds));
sessionTwoFactorStore.put(sessionId, session);
}
@Override
public Session removeTwoFactor(String sessionId) {
Session session = sessionTwoFactorStore.getIfPresent(sessionId);
sessionTwoFactorStore.invalidate(sessionId);
return session;
}
@Override
public Session removeTwoFactor(String sessionId) {
Session session = sessionTwoFactorStore.getIfPresent(sessionId);
sessionTwoFactorStore.invalidate(sessionId);
return session;
}
@Override
public Session getTwoFactor(String sessionId) {
Session session = sessionTwoFactorStore.getIfPresent(sessionId);
return session;
}
@Override
public Session getTwoFactor(String sessionId) {
Session session = sessionTwoFactorStore.getIfPresent(sessionId);
return session;
}
}

View File

@ -32,65 +32,65 @@ import org.slf4j.LoggerFactory;
public class RedisSessionManager implements SessionManager {
private static final Logger _logger = LoggerFactory.getLogger(RedisSessionManager.class);
protected int validitySeconds = 60 * 30; //default 30 minutes.
int twoFactorValidity = 10 * 60; //default 10 minutes.
int twoFactorValidity = 10 * 60; //default 10 minutes.
RedisConnectionFactory connectionFactory;
public static final String PREFIX = "MXK_SESSION_";
public static final String PREFIX_TWOFACTOR = "mxk:session:twofactor:%s";
public String getKey(String sessionId) {
return PREFIX + sessionId;
}
/**
* @param connectionFactory
*/
public RedisSessionManager(
RedisConnectionFactory connectionFactory,
int validitySeconds) {
super();
this.connectionFactory = connectionFactory;
this.validitySeconds = validitySeconds;
}
/**
*
*/
public RedisSessionManager() {
}
RedisConnectionFactory connectionFactory;
public static final String PREFIX = "MXK_SESSION_";
public static final String PREFIX_TWOFACTOR = "mxk:session:twofactor:%s";
public String getKey(String sessionId) {
return PREFIX + sessionId;
}
/**
* @param connectionFactory
*/
public RedisSessionManager(
RedisConnectionFactory connectionFactory,
int validitySeconds) {
super();
this.connectionFactory = connectionFactory;
this.validitySeconds = validitySeconds;
}
/**
*
*/
public RedisSessionManager() {
}
public void setConnectionFactory(RedisConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
public void setConnectionFactory(RedisConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
@Override
public void create(String sessionId, Session session) {
_logger.debug("store session key {} .",sessionId);
session.setExpiredTime(session.getLastAccessTime().plusSeconds(validitySeconds));
RedisConnection conn = connectionFactory.getConnection();
_logger.trace("store session {} ...",sessionId);
conn.setexObject( getKey(sessionId), validitySeconds, session);
_logger.debug("store session {} successful .",sessionId);
_logger.trace("close conn ...");
conn.close();
_logger.trace("close conn successful .");
}
@Override
public void create(String sessionId, Session session) {
_logger.debug("store session key {} .",sessionId);
session.setExpiredTime(session.getLastAccessTime().plusSeconds(validitySeconds));
RedisConnection conn = connectionFactory.getConnection();
_logger.trace("store session {} ...",sessionId);
conn.setexObject( getKey(sessionId), validitySeconds, session);
_logger.debug("store session {} successful .",sessionId);
_logger.trace("close conn ...");
conn.close();
_logger.trace("close conn successful .");
}
@Override
public Session remove(String sessionId) {
RedisConnection conn=connectionFactory.getConnection();
Session ticket = conn.getObject(getKey(sessionId));
conn.delete(getKey(sessionId));
conn.close();
return ticket;
}
@Override
public Session remove(String sessionId) {
RedisConnection conn=connectionFactory.getConnection();
Session ticket = conn.getObject(getKey(sessionId));
conn.delete(getKey(sessionId));
conn.close();
return ticket;
}
@Override
public Session get(String sessionId) {
@ -102,20 +102,20 @@ public class RedisSessionManager implements SessionManager {
@Override
public int getValiditySeconds() {
return validitySeconds;
}
return validitySeconds;
}
public void setValiditySeconds(int validitySeconds) {
this.validitySeconds = validitySeconds;
}
public void setValiditySeconds(int validitySeconds) {
this.validitySeconds = validitySeconds;
}
@Override
@Override
public Session refresh(String sessionId,LocalDateTime refreshTime) {
Session session = get(sessionId);
if(session != null) {
_logger.debug("refresh session Id {} at {}",sessionId,refreshTime);
session.setLastAccessTime(refreshTime);
create(sessionId , session);
_logger.debug("refresh session Id {} at {}",sessionId,refreshTime);
session.setLastAccessTime(refreshTime);
create(sessionId , session);
}
return session;
}
@ -124,65 +124,65 @@ public class RedisSessionManager implements SessionManager {
public Session refresh(String sessionId) {
Session session = get(sessionId);
if(session != null) {
LocalDateTime currentTime = LocalDateTime.now();
_logger.debug("refresh session Id {} at time {}",sessionId,currentTime);
session.setLastAccessTime(currentTime);
create(sessionId , session);
LocalDateTime currentTime = LocalDateTime.now();
_logger.debug("refresh session Id {} at time {}",sessionId,currentTime);
session.setLastAccessTime(currentTime);
create(sessionId , session);
}
return session;
}
@Override
public List<HistoryLogin> querySessions(Integer category) {
// not need implement
return null;
}
@Override
public List<HistoryLogin> querySessions(Integer category) {
// not need implement
return null;
}
@Override
public void terminate(String sessionId, String userId, String username) {
// not need implement
}
@Override
public void terminate(String sessionId, String userId, String username) {
// not need implement
}
@Override
public void visited(String sessionId, VisitedDto visited) {
Session session = this.get(sessionId);
if(session != null) {
//set token or ticket to Visited , bind user session
session.visited(visited);
//override the session
this.create(sessionId, session);
_logger.debug("session {} store visited {} ." , sessionId , visited);
}
}
public String formatTwoFactorKey(String sessionId) {
return PREFIX_TWOFACTOR.formatted(sessionId) ;
}
@Override
public void createTwoFactor(String sessionId, Session session) {
session.setExpiredTime(session.getLastAccessTime().plusSeconds(validitySeconds));
RedisConnection conn = connectionFactory.getConnection();
conn.setexObject( formatTwoFactorKey(sessionId), twoFactorValidity, session);
conn.close();
}
@Override
public void visited(String sessionId, VisitedDto visited) {
Session session = this.get(sessionId);
if(session != null) {
//set token or ticket to Visited , bind user session
session.visited(visited);
//override the session
this.create(sessionId, session);
_logger.debug("session {} store visited {} ." , sessionId , visited);
}
}
public String formatTwoFactorKey(String sessionId) {
return PREFIX_TWOFACTOR.formatted(sessionId) ;
}
@Override
public void createTwoFactor(String sessionId, Session session) {
session.setExpiredTime(session.getLastAccessTime().plusSeconds(validitySeconds));
RedisConnection conn = connectionFactory.getConnection();
conn.setexObject( formatTwoFactorKey(sessionId), twoFactorValidity, session);
conn.close();
}
@Override
public Session removeTwoFactor(String sessionId) {
RedisConnection conn = connectionFactory.getConnection();
Session ticket = conn.getObject(formatTwoFactorKey(sessionId));
conn.delete(formatTwoFactorKey(sessionId));
conn.close();
return ticket;
}
@Override
public Session removeTwoFactor(String sessionId) {
RedisConnection conn = connectionFactory.getConnection();
Session ticket = conn.getObject(formatTwoFactorKey(sessionId));
conn.delete(formatTwoFactorKey(sessionId));
conn.close();
return ticket;
}
@Override
public Session getTwoFactor(String sessionId) {
RedisConnection conn = connectionFactory.getConnection();
@Override
public Session getTwoFactor(String sessionId) {
RedisConnection conn = connectionFactory.getConnection();
Session session = conn.getObject(formatTwoFactorKey(sessionId));
conn.close();
return session;
}
}
}

View File

@ -46,122 +46,122 @@ import org.springframework.jdbc.core.RowMapper;
*
*/
public class SessionManagerImpl implements SessionManager{
private static final Logger _logger = LoggerFactory.getLogger(SessionManagerImpl.class);
private static final String DEFAULT_DEFAULT_SELECT_STATEMENT =
"select id,sessionid,userId,username,displayname,logintime from mxk_history_login where sessionstatus = 1";
private static final Logger _logger = LoggerFactory.getLogger(SessionManagerImpl.class);
private static final String DEFAULT_DEFAULT_SELECT_STATEMENT =
"select id,sessionid,userId,username,displayname,logintime from mxk_history_login where sessionstatus = 1";
private static final String LOGOUT_USERINFO_UPDATE_STATEMENT =
"update mxk_userinfo set lastlogofftime = ? , online = " + UserInfo.ONLINE.OFFLINE + " where id = ?";
"update mxk_userinfo set lastlogofftime = ? , online = " + UserInfo.ONLINE.OFFLINE + " where id = ?";
private static final String HISTORY_LOGOUT_UPDATE_STATEMENT =
"update mxk_history_login set logouttime = ? ,sessionstatus = 7 where sessionid = ?";
"update mxk_history_login set logouttime = ? ,sessionstatus = 7 where sessionid = ?";
private static final String NO_SESSION_UPDATE_STATEMENT =
"update mxk_history_login set sessionstatus = 7 where sessionstatus = 1 and (sessionid is null or sessionid = '')";
"update mxk_history_login set sessionstatus = 7 where sessionstatus = 1 and (sessionid is null or sessionid = '')";
private JdbcTemplate jdbcTemplate;
private InMemorySessionManager inMemorySessionManager;
private RedisSessionManager redisSessionManager;
private boolean isRedis = false;
private int validitySeconds ;
public SessionManagerImpl(int persistence,
JdbcTemplate jdbcTemplate,
RedisConnectionFactory redisConnFactory,
int validitySeconds) {
this.validitySeconds = validitySeconds;
this.jdbcTemplate = jdbcTemplate;
this.inMemorySessionManager =
new InMemorySessionManager(validitySeconds);
_logger.debug("InMemorySessionManager");
if (persistence == ConstsPersistence.REDIS) {
isRedis = true;
this.redisSessionManager =
new RedisSessionManager(redisConnFactory,validitySeconds);
_logger.debug("RedisSessionManager");
}
}
private InMemorySessionManager inMemorySessionManager;
private RedisSessionManager redisSessionManager;
private boolean isRedis = false;
private int validitySeconds ;
public SessionManagerImpl(int persistence,
JdbcTemplate jdbcTemplate,
RedisConnectionFactory redisConnFactory,
int validitySeconds) {
this.validitySeconds = validitySeconds;
this.jdbcTemplate = jdbcTemplate;
this.inMemorySessionManager =
new InMemorySessionManager(validitySeconds);
_logger.debug("InMemorySessionManager");
if (persistence == ConstsPersistence.REDIS) {
isRedis = true;
this.redisSessionManager =
new RedisSessionManager(redisConnFactory,validitySeconds);
_logger.debug("RedisSessionManager");
}
}
@Override
public void create(String sessionId, Session session) {
inMemorySessionManager.create(sessionId, session);
if(isRedis) {
redisSessionManager.create(sessionId, session);
}
}
@Override
public void create(String sessionId, Session session) {
inMemorySessionManager.create(sessionId, session);
if(isRedis) {
redisSessionManager.create(sessionId, session);
}
}
@Override
public Session remove(String sessionId) {
Session session = inMemorySessionManager.remove(sessionId);
if(isRedis) {
session = redisSessionManager.remove(sessionId);
}
return session;
}
@Override
public Session remove(String sessionId) {
Session session = inMemorySessionManager.remove(sessionId);
if(isRedis) {
session = redisSessionManager.remove(sessionId);
}
return session;
}
@Override
public Session get(String sessionId) {
Session session = inMemorySessionManager.get(sessionId);
if(session == null && isRedis) {
session = redisSessionManager.get(sessionId);
}
return session;
}
@Override
public Session get(String sessionId) {
Session session = inMemorySessionManager.get(sessionId);
if(session == null && isRedis) {
session = redisSessionManager.get(sessionId);
}
return session;
}
@Override
public Session refresh(String sessionId, LocalDateTime refreshTime) {
Session session = null;
if(isRedis) {
session = redisSessionManager.refresh(sessionId,refreshTime);
//renew one in Memory
inMemorySessionManager.create(sessionId, session);
}else {
session = inMemorySessionManager.refresh(sessionId,refreshTime);
}
return session;
}
@Override
public Session refresh(String sessionId, LocalDateTime refreshTime) {
Session session = null;
if(isRedis) {
session = redisSessionManager.refresh(sessionId,refreshTime);
//renew one in Memory
inMemorySessionManager.create(sessionId, session);
}else {
session = inMemorySessionManager.refresh(sessionId,refreshTime);
}
return session;
}
@Override
public Session refresh(String sessionId) {
Session session = null;
if(isRedis) {
session = redisSessionManager.refresh(sessionId);
//renew one
inMemorySessionManager.remove(sessionId);
inMemorySessionManager.create(sessionId, session);
}else {
session = inMemorySessionManager.refresh(sessionId);
}
return session;
}
@Override
public Session refresh(String sessionId) {
Session session = null;
if(isRedis) {
session = redisSessionManager.refresh(sessionId);
//renew one
inMemorySessionManager.remove(sessionId);
inMemorySessionManager.create(sessionId, session);
}else {
session = inMemorySessionManager.refresh(sessionId);
}
return session;
}
@Override
public List<HistoryLogin> querySessions(Integer category) {
//clear session id is null
jdbcTemplate.execute(NO_SESSION_UPDATE_STATEMENT);
String sessionSql = DEFAULT_DEFAULT_SELECT_STATEMENT;
if(!isRedis) {
sessionSql = sessionSql + " and category = " + category;
}
_logger.trace("sessionSql {} " ,sessionSql);
//query on line session
List<HistoryLogin> listSessions = jdbcTemplate.query(
sessionSql,
new OnlineTicketRowMapper());
return listSessions;
}
@Override
public List<HistoryLogin> querySessions(Integer category) {
//clear session id is null
jdbcTemplate.execute(NO_SESSION_UPDATE_STATEMENT);
String sessionSql = DEFAULT_DEFAULT_SELECT_STATEMENT;
if(!isRedis) {
sessionSql = sessionSql + " and category = " + category;
}
_logger.trace("sessionSql {} " ,sessionSql);
//query on line session
List<HistoryLogin> listSessions = jdbcTemplate.query(
sessionSql,
new OnlineTicketRowMapper());
return listSessions;
}
private void profileLastLogoffTime(String userId,String lastLogoffTime) {
_logger.trace("userId {} , lastlogofftime {}" ,userId, lastLogoffTime);
jdbcTemplate.update( LOGOUT_USERINFO_UPDATE_STATEMENT,
new Object[] { lastLogoffTime, userId },
new int[] { Types.TIMESTAMP, Types.VARCHAR });
jdbcTemplate.update( LOGOUT_USERINFO_UPDATE_STATEMENT,
new Object[] { lastLogoffTime, userId },
new int[] { Types.TIMESTAMP, Types.VARCHAR });
}
private void sessionLogoff(String sessionId,String lastLogoffTime) {
@ -172,70 +172,70 @@ public class SessionManagerImpl implements SessionManager{
}
@Override
public void terminate(String sessionId, String userId, String username) {
String lastLogoffTime = DateUtils.formatDateTime(new Date());
_logger.trace("{} user {} terminate session {} ." ,lastLogoffTime,username, sessionId);
this.profileLastLogoffTime(userId, lastLogoffTime);
this.sessionLogoff(sessionId, lastLogoffTime);
this.remove(sessionId);
}
public void terminate(String sessionId, String userId, String username) {
String lastLogoffTime = DateUtils.formatDateTime(new Date());
_logger.trace("{} user {} terminate session {} ." ,lastLogoffTime,username, sessionId);
this.profileLastLogoffTime(userId, lastLogoffTime);
this.sessionLogoff(sessionId, lastLogoffTime);
this.remove(sessionId);
}
@Override
public int getValiditySeconds() {
return validitySeconds;
}
private final class OnlineTicketRowMapper implements RowMapper<HistoryLogin> {
@Override
public HistoryLogin mapRow(ResultSet rs, int rowNum)
throws SQLException {
HistoryLogin history=new HistoryLogin();
history.setId(rs.getString(1));
history.setSessionId(rs.getString(2));
history.setUserId(rs.getString(3));
history.setUsername(rs.getString(4));
history.setDisplayName(rs.getString(5));
history.setLoginTime(rs.getTimestamp(6));
return history;
}
}
public int getValiditySeconds() {
return validitySeconds;
}
private final class OnlineTicketRowMapper implements RowMapper<HistoryLogin> {
@Override
public HistoryLogin mapRow(ResultSet rs, int rowNum)
throws SQLException {
HistoryLogin history=new HistoryLogin();
history.setId(rs.getString(1));
history.setSessionId(rs.getString(2));
history.setUserId(rs.getString(3));
history.setUsername(rs.getString(4));
history.setDisplayName(rs.getString(5));
history.setLoginTime(rs.getTimestamp(6));
return history;
}
}
@Override
public void visited(String sessionId, VisitedDto visited) {
@Override
public void visited(String sessionId, VisitedDto visited) {
inMemorySessionManager.visited(sessionId,visited);
if(isRedis) {
redisSessionManager.visited(sessionId,visited);
}
}
@Override
public void createTwoFactor(String sessionId, Session session) {
if(isRedis) {
redisSessionManager.createTwoFactor(sessionId, session);
}else {
inMemorySessionManager.createTwoFactor(sessionId, session);
}
}
if(isRedis) {
redisSessionManager.visited(sessionId,visited);
}
}
@Override
public void createTwoFactor(String sessionId, Session session) {
if(isRedis) {
redisSessionManager.createTwoFactor(sessionId, session);
}else {
inMemorySessionManager.createTwoFactor(sessionId, session);
}
}
@Override
public Session removeTwoFactor(String sessionId) {
Session session = null;
if(isRedis) {
session = redisSessionManager.removeTwoFactor(sessionId);
}else {
session = inMemorySessionManager.removeTwoFactor(sessionId);
}
return session;
}
@Override
public Session removeTwoFactor(String sessionId) {
Session session = null;
if(isRedis) {
session = redisSessionManager.removeTwoFactor(sessionId);
}else {
session = inMemorySessionManager.removeTwoFactor(sessionId);
}
return session;
}
@Override
public Session getTwoFactor(String sessionId) {
Session session = null;
if(isRedis) {
session = redisSessionManager.getTwoFactor(sessionId);
}else {
session = inMemorySessionManager.getTwoFactor(sessionId);
}
return session;
}
@Override
public Session getTwoFactor(String sessionId) {
Session session = null;
if(isRedis) {
session = redisSessionManager.getTwoFactor(sessionId);
}else {
session = inMemorySessionManager.getTwoFactor(sessionId);
}
return session;
}
}

View File

@ -40,47 +40,47 @@ import jakarta.servlet.http.HttpServletRequest;
@RestController
@RequestMapping(value = "/auth")
public class AuthTokenRefreshPoint {
private static final Logger _logger = LoggerFactory.getLogger(AuthTokenRefreshPoint.class);
@Autowired
AuthTokenService authTokenService;
@Autowired
AuthRefreshTokenService refreshTokenService;
@Autowired
SessionManager sessionManager;
@GetMapping(value={"/token/refresh"})
public ResponseEntity<?> refreshGet(HttpServletRequest request,
@RequestParam(name = "refresh_token", required = false) String refreshToken) {
return refresh(request,refreshToken);
}
@PostMapping(value={"/token/refresh"})
public ResponseEntity<?> refresh(HttpServletRequest request,
@RequestParam(name = "refresh_token", required = false) String refreshToken) {
_logger.debug("try to refresh token " );
_logger.trace("refresh token {} " , refreshToken);
if(_logger.isTraceEnabled()) {WebContext.printRequest(request);}
try {
if(refreshTokenService.validateJwtToken(refreshToken)) {
String sessionId = refreshTokenService.resolveJWTID(refreshToken);
_logger.trace("Try to refresh sessionId [{}]" , sessionId);
Session session = sessionManager.refresh(sessionId);
if(session != null) {
AuthJwt authJwt = authTokenService.genAuthJwt(session.getAuthentication());
_logger.trace("Grant new token {}" , authJwt);
return new Message<AuthJwt>(authJwt).buildResponse();
}else {
_logger.debug("Session is timeout , sessionId [{}]" , sessionId);
}
}else {
_logger.debug("refresh token is not validate .");
}
}catch(Exception e) {
_logger.error("Refresh Exception !",e);
}
return new ResponseEntity<>("Refresh Token Fail !", HttpStatus.UNAUTHORIZED);
}
private static final Logger _logger = LoggerFactory.getLogger(AuthTokenRefreshPoint.class);
@Autowired
AuthTokenService authTokenService;
@Autowired
AuthRefreshTokenService refreshTokenService;
@Autowired
SessionManager sessionManager;
@GetMapping(value={"/token/refresh"})
public ResponseEntity<?> refreshGet(HttpServletRequest request,
@RequestParam(name = "refresh_token", required = false) String refreshToken) {
return refresh(request,refreshToken);
}
@PostMapping(value={"/token/refresh"})
public ResponseEntity<?> refresh(HttpServletRequest request,
@RequestParam(name = "refresh_token", required = false) String refreshToken) {
_logger.debug("try to refresh token " );
_logger.trace("refresh token {} " , refreshToken);
if(_logger.isTraceEnabled()) {WebContext.printRequest(request);}
try {
if(refreshTokenService.validateJwtToken(refreshToken)) {
String sessionId = refreshTokenService.resolveJWTID(refreshToken);
_logger.trace("Try to refresh sessionId [{}]" , sessionId);
Session session = sessionManager.refresh(sessionId);
if(session != null) {
AuthJwt authJwt = authTokenService.genAuthJwt(session.getAuthentication());
_logger.trace("Grant new token {}" , authJwt);
return new Message<AuthJwt>(authJwt).buildResponse();
}else {
_logger.debug("Session is timeout , sessionId [{}]" , sessionId);
}
}else {
_logger.debug("refresh token is not validate .");
}
}catch(Exception e) {
_logger.error("Refresh Exception !",e);
}
return new ResponseEntity<>("Refresh Token Fail !", HttpStatus.UNAUTHORIZED);
}
}

View File

@ -37,125 +37,125 @@ import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
public class AuthorizationUtils {
private static final Logger _logger = LoggerFactory.getLogger(AuthorizationUtils.class);
private static final Logger _logger = LoggerFactory.getLogger(AuthorizationUtils.class);
public static final class BEARERTYPE{
public static final class BEARERTYPE{
public static final String CONGRESS = "congress";
public static final String CONGRESS = "congress";
public static final String AUTHORIZATION = "Authorization";
}
public static final String AUTHORIZATION = "Authorization";
}
public static void authenticateWithCookie(
HttpServletRequest request,
AuthTokenService authTokenService,
SessionManager sessionManager
) throws ParseException{
Cookie authCookie = WebContext.getCookie(request, BEARERTYPE.CONGRESS);
if(authCookie != null ) {
String authorization = authCookie.getValue();
_logger.trace("Try congress authenticate .");
doJwtAuthenticate(BEARERTYPE.CONGRESS,authorization,authTokenService,sessionManager);
}else {
_logger.debug("cookie is null , clear authentication .");
clearAuthentication();
}
}
public static void authenticateWithCookie(
HttpServletRequest request,
AuthTokenService authTokenService,
SessionManager sessionManager
) throws ParseException{
Cookie authCookie = WebContext.getCookie(request, BEARERTYPE.CONGRESS);
if(authCookie != null ) {
String authorization = authCookie.getValue();
_logger.trace("Try congress authenticate .");
doJwtAuthenticate(BEARERTYPE.CONGRESS,authorization,authTokenService,sessionManager);
}else {
_logger.debug("cookie is null , clear authentication .");
clearAuthentication();
}
}
public static void authenticate(
HttpServletRequest request,
AuthTokenService authTokenService,
SessionManager sessionManager
) throws ParseException{
String authorization = AuthorizationHeaderUtils.resolveBearer(request);
if(authorization != null ) {
_logger.trace("Try Authorization authenticate .");
doJwtAuthenticate(BEARERTYPE.AUTHORIZATION,authorization,authTokenService,sessionManager);
}
public static void authenticate(
HttpServletRequest request,
AuthTokenService authTokenService,
SessionManager sessionManager
) throws ParseException{
String authorization = AuthorizationHeaderUtils.resolveBearer(request);
if(authorization != null ) {
_logger.trace("Try Authorization authenticate .");
doJwtAuthenticate(BEARERTYPE.AUTHORIZATION,authorization,authTokenService,sessionManager);
}
}
}
public static void doJwtAuthenticate(
String bearerType,
String authorization,
AuthTokenService authTokenService,
SessionManager sessionManager) throws ParseException {
if(authTokenService.validateJwtToken(authorization)) {
if(isNotAuthenticated()) {
String sessionId = authTokenService.resolveJWTID(authorization);
Session session = sessionManager.get(sessionId);
if(session != null) {
setAuthentication(session.getAuthentication());
_logger.debug("{} Automatic authenticated .",bearerType);
}else {
//time out
_logger.debug("Session timeout .");
clearAuthentication();
}
}
}else {
//token invalidate
_logger.debug("Token invalidate .");
clearAuthentication();
}
}
public static void doJwtAuthenticate(
String bearerType,
String authorization,
AuthTokenService authTokenService,
SessionManager sessionManager) throws ParseException {
if(authTokenService.validateJwtToken(authorization)) {
if(isNotAuthenticated()) {
String sessionId = authTokenService.resolveJWTID(authorization);
Session session = sessionManager.get(sessionId);
if(session != null) {
setAuthentication(session.getAuthentication());
_logger.debug("{} Automatic authenticated .",bearerType);
}else {
//time out
_logger.debug("Session timeout .");
clearAuthentication();
}
}
}else {
//token invalidate
_logger.debug("Token invalidate .");
clearAuthentication();
}
}
public static Session getSession(SessionManager sessionManager, String authorization) throws ParseException {
_logger.debug("get session by authorization {}", authorization);
SignedJWT signedJWT = SignedJWT.parse(authorization);
String sessionId = signedJWT.getJWTClaimsSet().getJWTID();
_logger.debug("sessionId {}", sessionId);
return sessionManager.get(sessionId);
}
public static Session getSession(SessionManager sessionManager, String authorization) throws ParseException {
_logger.debug("get session by authorization {}", authorization);
SignedJWT signedJWT = SignedJWT.parse(authorization);
String sessionId = signedJWT.getJWTClaimsSet().getJWTID();
_logger.debug("sessionId {}", sessionId);
return sessionManager.get(sessionId);
}
public static Authentication getAuthentication() {
Authentication authentication = (Authentication) getAuthentication(WebContext.getRequest());
Authentication authentication = (Authentication) getAuthentication(WebContext.getRequest());
return authentication;
}
public static Authentication getAuthentication(HttpServletRequest request) {
Authentication authentication = (Authentication) request.getSession().getAttribute(WebConstants.AUTHENTICATION);
Authentication authentication = (Authentication) request.getSession().getAttribute(WebConstants.AUTHENTICATION);
return authentication;
}
//set Authentication to http session
public static void setAuthentication(Authentication authentication) {
WebContext.setAttribute(WebConstants.AUTHENTICATION, authentication);
WebContext.setAttribute(WebConstants.AUTHENTICATION, authentication);
}
public static void clearAuthentication() {
WebContext.removeAttribute(WebConstants.AUTHENTICATION);
WebContext.removeAttribute(WebConstants.AUTHENTICATION);
}
public static boolean isAuthenticated() {
return getAuthentication() != null;
return getAuthentication() != null;
}
public static boolean isNotAuthenticated() {
return ! isAuthenticated();
return ! isAuthenticated();
}
public static SignPrincipal getPrincipal() {
Authentication authentication = getAuthentication();
return getPrincipal(authentication);
Authentication authentication = getAuthentication();
return getPrincipal(authentication);
}
public static SignPrincipal getPrincipal(Authentication authentication) {
return authentication == null ? null : (SignPrincipal) authentication.getPrincipal();
return authentication == null ? null : (SignPrincipal) authentication.getPrincipal();
}
public static UserInfo getUserInfo(Authentication authentication) {
UserInfo userInfo = null;
SignPrincipal principal = getPrincipal(authentication);
if(principal != null ) {
userInfo = principal.getUserInfo();
UserInfo userInfo = null;
SignPrincipal principal = getPrincipal(authentication);
if(principal != null ) {
userInfo = principal.getUserInfo();
}
return userInfo;
return userInfo;
}
public static UserInfo getUserInfo() {
return getUserInfo(getAuthentication());
return getUserInfo(getAuthentication());
}
}

View File

@ -30,14 +30,14 @@ import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
Authentication authentication =
(Authentication ) webRequest.getAttribute(
WebConstants.AUTHENTICATION, RequestAttributes.SCOPE_SESSION);
UserInfo userInfo = AuthorizationUtils.getUserInfo(authentication);
if (userInfo != null) {
Authentication authentication =
(Authentication ) webRequest.getAttribute(
WebConstants.AUTHENTICATION, RequestAttributes.SCOPE_SESSION);
UserInfo userInfo = AuthorizationUtils.getUserInfo(authentication);
if (userInfo != null) {
return userInfo;
}
throw new MissingServletRequestPartException("currentUser");

View File

@ -37,37 +37,37 @@ import jakarta.servlet.http.HttpServletResponse;
@Controller
public class FileUploadEndpoint {
private static Logger _logger = LoggerFactory.getLogger(FileUploadEndpoint.class);
@Autowired
FileUploadService fileUploadService;
@PostMapping({"/file/upload/"})
@ResponseBody
public Message<Object> upload( HttpServletRequest request,
HttpServletResponse response,
@ModelAttribute FileUpload fileUpload,
@CurrentUser UserInfo currentUser){
_logger.debug("FileUpload");
fileUpload.setId(fileUpload.generateId());
fileUpload.setContentType(fileUpload.getUploadFile().getContentType());
fileUpload.setFileName(fileUpload.getUploadFile().getOriginalFilename());
fileUpload.setContentSize(fileUpload.getUploadFile().getSize());
fileUpload.setCreatedBy(currentUser.getUsername());
/*
* upload UploadFile MultipartFile to Uploaded Bytes
*/
if(null!=fileUpload.getUploadFile()&&!fileUpload.getUploadFile().isEmpty()){
try {
fileUpload.setUploaded(fileUpload.getUploadFile().getBytes());
fileUploadService.insert(fileUpload);
_logger.trace("FileUpload SUCCESS");
} catch (IOException e) {
_logger.error("FileUpload IOException",e);
}
}
return new Message<Object>(Message.SUCCESS,(Object)fileUpload.getId());
}
private static Logger _logger = LoggerFactory.getLogger(FileUploadEndpoint.class);
@Autowired
FileUploadService fileUploadService;
@PostMapping({"/file/upload/"})
@ResponseBody
public Message<Object> upload( HttpServletRequest request,
HttpServletResponse response,
@ModelAttribute FileUpload fileUpload,
@CurrentUser UserInfo currentUser){
_logger.debug("FileUpload");
fileUpload.setId(fileUpload.generateId());
fileUpload.setContentType(fileUpload.getUploadFile().getContentType());
fileUpload.setFileName(fileUpload.getUploadFile().getOriginalFilename());
fileUpload.setContentSize(fileUpload.getUploadFile().getSize());
fileUpload.setCreatedBy(currentUser.getUsername());
/*
* upload UploadFile MultipartFile to Uploaded Bytes
*/
if(null!=fileUpload.getUploadFile()&&!fileUpload.getUploadFile().isEmpty()){
try {
fileUpload.setUploaded(fileUpload.getUploadFile().getBytes());
fileUploadService.insert(fileUpload);
_logger.trace("FileUpload SUCCESS");
} catch (IOException e) {
_logger.error("FileUpload IOException",e);
}
}
return new Message<Object>(Message.SUCCESS,(Object)fileUpload.getId());
}
}

View File

@ -58,31 +58,31 @@ public class HttpSessionListenerAdapter implements HttpSessionListener {
Object principal = authentication == null ? null : authentication.getPrincipal();
_logger.trace("principal {}",principal);
if(principal != null ) {
if(principal instanceof SignPrincipal && ((SignPrincipal)principal).getUserInfo()!=null) {
SignPrincipal signPrincipal = (SignPrincipal)principal;
_logger.trace("{} HttpSession Id {} for userId {} , username {} @Ticket {} Destroyed" ,
DateUtils.formatDateTime(new Date()),
session.getId(),
signPrincipal.getUserInfo().getId(),
signPrincipal.getUserInfo().getUsername(),
signPrincipal.getSessionId());
}else if(principal instanceof User) {
User user = (User)principal;
_logger.trace("{} HttpSession Id {} for username {} password {} Destroyed" ,
DateUtils.formatDateTime(new Date()),
session.getId(),
user.getUsername(),
user.getPassword());
}else{
_logger.trace("{} HttpSession Id {} for principal {} Destroyed" ,
DateUtils.formatDateTime(new Date()),
session.getId(),
principal);
}
if(principal instanceof SignPrincipal && ((SignPrincipal)principal).getUserInfo()!=null) {
SignPrincipal signPrincipal = (SignPrincipal)principal;
_logger.trace("{} HttpSession Id {} for userId {} , username {} @Ticket {} Destroyed" ,
DateUtils.formatDateTime(new Date()),
session.getId(),
signPrincipal.getUserInfo().getId(),
signPrincipal.getUserInfo().getUsername(),
signPrincipal.getSessionId());
}else if(principal instanceof User) {
User user = (User)principal;
_logger.trace("{} HttpSession Id {} for username {} password {} Destroyed" ,
DateUtils.formatDateTime(new Date()),
session.getId(),
user.getUsername(),
user.getPassword());
}else{
_logger.trace("{} HttpSession Id {} for principal {} Destroyed" ,
DateUtils.formatDateTime(new Date()),
session.getId(),
principal);
}
}else {
_logger.trace("{} HttpSession Id {} Destroyed" ,
DateUtils.formatDateTime(new Date()),
session.getId());
_logger.trace("{} HttpSession Id {} Destroyed" ,
DateUtils.formatDateTime(new Date()),
session.getId());
}
}

View File

@ -35,45 +35,45 @@ import jakarta.servlet.http.HttpServletRequest;
@RestController
@RequestMapping(value = "/inst")
public class InstitutionEndpoint {
private static final Logger _logger = LoggerFactory.getLogger(InstitutionEndpoint.class);
public static final String HEADER_HOST = "host";
public static final String HEADER_HOSTNAME = "hostname";
@Autowired
InstitutionsService institutionsService;
@Autowired
ApplicationConfig applicationConfig;
@GetMapping(value={"/get"})
public Message<Institutions> get(
HttpServletRequest request,
@RequestHeader(value = "Origin",required=false) String originURL,
@RequestHeader(value = HEADER_HOSTNAME,required=false) String headerHostName,
@RequestHeader(value = HEADER_HOST,required=false) String headerHost) {
_logger.debug("get Institution" );
String host = headerHostName;
_logger.trace("hostname {}",host);
if(StringUtils.isEmpty(host)) {
host = headerHost;
_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 inst = institutionsService.get(host);
_logger.debug("inst {}",inst);
return new Message<>(inst);
}
private static final Logger _logger = LoggerFactory.getLogger(InstitutionEndpoint.class);
public static final String HEADER_HOST = "host";
public static final String HEADER_HOSTNAME = "hostname";
@Autowired
InstitutionsService institutionsService;
@Autowired
ApplicationConfig applicationConfig;
@GetMapping(value={"/get"})
public Message<Institutions> get(
HttpServletRequest request,
@RequestHeader(value = "Origin",required=false) String originURL,
@RequestHeader(value = HEADER_HOSTNAME,required=false) String headerHostName,
@RequestHeader(value = HEADER_HOST,required=false) String headerHost) {
_logger.debug("get Institution" );
String host = headerHostName;
_logger.trace("hostname {}",host);
if(StringUtils.isEmpty(host)) {
host = headerHost;
_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 inst = institutionsService.get(host);
_logger.debug("inst {}",inst);
return new Message<>(inst);
}
}

View File

@ -27,39 +27,39 @@ import org.springframework.stereotype.Component;
@Component
public class PersistFieldAutoFillHandler extends FieldAutoFillHandler{
@Override
public void insertFill(MetaObject metaObject) {
SignPrincipal principal = getPrincipal();
if(principal != null) {
this.setFieldValue(metaObject , "instId", principal.getInstId());
this.setFieldValue(metaObject , "createdBy", principal.getUserId());
}
this.setFieldValue(metaObject , "createdDate", new Date());
}
@Override
public void insertFill(MetaObject metaObject) {
SignPrincipal principal = getPrincipal();
if(principal != null) {
this.setFieldValue(metaObject , "instId", principal.getInstId());
this.setFieldValue(metaObject , "createdBy", principal.getUserId());
}
this.setFieldValue(metaObject , "createdDate", new Date());
}
@Override
public void updateFill(MetaObject metaObject) {
SignPrincipal principal = getPrincipal();
if(principal != null) {
this.setFieldValue(metaObject , "modifiedBy", principal.getUserId());
}
this.setFieldValue(metaObject , "modifiedDate", new Date());
}
/**
* 获取principal , 忽略异常情况
* @return
*/
SignPrincipal getPrincipal() {
SignPrincipal principal = null;
try {
principal = AuthorizationUtils.getPrincipal();
}catch(Exception e) {
//
}
return principal;
}
@Override
public void updateFill(MetaObject metaObject) {
SignPrincipal principal = getPrincipal();
if(principal != null) {
this.setFieldValue(metaObject , "modifiedBy", principal.getUserId());
}
this.setFieldValue(metaObject , "modifiedDate", new Date());
}
/**
* 获取principal , 忽略异常情况
* @return
*/
SignPrincipal getPrincipal() {
SignPrincipal principal = null;
try {
principal = AuthorizationUtils.getPrincipal();
}catch(Exception e) {
//
}
return principal;
}
}

View File

@ -59,7 +59,7 @@ public class SessionSecurityContextHolderStrategy implements SecurityContextHold
@Override
public void setContext(SecurityContext context) {
AuthorizationUtils.setAuthentication(context.getAuthentication());
AuthorizationUtils.setAuthentication(context.getAuthentication());
}
@Override

View File

@ -38,23 +38,23 @@ import jakarta.servlet.http.HttpServletResponse;
@Controller
@RequestMapping(value = "/auth")
public class UnauthorizedEntryPoint {
private static final Logger _logger = LoggerFactory.getLogger(UnauthorizedEntryPoint.class);
@RequestMapping(value={"/entrypoint"})
public void entryPoint(
HttpServletRequest request, HttpServletResponse response)
throws StreamWriteException, DatabindException, IOException {
_logger.trace("UnauthorizedEntryPoint /entrypoint.");
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
private static final Logger _logger = LoggerFactory.getLogger(UnauthorizedEntryPoint.class);
@RequestMapping(value={"/entrypoint"})
public void entryPoint(
HttpServletRequest request, HttpServletResponse response)
throws StreamWriteException, DatabindException, IOException {
_logger.trace("UnauthorizedEntryPoint /entrypoint.");
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
final Map<String, Object> responseBody = new HashMap<>();
responseBody.put("status", HttpServletResponse.SC_UNAUTHORIZED);
responseBody.put("error", "Unauthorized");
responseBody.put("message", "Unauthorized");
responseBody.put("path", request.getServletPath());
final Map<String, Object> responseBody = new HashMap<>();
responseBody.put("status", HttpServletResponse.SC_UNAUTHORIZED);
responseBody.put("error", "Unauthorized");
responseBody.put("message", "Unauthorized");
responseBody.put("path", request.getServletPath());
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(response.getOutputStream(), responseBody);
}
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(response.getOutputStream(), responseBody);
}
}

View File

@ -39,51 +39,51 @@ import jakarta.servlet.http.HttpServletResponse;
*/
@Component
public class PermissionInterceptor implements AsyncHandlerInterceptor {
private static final Logger _logger = LoggerFactory.getLogger(PermissionInterceptor.class);
//无需Interceptor url
@Autowired
ApplicationConfig applicationConfig;
@Autowired
SessionManager sessionManager;
@Autowired
AuthTokenService authTokenService ;
boolean mgmt = false;
/*
* 请求前处理
* (non-Javadoc)
* @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)
*/
@Override
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
_logger.trace("Permission Interceptor .");
AuthorizationUtils.authenticate(request, authTokenService, sessionManager);
SignPrincipal principal = AuthorizationUtils.getPrincipal();
//判断用户是否登录,判断用户是否登录用户
if(principal == null){
_logger.debug("No Authentication ... forward to /auth/entrypoint , request URI {}" , request.getRequestURI());
RequestDispatcher dispatcher = request.getRequestDispatcher("/auth/entrypoint");
dispatcher.forward(request, response);
return false;
}
//管理端必须使用管理员登录,非管理员用户直接注销
if (this.mgmt && !principal.isRoleAdministrators()) {
_logger.debug("Not ADMINISTRATORS Authentication .");
RequestDispatcher dispatcher = request.getRequestDispatcher("/auth/entrypoint");
dispatcher.forward(request, response);
return false;
}
return true;
}
private static final Logger _logger = LoggerFactory.getLogger(PermissionInterceptor.class);
//无需Interceptor url
@Autowired
ApplicationConfig applicationConfig;
@Autowired
SessionManager sessionManager;
@Autowired
AuthTokenService authTokenService ;
boolean mgmt = false;
/*
* 请求前处理
* (non-Javadoc)
* @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)
*/
@Override
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
_logger.trace("Permission Interceptor .");
AuthorizationUtils.authenticate(request, authTokenService, sessionManager);
SignPrincipal principal = AuthorizationUtils.getPrincipal();
//判断用户是否登录,判断用户是否登录用户
if(principal == null){
_logger.debug("No Authentication ... forward to /auth/entrypoint , request URI {}" , request.getRequestURI());
RequestDispatcher dispatcher = request.getRequestDispatcher("/auth/entrypoint");
dispatcher.forward(request, response);
return false;
}
//管理端必须使用管理员登录,非管理员用户直接注销
if (this.mgmt && !principal.isRoleAdministrators()) {
_logger.debug("Not ADMINISTRATORS Authentication .");
RequestDispatcher dispatcher = request.getRequestDispatcher("/auth/entrypoint");
dispatcher.forward(request, response);
return false;
}
return true;
}
public void setMgmt(boolean mgmt) {
this.mgmt = mgmt;
_logger.debug("Permission for ADMINISTRATORS {}", this.mgmt);
}
public void setMgmt(boolean mgmt) {
this.mgmt = mgmt;
_logger.debug("Permission for ADMINISTRATORS {}", this.mgmt);
}
}

View File

@ -49,9 +49,9 @@ public class SessionAutoConfiguration {
RedisConnectionFactory redisConnFactory,
@Value("${maxkey.auth.session.timeout:1800}") int timeout
) {
_logger.debug("session timeout {}" , timeout);
_logger.debug("session timeout {}" , timeout);
return new SessionManagerImpl(
persistence, jdbcTemplate, redisConnFactory,timeout);
persistence, jdbcTemplate, redisConnFactory,timeout);
}
@Bean

View File

@ -41,30 +41,30 @@ public class TokenAutoConfiguration{
@Bean
AuthTokenService authTokenService(
AuthJwkConfig authJwkConfig,
RedisConnectionFactory redisConnFactory,
MomentaryService momentaryService,
AuthRefreshTokenService refreshTokenService,
@Value("${maxkey.server.persistence}") int persistence) throws JOSEException {
CongressService congressService;
_logger.debug("cache persistence {}" , persistence);
if (persistence == ConstsPersistence.REDIS) {
congressService = new RedisCongressService(redisConnFactory);
}else {
congressService = new InMemoryCongressService();
}
return new AuthTokenService(
authJwkConfig,
congressService,
momentaryService,
refreshTokenService
);
AuthJwkConfig authJwkConfig,
RedisConnectionFactory redisConnFactory,
MomentaryService momentaryService,
AuthRefreshTokenService refreshTokenService,
@Value("${maxkey.server.persistence}") int persistence) throws JOSEException {
CongressService congressService;
_logger.debug("cache persistence {}" , persistence);
if (persistence == ConstsPersistence.REDIS) {
congressService = new RedisCongressService(redisConnFactory);
}else {
congressService = new InMemoryCongressService();
}
return new AuthTokenService(
authJwkConfig,
congressService,
momentaryService,
refreshTokenService
);
}
@Bean
AuthRefreshTokenService refreshTokenService(AuthJwkConfig authJwkConfig) throws JOSEException {
return new AuthRefreshTokenService(authJwkConfig);
return new AuthRefreshTokenService(authJwkConfig);
}
}

View File

@ -56,19 +56,19 @@ public abstract class AbstractAuthenticationProvider {
public static String PROVIDER_SUFFIX = "AuthenticationProvider";
public class AuthType{
public static final String NORMAL = "normal";
public static final String TFA = "tfa";
public static final String MOBILE = "mobile";
public static final String TRUSTED = "trusted";
public static final String NORMAL = "normal";
public static final String TFA = "tfa";
public static final String MOBILE = "mobile";
public static final String TRUSTED = "trusted";
/**
* 扫描认证
*/
public static final String SCAN_CODE = "scancode";
public static final String SCAN_CODE = "scancode";
/**
* 手机端APP
*/
public static final String APP = "app";
public static final String APP = "app";
}
protected ApplicationConfig applicationConfig;
@ -99,11 +99,11 @@ public abstract class AbstractAuthenticationProvider {
}
public Authentication authenticate(LoginCredential authentication){
return null;
return null;
}
public Authentication authenticate(LoginCredential authentication,boolean trusted) {
return null;
return null;
}
/**
@ -124,7 +124,7 @@ public abstract class AbstractAuthenticationProvider {
for(GrantedAuthority administratorsAuthority : grantedAdministratorsAuthoritys) {
if(grantedAuthoritys.contains(administratorsAuthority)) {
principal.setRoleAdministrators(true);
principal.setRoleAdministrators(true);
_logger.trace("ROLE ADMINISTRATORS Authentication .");
}
}
@ -134,7 +134,7 @@ public abstract class AbstractAuthenticationProvider {
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(
principal,
principal,
"PASSWORD",
grantedAuthoritys
);
@ -228,34 +228,34 @@ public abstract class AbstractAuthenticationProvider {
loginUser.setDisplayName("not exist");
loginUser.setLoginCount(0);
authenticationRealm.insertLoginHistory(
loginUser,
ConstsLoginType.LOCAL,
"",
i18nMessage,
WebConstants.LOGIN_RESULT.USER_NOT_EXIST);
loginUser,
ConstsLoginType.LOCAL,
"",
i18nMessage,
WebConstants.LOGIN_RESULT.USER_NOT_EXIST);
throw new BadCredentialsException(i18nMessage);
}
return true;
}
protected boolean statusValid(LoginCredential loginCredential , UserInfo userInfo) {
if(userInfo.getIsLocked()==ConstsStatus.LOCK) {
authenticationRealm.insertLoginHistory(
userInfo,
if(userInfo.getIsLocked()==ConstsStatus.LOCK) {
authenticationRealm.insertLoginHistory(
userInfo,
loginCredential.getAuthType(),
loginCredential.getProvider(),
loginCredential.getCode(),
WebConstants.LOGIN_RESULT.USER_LOCKED
);
}else if(userInfo.getStatus()!=ConstsStatus.ACTIVE) {
authenticationRealm.insertLoginHistory(
userInfo,
}else if(userInfo.getStatus()!=ConstsStatus.ACTIVE) {
authenticationRealm.insertLoginHistory(
userInfo,
loginCredential.getAuthType(),
loginCredential.getProvider(),
loginCredential.getCode(),
WebConstants.LOGIN_RESULT.USER_INACTIVE
);
}
}
return true;
}

View File

@ -26,33 +26,33 @@ public class AuthenticationProviderFactory extends AbstractAuthenticationProvide
@Override
public Authentication authenticate(LoginCredential authentication){
if(authentication.getAuthType().equalsIgnoreCase("trusted")) {
//risk remove
return null;
}
AbstractAuthenticationProvider provider = providers.get(authentication.getAuthType() + PROVIDER_SUFFIX);
return provider == null ? null : provider.doAuthenticate(authentication);
if(authentication.getAuthType().equalsIgnoreCase("trusted")) {
//risk remove
return null;
}
AbstractAuthenticationProvider provider = providers.get(authentication.getAuthType() + PROVIDER_SUFFIX);
return provider == null ? null : provider.doAuthenticate(authentication);
}
@Override
public Authentication authenticate(LoginCredential authentication,boolean trusted){
AbstractAuthenticationProvider provider = providers.get(AuthType.TRUSTED + PROVIDER_SUFFIX);
return provider.doAuthenticate(authentication);
AbstractAuthenticationProvider provider = providers.get(AuthType.TRUSTED + PROVIDER_SUFFIX);
return provider.doAuthenticate(authentication);
}
public void addAuthenticationProvider(AbstractAuthenticationProvider provider) {
providers.put(provider.getProviderName(), provider);
providers.put(provider.getProviderName(), provider);
}
@Override
public String getProviderName() {
return "AuthenticationProviderFactory";
}
@Override
public String getProviderName() {
return "AuthenticationProviderFactory";
}
@Override
public Authentication doAuthenticate(LoginCredential authentication) {
//AuthenticationProvider Factory do nothing
return null;
}
@Override
public Authentication doAuthenticate(LoginCredential authentication) {
//AuthenticationProvider Factory do nothing
return null;
}
}

View File

@ -51,65 +51,65 @@ public class NormalAuthenticationProvider extends AbstractAuthenticationProvider
public NormalAuthenticationProvider() {
super();
}
super();
}
public NormalAuthenticationProvider(
AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig,
SessionManager sessionManager,
AuthTokenService authTokenService) {
this.authenticationRealm = authenticationRealm;
this.applicationConfig = applicationConfig;
this.sessionManager = sessionManager;
this.authTokenService = authTokenService;
}
AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig,
SessionManager sessionManager,
AuthTokenService authTokenService) {
this.authenticationRealm = authenticationRealm;
this.applicationConfig = applicationConfig;
this.sessionManager = sessionManager;
this.authTokenService = authTokenService;
}
@Override
public Authentication doAuthenticate(LoginCredential loginCredential) {
UsernamePasswordAuthenticationToken authenticationToken = null;
_logger.debug("Trying to authenticate user '{}' via {}",
public Authentication doAuthenticate(LoginCredential loginCredential) {
UsernamePasswordAuthenticationToken authenticationToken = null;
_logger.debug("Trying to authenticate user '{}' via {}",
loginCredential.getPrincipal(), getProviderName());
try {
_logger.debug("authentication {}" , loginCredential);
if(this.applicationConfig.getLoginConfig().isCaptcha()) {
captchaValid(loginCredential.getState(),loginCredential.getCaptcha());
}
emptyPasswordValid(loginCredential.getPassword());
emptyUsernameValid(loginCredential.getUsername());
UserInfo userInfo = loadUserInfo(loginCredential.getUsername(),loginCredential.getPassword());
isUserExist(loginCredential , userInfo);
//Validate PasswordPolicy
authenticationRealm.getLoginService().passwordPolicyValid(userInfo);
statusValid(loginCredential , userInfo);
//Match password
authenticationRealm.passwordMatches(userInfo, loginCredential.getPassword());
_logger.debug("authentication {}" , loginCredential);
if(this.applicationConfig.getLoginConfig().isCaptcha()) {
captchaValid(loginCredential.getState(),loginCredential.getCaptcha());
}
emptyPasswordValid(loginCredential.getPassword());
emptyUsernameValid(loginCredential.getUsername());
UserInfo userInfo = loadUserInfo(loginCredential.getUsername(),loginCredential.getPassword());
isUserExist(loginCredential , userInfo);
//Validate PasswordPolicy
authenticationRealm.getLoginService().passwordPolicyValid(userInfo);
statusValid(loginCredential , userInfo);
//Match password
authenticationRealm.passwordMatches(userInfo, loginCredential.getPassword());
//apply PasswordSetType and resetBadPasswordCount
authenticationRealm.getLoginService().applyPasswordPolicy(userInfo);
authenticationToken = createOnlineTicket(loginCredential,userInfo);
// user authenticated
_logger.debug("'{}' authenticated successfully by {}.",
loginCredential.getPrincipal(), getProviderName());
authenticationRealm.insertLoginHistory(userInfo,
ConstsLoginType.LOCAL,
"",
"xe00000004",
WebConstants.LOGIN_RESULT.SUCCESS);
//apply PasswordSetType and resetBadPasswordCount
authenticationRealm.getLoginService().applyPasswordPolicy(userInfo);
authenticationToken = createOnlineTicket(loginCredential,userInfo);
// user authenticated
_logger.debug("'{}' authenticated successfully by {}.",
loginCredential.getPrincipal(), getProviderName());
authenticationRealm.insertLoginHistory(userInfo,
ConstsLoginType.LOCAL,
"",
"xe00000004",
WebConstants.LOGIN_RESULT.SUCCESS);
} catch (AuthenticationException e) {
_logger.error("Failed to authenticate user {} via {}: {}",
loginCredential.getPrincipal(),
loginCredential.getPrincipal(),
getProviderName(),
e.getMessage() );
WebContext.setAttribute(
@ -131,8 +131,8 @@ public class NormalAuthenticationProvider extends AbstractAuthenticationProvider
*/
protected void captchaValid(String state ,String captcha) {
// for basic
if(!authTokenService.validateCaptcha(state,captcha)) {
throw new BadCredentialsException(WebContext.getI18nValue("login.error.captcha"));
}
if(!authTokenService.validateCaptcha(state,captcha)) {
throw new BadCredentialsException(WebContext.getI18nValue("login.error.captcha"));
}
}
}

View File

@ -43,20 +43,20 @@ public class TrustedAuthenticationProvider extends AbstractAuthenticationProvide
}
public TrustedAuthenticationProvider() {
super();
}
super();
}
public TrustedAuthenticationProvider(
AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig,
SessionManager sessionManager) {
this.authenticationRealm = authenticationRealm;
this.applicationConfig = applicationConfig;
this.sessionManager = sessionManager;
}
AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig,
SessionManager sessionManager) {
this.authenticationRealm = authenticationRealm;
this.applicationConfig = applicationConfig;
this.sessionManager = sessionManager;
}
@Override
public Authentication doAuthenticate(LoginCredential loginCredential) {
public Authentication doAuthenticate(LoginCredential loginCredential) {
UserInfo loadeduserInfo = loadUserInfo(loginCredential.getUsername(), "");
statusValid(loginCredential , loadeduserInfo);
if (loadeduserInfo != null) {

View File

@ -127,8 +127,8 @@ public abstract class AbstractAuthenticationRealm {
historyLogin.setSessionStatus(7);
Authentication authentication = (Authentication ) WebContext.getAttribute(WebConstants.AUTHENTICATION);
if(authentication != null
&& authentication.getPrincipal() instanceof SignPrincipal) {
historyLogin.setSessionStatus(1);
&& authentication.getPrincipal() instanceof SignPrincipal) {
historyLogin.setSessionStatus(1);
historyLogin.setSessionId(userInfo.getSessionId());
}
@ -153,10 +153,10 @@ public abstract class AbstractAuthenticationRealm {
Region ipRegion =ipLocationParser.region(userInfo.getLastLoginIp());
if(ipRegion != null) {
historyLogin.setCountry(ipRegion.getCountry());
historyLogin.setProvince(ipRegion.getProvince());
historyLogin.setCity(ipRegion.getCity());
historyLogin.setLocation(ipRegion.getAddr());
historyLogin.setCountry(ipRegion.getCountry());
historyLogin.setProvince(ipRegion.getProvince());
historyLogin.setCity(ipRegion.getCity());
historyLogin.setLocation(ipRegion.getAddr());
}
historyLoginService.login(historyLogin);

View File

@ -57,40 +57,40 @@ public class JdbcAuthenticationRealm extends AbstractAuthenticationRealm {
}
public JdbcAuthenticationRealm(
PasswordEncoder passwordEncoder,
PasswordPolicyValidatorService passwordPolicyValidatorService,
LoginService loginService,
HistoryLoginService historyLoginService,
UserInfoService userInfoService,
IpLocationParser ipLocationParser,
JdbcTemplate jdbcTemplate) {
this.passwordEncoder =passwordEncoder;
this.passwordPolicyValidatorService=passwordPolicyValidatorService;
this.loginService = loginService;
this.historyLoginService = historyLoginService;
this.userInfoService = userInfoService;
this.ipLocationParser = ipLocationParser;
PasswordEncoder passwordEncoder,
PasswordPolicyValidatorService passwordPolicyValidatorService,
LoginService loginService,
HistoryLoginService historyLoginService,
UserInfoService userInfoService,
IpLocationParser ipLocationParser,
JdbcTemplate jdbcTemplate) {
this.passwordEncoder =passwordEncoder;
this.passwordPolicyValidatorService=passwordPolicyValidatorService;
this.loginService = loginService;
this.historyLoginService = historyLoginService;
this.userInfoService = userInfoService;
this.ipLocationParser = ipLocationParser;
this.jdbcTemplate = jdbcTemplate;
}
public JdbcAuthenticationRealm(
PasswordEncoder passwordEncoder,
PasswordPolicyValidatorService passwordPolicyValidatorService,
LoginService loginService,
HistoryLoginService historyLoginService,
UserInfoService userInfoService,
IpLocationParser ipLocationParser,
JdbcTemplate jdbcTemplate,
LdapAuthenticationRealmService ldapAuthenticationRealmService) {
this.passwordEncoder = passwordEncoder;
this.passwordPolicyValidatorService = passwordPolicyValidatorService;
this.loginService = loginService;
this.historyLoginService = historyLoginService;
this.userInfoService = userInfoService;
this.ipLocationParser = ipLocationParser;
this.jdbcTemplate = jdbcTemplate;
this.ldapAuthenticationRealmService = ldapAuthenticationRealmService;
PasswordEncoder passwordEncoder,
PasswordPolicyValidatorService passwordPolicyValidatorService,
LoginService loginService,
HistoryLoginService historyLoginService,
UserInfoService userInfoService,
IpLocationParser ipLocationParser,
JdbcTemplate jdbcTemplate,
LdapAuthenticationRealmService ldapAuthenticationRealmService) {
this.passwordEncoder = passwordEncoder;
this.passwordPolicyValidatorService = passwordPolicyValidatorService;
this.loginService = loginService;
this.historyLoginService = historyLoginService;
this.userInfoService = userInfoService;
this.ipLocationParser = ipLocationParser;
this.jdbcTemplate = jdbcTemplate;
this.ldapAuthenticationRealmService = ldapAuthenticationRealmService;
}
/**
@ -105,28 +105,28 @@ public class JdbcAuthenticationRealm extends AbstractAuthenticationRealm {
passwordMatches = passwordEncoder.matches(password,userInfo.getPassword());
if(ldapAuthenticationRealmService != null) {
//passwordMatches == false and ldapSupport ==true
//validate password with LDAP
try {
LdapAuthenticationRealm ldapRealm = ldapAuthenticationRealmService.getByInstId(userInfo.getInstId());
if(!passwordMatches && ldapRealm != null
&& ldapRealm.isLdapSupport()
&& userInfo.getIsLocked() == ConstsStatus.ACTIVE) {
passwordMatches = ldapRealm.passwordMatches(userInfo, password);
if(passwordMatches) {
//write password to database Realm
ChangePassword changePassword = new ChangePassword(userInfo);
changePassword.setPassword(password);
userInfoService.changePassword(changePassword, false);
}
}
}catch(Exception e) {
_logger.debug("passwordvalid Exception : {}" , e);
}
//passwordMatches == false and ldapSupport ==true
//validate password with LDAP
try {
LdapAuthenticationRealm ldapRealm = ldapAuthenticationRealmService.getByInstId(userInfo.getInstId());
if(!passwordMatches && ldapRealm != null
&& ldapRealm.isLdapSupport()
&& userInfo.getIsLocked() == ConstsStatus.ACTIVE) {
passwordMatches = ldapRealm.passwordMatches(userInfo, password);
if(passwordMatches) {
//write password to database Realm
ChangePassword changePassword = new ChangePassword(userInfo);
changePassword.setPassword(password);
userInfoService.changePassword(changePassword, false);
}
}
}catch(Exception e) {
_logger.debug("passwordvalid Exception : {}" , e);
}
}
_logger.debug("passwordvalid : {}" , passwordMatches);
if (!passwordMatches) {
loginService.plusBadPasswordCount(userInfo);
loginService.plusBadPasswordCount(userInfo);
insertLoginHistory(userInfo, ConstsLoginType.LOCAL, "", "xe00000004", WebConstants.LOGIN_RESULT.PASSWORD_ERROE);
CnfPasswordPolicy passwordPolicy = passwordPolicyValidatorService.getPasswordPolicy();
if(userInfo.getBadPasswordCount()>=(passwordPolicy.getAttempts()/2)) {

View File

@ -30,59 +30,59 @@ import org.slf4j.LoggerFactory;
*
*/
public final class ActiveDirectoryServer implements IAuthenticationServer {
private static final Logger _logger = LoggerFactory.getLogger(ActiveDirectoryServer.class);
private static final Logger _logger = LoggerFactory.getLogger(ActiveDirectoryServer.class);
ActiveDirectoryUtils activeDirectoryUtils;
ActiveDirectoryUtils activeDirectoryUtils;
String filter;
boolean mapping;
/* (non-Javadoc)
* @see com.connsec.web.authentication.realm.IAuthenticationServer#authenticate(java.lang.String, java.lang.String)
*/
@Override
public boolean authenticate(String username, String password) {
ActiveDirectoryUtils ldapPassWordValid =
new ActiveDirectoryUtils(
activeDirectoryUtils.getProviderUrl(),
username,
password,
activeDirectoryUtils.getDomain()
);
ldapPassWordValid.openConnection();
if(ldapPassWordValid.getCtx()!=null){
_logger.debug("Active Directory user " + username + " is validate .");
ldapPassWordValid.close();
return true;
}
ldapPassWordValid.close();
return false;
}
String filter;
boolean mapping;
/* (non-Javadoc)
* @see com.connsec.web.authentication.realm.IAuthenticationServer#authenticate(java.lang.String, java.lang.String)
*/
@Override
public boolean authenticate(String username, String password) {
ActiveDirectoryUtils ldapPassWordValid =
new ActiveDirectoryUtils(
activeDirectoryUtils.getProviderUrl(),
username,
password,
activeDirectoryUtils.getDomain()
);
ldapPassWordValid.openConnection();
if(ldapPassWordValid.getCtx()!=null){
_logger.debug("Active Directory user " + username + " is validate .");
ldapPassWordValid.close();
return true;
}
ldapPassWordValid.close();
return false;
}
public ActiveDirectoryUtils getActiveDirectoryUtils() {
return activeDirectoryUtils;
}
public ActiveDirectoryUtils getActiveDirectoryUtils() {
return activeDirectoryUtils;
}
public void setActiveDirectoryUtils(ActiveDirectoryUtils activeDirectoryUtils) {
this.activeDirectoryUtils = activeDirectoryUtils;
}
public void setActiveDirectoryUtils(ActiveDirectoryUtils activeDirectoryUtils) {
this.activeDirectoryUtils = activeDirectoryUtils;
}
public String getFilter() {
return filter;
}
public String getFilter() {
return filter;
}
public void setFilter(String filter) {
this.filter = filter;
}
public void setFilter(String filter) {
this.filter = filter;
}
@Override
public boolean isMapping() {
return mapping;
}
@Override
public boolean isMapping() {
return mapping;
}
public void setMapping(boolean mapping) {
this.mapping = mapping;
}
public void setMapping(boolean mapping) {
this.mapping = mapping;
}
}

View File

@ -30,65 +30,65 @@ import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
public class LdapAuthenticationRealm extends AbstractAuthenticationRealm{
private static final Logger _logger = LoggerFactory.getLogger(LdapAuthenticationRealm.class);
@NotNull
private static final Logger _logger = LoggerFactory.getLogger(LdapAuthenticationRealm.class);
@NotNull
@Size(min=1)
private List<IAuthenticationServer> ldapServers;
private boolean ldapSupport;
/**
*
*/
public LdapAuthenticationRealm() {
}
private boolean ldapSupport;
/**
*
*/
public LdapAuthenticationRealm() {
}
public LdapAuthenticationRealm(boolean ldapSupport) {
this.ldapSupport = ldapSupport;
}
/**
* @param jdbcTemplate
*/
public LdapAuthenticationRealm(JdbcTemplate jdbcTemplate) {
super(jdbcTemplate);
}
@Override
public boolean passwordMatches(UserInfo userInfo, String password) {
boolean isAuthenticated=false;
for (final IAuthenticationServer ldapServer : this.ldapServers) {
String username = userInfo.getUsername();
if(ldapServer.isMapping()) {//if ldap Context accountMapping equals YES
username = userInfo.getWindowsAccount();
}
public LdapAuthenticationRealm(boolean ldapSupport) {
this.ldapSupport = ldapSupport;
}
/**
* @param jdbcTemplate
*/
public LdapAuthenticationRealm(JdbcTemplate jdbcTemplate) {
super(jdbcTemplate);
}
@Override
public boolean passwordMatches(UserInfo userInfo, String password) {
boolean isAuthenticated=false;
for (final IAuthenticationServer ldapServer : this.ldapServers) {
String username = userInfo.getUsername();
if(ldapServer.isMapping()) {//if ldap Context accountMapping equals YES
username = userInfo.getWindowsAccount();
}
_logger.debug("Attempting to authenticate {} at {}", username, ldapServer);
try {
isAuthenticated = ldapServer.authenticate(username, password);
isAuthenticated = ldapServer.authenticate(username, password);
}catch(Exception e) {
_logger.debug("Attempting Authenticated fail .");
_logger.debug("Attempting Authenticated fail .");
}
if (isAuthenticated ) {
return true;
return true;
}
}
return false;
}
}
return false;
}
public void setLdapServers(List<IAuthenticationServer> ldapServers) {
this.ldapServers = ldapServers;
}
public void setLdapServers(List<IAuthenticationServer> ldapServers) {
this.ldapServers = ldapServers;
}
public boolean isLdapSupport() {
return ldapSupport;
}
public boolean isLdapSupport() {
return ldapSupport;
}
public void setLdapSupport(boolean ldapSupport) {
this.ldapSupport = ldapSupport;
}
public void setLdapSupport(boolean ldapSupport) {
this.ldapSupport = ldapSupport;
}
}

View File

@ -40,54 +40,54 @@ public class LdapAuthenticationRealmService {
public LdapAuthenticationRealmService(CnfLdapContextService ldapContextService) {
this.ldapContextService = ldapContextService;
}
this.ldapContextService = ldapContextService;
}
public LdapAuthenticationRealm getByInstId(String instId) {
LdapAuthenticationRealm authenticationRealm = ldapRealmStore.getIfPresent(instId);
if(authenticationRealm == null) {
List<CnfLdapContext> ldapContexts =
ldapContextService.find("where instid = ? and status = 1 ", new Object[]{instId}, new int[]{Types.VARCHAR});
authenticationRealm = new LdapAuthenticationRealm(false);
if(ldapContexts != null && ldapContexts.size()>0) {
authenticationRealm.setLdapSupport(true);
List<IAuthenticationServer> ldapAuthenticationServers = new ArrayList<IAuthenticationServer>();
for(CnfLdapContext ldapContext : ldapContexts) {
if(ldapContext.getProduct().equalsIgnoreCase("ActiveDirectory")) {
ActiveDirectoryServer ldapServer = new ActiveDirectoryServer();
ActiveDirectoryUtils ldapUtils = new ActiveDirectoryUtils(
ldapContext.getProviderUrl(),
ldapContext.getPrincipal(),
PasswordReciprocal.getInstance().decoder(
ldapContext.getCredentials()),
ldapContext.getMsadDomain());
ldapServer.setActiveDirectoryUtils(ldapUtils);
if(ldapContext.getAccountMapping().equalsIgnoreCase("YES")) {
ldapServer.setMapping(true);
}
ldapAuthenticationServers.add(ldapServer);
}else {
StandardLdapServer standardLdapServer=new StandardLdapServer();
LdapUtils ldapUtils = new LdapUtils(
ldapContext.getProviderUrl(),
ldapContext.getPrincipal(),
PasswordReciprocal.getInstance().decoder(
ldapContext.getCredentials()),
ldapContext.getBasedn());
standardLdapServer.setLdapUtils(ldapUtils);
standardLdapServer.setFilterAttribute(ldapContext.getFilters());
if(ldapContext.getAccountMapping().equalsIgnoreCase("YES")) {
standardLdapServer.setMapping(true);
}
ldapAuthenticationServers.add(standardLdapServer);
}
}
authenticationRealm.setLdapServers(ldapAuthenticationServers);
}
ldapRealmStore.put(instId, authenticationRealm);
}
return authenticationRealm;
public LdapAuthenticationRealm getByInstId(String instId) {
LdapAuthenticationRealm authenticationRealm = ldapRealmStore.getIfPresent(instId);
if(authenticationRealm == null) {
List<CnfLdapContext> ldapContexts =
ldapContextService.find("where instid = ? and status = 1 ", new Object[]{instId}, new int[]{Types.VARCHAR});
authenticationRealm = new LdapAuthenticationRealm(false);
if(ldapContexts != null && ldapContexts.size()>0) {
authenticationRealm.setLdapSupport(true);
List<IAuthenticationServer> ldapAuthenticationServers = new ArrayList<IAuthenticationServer>();
for(CnfLdapContext ldapContext : ldapContexts) {
if(ldapContext.getProduct().equalsIgnoreCase("ActiveDirectory")) {
ActiveDirectoryServer ldapServer = new ActiveDirectoryServer();
ActiveDirectoryUtils ldapUtils = new ActiveDirectoryUtils(
ldapContext.getProviderUrl(),
ldapContext.getPrincipal(),
PasswordReciprocal.getInstance().decoder(
ldapContext.getCredentials()),
ldapContext.getMsadDomain());
ldapServer.setActiveDirectoryUtils(ldapUtils);
if(ldapContext.getAccountMapping().equalsIgnoreCase("YES")) {
ldapServer.setMapping(true);
}
ldapAuthenticationServers.add(ldapServer);
}else {
StandardLdapServer standardLdapServer=new StandardLdapServer();
LdapUtils ldapUtils = new LdapUtils(
ldapContext.getProviderUrl(),
ldapContext.getPrincipal(),
PasswordReciprocal.getInstance().decoder(
ldapContext.getCredentials()),
ldapContext.getBasedn());
standardLdapServer.setLdapUtils(ldapUtils);
standardLdapServer.setFilterAttribute(ldapContext.getFilters());
if(ldapContext.getAccountMapping().equalsIgnoreCase("YES")) {
standardLdapServer.setMapping(true);
}
ldapAuthenticationServers.add(standardLdapServer);
}
}
authenticationRealm.setLdapServers(ldapAuthenticationServers);
}
ldapRealmStore.put(instId, authenticationRealm);
}
return authenticationRealm;
}
}

View File

@ -35,75 +35,75 @@ import org.slf4j.LoggerFactory;
*
*/
public final class StandardLdapServer implements IAuthenticationServer {
private static final Logger _logger = LoggerFactory.getLogger(StandardLdapServer.class);
LdapUtils ldapUtils;
String filterAttribute;
boolean mapping;
/* (non-Javadoc)
* @see com.connsec.web.authentication.realm.IAuthenticationServer#authenticate(java.lang.String, java.lang.String)
*/
@Override
public boolean authenticate(String username, String password) {
String queryFilter = String.format(filterAttribute, username);
_logger.info(" filter : " + queryFilter);
String dn="";
SearchControls constraints = new SearchControls();
constraints.setSearchScope(ldapUtils.getSearchScope());
try {
NamingEnumeration<SearchResult> results = ldapUtils.getConnection()
.search(ldapUtils.getBaseDN(), queryFilter, constraints);
if (results == null || !results.hasMore()) {
_logger.error("Ldap user "+username +" not found . ");
return false;
}else{
while (results != null && results.hasMore()) {
SearchResult sr = (SearchResult) results.next();
//String rdn = sr.getName();
dn = sr.getNameInNamespace();
_logger.debug("Directory user dn is "+dn+" .");
}
}
} catch (NamingException e) {
_logger.error("query throw NamingException:" + e.getMessage());
} finally {
//ldapUtils.close();
}
LdapUtils ldapPassWordValid=new LdapUtils(ldapUtils.getProviderUrl(),dn,password);
ldapPassWordValid.openConnection();
if(ldapPassWordValid.getCtx()!=null){
_logger.debug("Directory user " + username + " is validate .");
ldapPassWordValid.close();
return true;
}
return false;
}
public LdapUtils getLdapUtils() {
return ldapUtils;
}
public void setLdapUtils(LdapUtils ldapUtils) {
this.ldapUtils = ldapUtils;
}
public String getFilterAttribute() {
return filterAttribute;
}
public void setFilterAttribute(String filterAttribute) {
this.filterAttribute = filterAttribute;
}
private static final Logger _logger = LoggerFactory.getLogger(StandardLdapServer.class);
LdapUtils ldapUtils;
String filterAttribute;
boolean mapping;
/* (non-Javadoc)
* @see com.connsec.web.authentication.realm.IAuthenticationServer#authenticate(java.lang.String, java.lang.String)
*/
@Override
public boolean authenticate(String username, String password) {
String queryFilter = String.format(filterAttribute, username);
_logger.info(" filter : " + queryFilter);
String dn="";
SearchControls constraints = new SearchControls();
constraints.setSearchScope(ldapUtils.getSearchScope());
try {
NamingEnumeration<SearchResult> results = ldapUtils.getConnection()
.search(ldapUtils.getBaseDN(), queryFilter, constraints);
if (results == null || !results.hasMore()) {
_logger.error("Ldap user "+username +" not found . ");
return false;
}else{
while (results != null && results.hasMore()) {
SearchResult sr = (SearchResult) results.next();
//String rdn = sr.getName();
dn = sr.getNameInNamespace();
_logger.debug("Directory user dn is "+dn+" .");
}
}
} catch (NamingException e) {
_logger.error("query throw NamingException:" + e.getMessage());
} finally {
//ldapUtils.close();
}
LdapUtils ldapPassWordValid=new LdapUtils(ldapUtils.getProviderUrl(),dn,password);
ldapPassWordValid.openConnection();
if(ldapPassWordValid.getCtx()!=null){
_logger.debug("Directory user " + username + " is validate .");
ldapPassWordValid.close();
return true;
}
return false;
}
public LdapUtils getLdapUtils() {
return ldapUtils;
}
public void setLdapUtils(LdapUtils ldapUtils) {
this.ldapUtils = ldapUtils;
}
public String getFilterAttribute() {
return filterAttribute;
}
public void setFilterAttribute(String filterAttribute) {
this.filterAttribute = filterAttribute;
}
@Override
public boolean isMapping() {
return mapping;
}
@Override
public boolean isMapping() {
return mapping;
}
public void setMapping(boolean mapping) {
this.mapping = mapping;
}
public void setMapping(boolean mapping) {
this.mapping = mapping;
}
}

View File

@ -33,25 +33,25 @@ public class CasTrustLoginService {
Cas20ServiceTicketValidator cas20ServiceTicketValidator;
public CasTrustLoginService(String casServerUrlPrefix,String service) {
this.service = service;
this.service = service;
this.cas20ServiceTicketValidator = new Cas20ServiceTicketValidator(casServerUrlPrefix);
}
public String buildLoginUser(String ticket) {
_logger.debug("build Login User .");
_logger.debug("build Login User .");
String user = null;
Assertion assertion;
try {
assertion = cas20ServiceTicketValidator.validate(ticket, service);
if(assertion != null) {
user = assertion.getPrincipal().getName();
}
} catch (TicketValidationException e) {
_logger.error("cas TicketValidationException" , e);
e.printStackTrace();
}
try {
assertion = cas20ServiceTicketValidator.validate(ticket, service);
if(assertion != null) {
user = assertion.getPrincipal().getName();
}
} catch (TicketValidationException e) {
_logger.error("cas TicketValidationException" , e);
e.printStackTrace();
}
_logger.debug("cas user : {}" , user);
_logger.debug("cas user : {}" , user);
return user;
}

View File

@ -38,49 +38,49 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/login")
public class HttpTrustEntryPoint {
private static final Logger _logger = LoggerFactory.getLogger(HttpTrustEntryPoint.class);
private static final Logger _logger = LoggerFactory.getLogger(HttpTrustEntryPoint.class);
@Autowired
ApplicationConfig applicationConfig;
@Autowired
ApplicationConfig applicationConfig;
@Autowired
@Autowired
AbstractAuthenticationProvider authenticationProvider ;
@Autowired
AuthTokenService authTokenService;
@Autowired
CasTrustLoginService casTrustLoginService;
@GetMapping(value={"/trust"}, produces = {MediaType.APPLICATION_JSON_VALUE})
public Message<AuthJwt> trust(@RequestParam(value = WebConstants.CAS_TICKET_PARAMETER, required = true) String ticket) {
try {
//for ticket Login
_logger.debug("ticket : {}" , ticket);
String username = casTrustLoginService.buildLoginUser(ticket);
if(username != null) {
LoginCredential loginCredential =new LoginCredential(username,"",ConstsLoginType.CAS);
Authentication authentication = authenticationProvider.authenticate(loginCredential,true);
_logger.debug("CAS Logined in , username {}" , username);
AuthJwt authJwt = authTokenService.genAuthJwt(authentication);
return new Message<>(authJwt);
}
}catch(Exception e) {
_logger.error("Exception ",e);
}
return new Message<>(Message.FAIL);
}
@Autowired
AuthTokenService authTokenService;
@Autowired
CasTrustLoginService casTrustLoginService;
@GetMapping(value={"/trust"}, produces = {MediaType.APPLICATION_JSON_VALUE})
public Message<AuthJwt> trust(@RequestParam(value = WebConstants.CAS_TICKET_PARAMETER, required = true) String ticket) {
try {
//for ticket Login
_logger.debug("ticket : {}" , ticket);
String username = casTrustLoginService.buildLoginUser(ticket);
if(username != null) {
LoginCredential loginCredential =new LoginCredential(username,"",ConstsLoginType.CAS);
Authentication authentication = authenticationProvider.authenticate(loginCredential,true);
_logger.debug("CAS Logined in , username {}" , username);
AuthJwt authJwt = authTokenService.genAuthJwt(authentication);
return new Message<>(authJwt);
}
}catch(Exception e) {
_logger.error("Exception ",e);
}
return new Message<>(Message.FAIL);
}
public void setApplicationConfig(ApplicationConfig applicationConfig) {
this.applicationConfig = applicationConfig;
}
public void setApplicationConfig(ApplicationConfig applicationConfig) {
this.applicationConfig = applicationConfig;
}
public void setAuthenticationProvider(AbstractAuthenticationProvider authenticationProvider) {
this.authenticationProvider = authenticationProvider;
}
public void setAuthenticationProvider(AbstractAuthenticationProvider authenticationProvider) {
this.authenticationProvider = authenticationProvider;
}
}

View File

@ -41,67 +41,67 @@ public class AuthnProviderAutoConfiguration {
@Bean
AbstractAuthenticationProvider authenticationProvider(
NormalAuthenticationProvider normalAuthenticationProvider,
MobileAuthenticationProvider mobileAuthenticationProvider,
TrustedAuthenticationProvider trustedAuthenticationProvider
) {
AuthenticationProviderFactory authenticationProvider = new AuthenticationProviderFactory();
authenticationProvider.addAuthenticationProvider(normalAuthenticationProvider);
authenticationProvider.addAuthenticationProvider(mobileAuthenticationProvider);
authenticationProvider.addAuthenticationProvider(trustedAuthenticationProvider);
return authenticationProvider;
NormalAuthenticationProvider normalAuthenticationProvider,
MobileAuthenticationProvider mobileAuthenticationProvider,
TrustedAuthenticationProvider trustedAuthenticationProvider
) {
AuthenticationProviderFactory authenticationProvider = new AuthenticationProviderFactory();
authenticationProvider.addAuthenticationProvider(normalAuthenticationProvider);
authenticationProvider.addAuthenticationProvider(mobileAuthenticationProvider);
authenticationProvider.addAuthenticationProvider(trustedAuthenticationProvider);
return authenticationProvider;
}
@Bean
NormalAuthenticationProvider normalAuthenticationProvider(
AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig,
SessionManager sessionManager,
AuthTokenService authTokenService
) {
_logger.debug("init authentication Provider .");
return new NormalAuthenticationProvider(
authenticationRealm,
applicationConfig,
sessionManager,
authTokenService
);
AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig,
SessionManager sessionManager,
AuthTokenService authTokenService
) {
_logger.debug("init authentication Provider .");
return new NormalAuthenticationProvider(
authenticationRealm,
applicationConfig,
sessionManager,
authTokenService
);
}
@Bean
MobileAuthenticationProvider mobileAuthenticationProvider(
AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig,
SmsOtpAuthnService smsAuthnService,
SessionManager sessionManager
) {
_logger.debug("init Mobile authentication Provider .");
return new MobileAuthenticationProvider(
authenticationRealm,
applicationConfig,
smsAuthnService,
sessionManager
);
AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig,
SmsOtpAuthnService smsAuthnService,
SessionManager sessionManager
) {
_logger.debug("init Mobile authentication Provider .");
return new MobileAuthenticationProvider(
authenticationRealm,
applicationConfig,
smsAuthnService,
sessionManager
);
}
@Bean
TrustedAuthenticationProvider trustedAuthenticationProvider(
AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig,
SessionManager sessionManager
) {
_logger.debug("init Mobile authentication Provider .");
return new TrustedAuthenticationProvider(
authenticationRealm,
applicationConfig,
sessionManager
);
AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig,
SessionManager sessionManager
) {
_logger.debug("init Mobile authentication Provider .");
return new TrustedAuthenticationProvider(
authenticationRealm,
applicationConfig,
sessionManager
);
}
@Bean
PasswordPolicyValidatorService passwordPolicyValidatorService(
CnfPasswordPolicyService cnfPasswordPolicyService,
MessageSource messageSource) {
CnfPasswordPolicyService cnfPasswordPolicyService,
MessageSource messageSource) {
return new PasswordPolicyValidatorServiceImpl(cnfPasswordPolicyService,messageSource);
}

View File

@ -36,8 +36,8 @@ public class CasAuthnAutoConfiguration {
@Bean
CasTrustLoginService casTrustLoginService(LoginConfig loginConfig) {
CasTrustLoginService casTrustLoginService = new CasTrustLoginService(
loginConfig.getCasServerUrlPrefix() ,
loginConfig.getCasService());
loginConfig.getCasServerUrlPrefix() ,
loginConfig.getCasService());
_logger.debug("CAS Login Service init.");
return casTrustLoginService;
}

View File

@ -58,19 +58,19 @@ public abstract class AbstractAuthenticationProvider {
public static String PROVIDER_SUFFIX = "AuthenticationProvider";
public class AuthType{
public static final String NORMAL = "normal";
public static final String TFA = "tfa";
public static final String MOBILE = "mobile";
public static final String TRUSTED = "trusted";
public static final String NORMAL = "normal";
public static final String TFA = "tfa";
public static final String MOBILE = "mobile";
public static final String TRUSTED = "trusted";
/**
* 扫描认证
*/
public static final String SCAN_CODE = "scancode";
public static final String SCAN_CODE = "scancode";
/**
* 手机端APP
*/
public static final String APP = "app";
public static final String APP = "app";
}
protected ApplicationConfig applicationConfig;
@ -96,7 +96,7 @@ public abstract class AbstractAuthenticationProvider {
public abstract Authentication doAuthenticate(LoginCredential authentication);
public Authentication doTwoFactorAuthenticate(LoginCredential credential , UserInfo user) {
return null;
return null;
}
@SuppressWarnings("rawtypes")
@ -105,11 +105,11 @@ public abstract class AbstractAuthenticationProvider {
}
public Authentication authenticate(LoginCredential authentication){
return null;
return null;
}
public Authentication authenticate(LoginCredential authentication,boolean trusted) {
return null;
return null;
}
/**
@ -130,7 +130,7 @@ public abstract class AbstractAuthenticationProvider {
for(GrantedAuthority administratorsAuthority : grantedAdministratorsAuthoritys) {
if(grantedAuthoritys.contains(administratorsAuthority)) {
principal.setRoleAdministrators(true);
principal.setRoleAdministrators(true);
_logger.trace("ROLE ADMINISTRATORS Authentication .");
}
}
@ -140,7 +140,7 @@ public abstract class AbstractAuthenticationProvider {
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(
principal,
principal,
"PASSWORD",
grantedAuthoritys
);
@ -154,10 +154,10 @@ public abstract class AbstractAuthenticationProvider {
session.setAuthentication(authenticationToken);
if(credential.getAuthType().equalsIgnoreCase(AuthType.NORMAL)
&& userInfo.getAuthnType() > ConstsTwoFactor.NONE ) {
//用户配置二次认证
principal.setTwoFactor(userInfo.getAuthnType());
this.sessionManager.createTwoFactor(session.getId(), session);
&& userInfo.getAuthnType() > ConstsTwoFactor.NONE ) {
//用户配置二次认证
principal.setTwoFactor(userInfo.getAuthnType());
this.sessionManager.createTwoFactor(session.getId(), session);
}
//create session
@ -241,34 +241,34 @@ public abstract class AbstractAuthenticationProvider {
loginUser.setDisplayName("not exist");
loginUser.setLoginCount(0);
authenticationRealm.insertLoginHistory(
loginUser,
ConstsLoginType.LOCAL,
"",
i18nMessage,
WebConstants.LOGIN_RESULT.USER_NOT_EXIST);
loginUser,
ConstsLoginType.LOCAL,
"",
i18nMessage,
WebConstants.LOGIN_RESULT.USER_NOT_EXIST);
throw new BadCredentialsException(i18nMessage);
}
return true;
}
protected boolean statusValid(LoginCredential loginCredential , UserInfo userInfo) {
if(userInfo.getIsLocked()==ConstsStatus.LOCK) {
authenticationRealm.insertLoginHistory(
userInfo,
if(userInfo.getIsLocked()==ConstsStatus.LOCK) {
authenticationRealm.insertLoginHistory(
userInfo,
loginCredential.getAuthType(),
loginCredential.getProvider(),
loginCredential.getCode(),
WebConstants.LOGIN_RESULT.USER_LOCKED
);
}else if(userInfo.getStatus()!=ConstsStatus.ACTIVE) {
authenticationRealm.insertLoginHistory(
userInfo,
}else if(userInfo.getStatus()!=ConstsStatus.ACTIVE) {
authenticationRealm.insertLoginHistory(
userInfo,
loginCredential.getAuthType(),
loginCredential.getProvider(),
loginCredential.getCode(),
WebConstants.LOGIN_RESULT.USER_INACTIVE
);
}
}
return true;
}

View File

@ -26,33 +26,33 @@ public class AuthenticationProviderFactory extends AbstractAuthenticationProvide
@Override
public Authentication authenticate(LoginCredential authentication){
if(authentication.getAuthType().equalsIgnoreCase("trusted")) {
//risk remove
return null;
}
AbstractAuthenticationProvider provider = providers.get(authentication.getAuthType() + PROVIDER_SUFFIX);
return provider == null ? null : provider.doAuthenticate(authentication);
if(authentication.getAuthType().equalsIgnoreCase("trusted")) {
//risk remove
return null;
}
AbstractAuthenticationProvider provider = providers.get(authentication.getAuthType() + PROVIDER_SUFFIX);
return provider == null ? null : provider.doAuthenticate(authentication);
}
@Override
public Authentication authenticate(LoginCredential authentication,boolean trusted){
AbstractAuthenticationProvider provider = providers.get(AuthType.TRUSTED + PROVIDER_SUFFIX);
return provider.doAuthenticate(authentication);
AbstractAuthenticationProvider provider = providers.get(AuthType.TRUSTED + PROVIDER_SUFFIX);
return provider.doAuthenticate(authentication);
}
public void addAuthenticationProvider(AbstractAuthenticationProvider provider) {
providers.put(provider.getProviderName(), provider);
providers.put(provider.getProviderName(), provider);
}
@Override
public String getProviderName() {
return "AuthenticationProviderFactory";
}
@Override
public String getProviderName() {
return "AuthenticationProviderFactory";
}
@Override
public Authentication doAuthenticate(LoginCredential authentication) {
//AuthenticationProvider Factory do nothing
return null;
}
@Override
public Authentication doAuthenticate(LoginCredential authentication) {
//AuthenticationProvider Factory do nothing
return null;
}
}

View File

@ -50,62 +50,62 @@ public class MfaAuthenticationProvider extends AbstractAuthenticationProvider {
public MfaAuthenticationProvider() {
super();
}
super();
}
public MfaAuthenticationProvider(
AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig,
SessionManager sessionManager,
AuthTokenService authTokenService) {
this.authenticationRealm = authenticationRealm;
this.applicationConfig = applicationConfig;
this.sessionManager = sessionManager;
this.authTokenService = authTokenService;
}
AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig,
SessionManager sessionManager,
AuthTokenService authTokenService) {
this.authenticationRealm = authenticationRealm;
this.applicationConfig = applicationConfig;
this.sessionManager = sessionManager;
this.authTokenService = authTokenService;
}
@Override
public Authentication doAuthenticate(LoginCredential loginCredential) {
UsernamePasswordAuthenticationToken authenticationToken = null;
_logger.debug("Trying to authenticate user '{}' via {}",
public Authentication doAuthenticate(LoginCredential loginCredential) {
UsernamePasswordAuthenticationToken authenticationToken = null;
_logger.debug("Trying to authenticate user '{}' via {}",
loginCredential.getPrincipal(), getProviderName());
try {
_logger.debug("authentication {}" , loginCredential);
emptyPasswordValid(loginCredential.getPassword());
UserInfo userInfo = null;
emptyUsernameValid(loginCredential.getUsername());
userInfo = loadUserInfo(loginCredential.getUsername(),loginCredential.getPassword());
isUserExist(loginCredential , userInfo);
statusValid(loginCredential , userInfo);
//mfa
mfacaptchaValid(loginCredential.getOtpCaptcha(),userInfo);
//Validate PasswordPolicy
authenticationRealm.getLoginService().passwordPolicyValid(userInfo);
//Match password
authenticationRealm.passwordMatches(userInfo, loginCredential.getPassword());
_logger.debug("authentication {}" , loginCredential);
emptyPasswordValid(loginCredential.getPassword());
UserInfo userInfo = null;
emptyUsernameValid(loginCredential.getUsername());
userInfo = loadUserInfo(loginCredential.getUsername(),loginCredential.getPassword());
isUserExist(loginCredential , userInfo);
statusValid(loginCredential , userInfo);
//mfa
mfacaptchaValid(loginCredential.getOtpCaptcha(),userInfo);
//Validate PasswordPolicy
authenticationRealm.getLoginService().passwordPolicyValid(userInfo);
//Match password
authenticationRealm.passwordMatches(userInfo, loginCredential.getPassword());
//apply PasswordSetType and resetBadPasswordCount
authenticationRealm.getLoginService().applyPasswordPolicy(userInfo);
authenticationToken = createOnlineTicket(loginCredential,userInfo);
// user authenticated
_logger.debug("'{}' authenticated successfully by {}.",
loginCredential.getPrincipal(), getProviderName());
authenticationRealm.insertLoginHistory(userInfo,
ConstsLoginType.LOCAL,
"",
"xe00000004",
WebConstants.LOGIN_RESULT.SUCCESS);
//apply PasswordSetType and resetBadPasswordCount
authenticationRealm.getLoginService().applyPasswordPolicy(userInfo);
authenticationToken = createOnlineTicket(loginCredential,userInfo);
// user authenticated
_logger.debug("'{}' authenticated successfully by {}.",
loginCredential.getPrincipal(), getProviderName());
authenticationRealm.insertLoginHistory(userInfo,
ConstsLoginType.LOCAL,
"",
"xe00000004",
WebConstants.LOGIN_RESULT.SUCCESS);
} catch (AuthenticationException e) {
_logger.error("Failed to authenticate user {} via {}: {}",
new Object[] { loginCredential.getPrincipal(),

View File

@ -51,65 +51,65 @@ public class NormalAuthenticationProvider extends AbstractAuthenticationProvider
public NormalAuthenticationProvider() {
super();
}
super();
}
public NormalAuthenticationProvider(
AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig,
SessionManager sessionManager,
AuthTokenService authTokenService) {
this.authenticationRealm = authenticationRealm;
this.applicationConfig = applicationConfig;
this.sessionManager = sessionManager;
this.authTokenService = authTokenService;
}
AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig,
SessionManager sessionManager,
AuthTokenService authTokenService) {
this.authenticationRealm = authenticationRealm;
this.applicationConfig = applicationConfig;
this.sessionManager = sessionManager;
this.authTokenService = authTokenService;
}
@Override
public Authentication doAuthenticate(LoginCredential loginCredential) {
UsernamePasswordAuthenticationToken authenticationToken = null;
_logger.debug("Trying to authenticate user '{}' via {}",
public Authentication doAuthenticate(LoginCredential loginCredential) {
UsernamePasswordAuthenticationToken authenticationToken = null;
_logger.debug("Trying to authenticate user '{}' via {}",
loginCredential.getPrincipal(), getProviderName());
try {
_logger.debug("authentication {}" , loginCredential);
if(this.applicationConfig.getLoginConfig().isCaptcha()) {
captchaValid(loginCredential.getState(),loginCredential.getCaptcha());
}
emptyPasswordValid(loginCredential.getPassword());
emptyUsernameValid(loginCredential.getUsername());
UserInfo userInfo = loadUserInfo(loginCredential.getUsername(),loginCredential.getPassword());
isUserExist(loginCredential , userInfo);
//Validate PasswordPolicy
authenticationRealm.getLoginService().passwordPolicyValid(userInfo);
statusValid(loginCredential , userInfo);
//Match password
authenticationRealm.passwordMatches(userInfo, loginCredential.getPassword());
_logger.debug("authentication {}" , loginCredential);
if(this.applicationConfig.getLoginConfig().isCaptcha()) {
captchaValid(loginCredential.getState(),loginCredential.getCaptcha());
}
emptyPasswordValid(loginCredential.getPassword());
emptyUsernameValid(loginCredential.getUsername());
UserInfo userInfo = loadUserInfo(loginCredential.getUsername(),loginCredential.getPassword());
isUserExist(loginCredential , userInfo);
//Validate PasswordPolicy
authenticationRealm.getLoginService().passwordPolicyValid(userInfo);
statusValid(loginCredential , userInfo);
//Match password
authenticationRealm.passwordMatches(userInfo, loginCredential.getPassword());
//apply PasswordSetType and resetBadPasswordCount
authenticationRealm.getLoginService().applyPasswordPolicy(userInfo);
authenticationToken = createOnlineTicket(loginCredential,userInfo);
// user authenticated
_logger.debug("'{}' authenticated successfully by {}.",
loginCredential.getPrincipal(), getProviderName());
authenticationRealm.insertLoginHistory(userInfo,
ConstsLoginType.LOCAL,
"",
"xe00000004",
WebConstants.LOGIN_RESULT.SUCCESS);
//apply PasswordSetType and resetBadPasswordCount
authenticationRealm.getLoginService().applyPasswordPolicy(userInfo);
authenticationToken = createOnlineTicket(loginCredential,userInfo);
// user authenticated
_logger.debug("'{}' authenticated successfully by {}.",
loginCredential.getPrincipal(), getProviderName());
authenticationRealm.insertLoginHistory(userInfo,
ConstsLoginType.LOCAL,
"",
"xe00000004",
WebConstants.LOGIN_RESULT.SUCCESS);
} catch (AuthenticationException e) {
_logger.error("Failed to authenticate user {} via {}: {}",
loginCredential.getPrincipal(),
loginCredential.getPrincipal(),
getProviderName(),
e.getMessage() );
WebContext.setAttribute(
@ -131,8 +131,8 @@ public class NormalAuthenticationProvider extends AbstractAuthenticationProvider
*/
protected void captchaValid(String state ,String captcha) {
// for basic
if(!authTokenService.validateCaptcha(state,captcha)) {
throw new BadCredentialsException(WebContext.getI18nValue("login.error.captcha"));
}
if(!authTokenService.validateCaptcha(state,captcha)) {
throw new BadCredentialsException(WebContext.getI18nValue("login.error.captcha"));
}
}
}

View File

@ -43,26 +43,26 @@ public class TrustedAuthenticationProvider extends AbstractAuthenticationProvide
}
public TrustedAuthenticationProvider() {
super();
}
super();
}
public TrustedAuthenticationProvider(
AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig,
SessionManager sessionManager) {
this.authenticationRealm = authenticationRealm;
this.applicationConfig = applicationConfig;
this.sessionManager = sessionManager;
}
AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig,
SessionManager sessionManager) {
this.authenticationRealm = authenticationRealm;
this.applicationConfig = applicationConfig;
this.sessionManager = sessionManager;
}
@Override
public Authentication doAuthenticate(LoginCredential loginCredential) {
public Authentication doAuthenticate(LoginCredential loginCredential) {
UserInfo loadeduserInfo = loadUserInfo(loginCredential.getUsername(), "");
statusValid(loginCredential , loadeduserInfo);
if (loadeduserInfo != null) {
//Validate PasswordPolicy
//authenticationRealm.getLoginService().passwordPolicyValid(loadeduserInfo);
//apply PasswordSetType and resetBadPasswordCount
//authenticationRealm.getLoginService().applyPasswordPolicy(loadeduserInfo);

View File

@ -42,84 +42,84 @@ public class TwoFactorAuthenticationProvider extends AbstractAuthenticationProvi
}
public TwoFactorAuthenticationProvider(
AbstractAuthenticationRealm authenticationRealm,
SessionManager sessionManager,
LoginService loginService,
AuthTokenService authTokenService) {
this.authenticationRealm = authenticationRealm;
this.sessionManager = sessionManager;
this.authTokenService = authTokenService;
}
AbstractAuthenticationRealm authenticationRealm,
SessionManager sessionManager,
LoginService loginService,
AuthTokenService authTokenService) {
this.authenticationRealm = authenticationRealm;
this.sessionManager = sessionManager;
this.authTokenService = authTokenService;
}
public void addProvider(int twoFactor,AbstractAuthenticationProvider provider) {
twoFactorProvider.put(twoFactor+"", provider);
twoFactorProvider.put(twoFactor+"", provider);
}
@Override
public Authentication doAuthenticate(LoginCredential credential) {
logger.debug("Credential {}" , credential);
emptyOtpCaptchaValid(credential.getOtpCaptcha());
public Authentication doAuthenticate(LoginCredential credential) {
logger.debug("Credential {}" , credential);
emptyOtpCaptchaValid(credential.getOtpCaptcha());
try {
if(authTokenService.validateJwtToken(credential.getJwtToken())) {
//解析refreshToken转换会话id
JWTClaimsSet claim = authTokenService.resolve(credential.getJwtToken());
String sessionId = claim.getJWTID();
String userId = claim.getClaim(ConstsJwt.USER_ID).toString();
//String style = claim.getClaim(AuthorizationUtils.STYLE).toString();
//尝试刷新会话
logger.trace("Try to get user {} , sessionId [{}]" , userId, sessionId);
Session session = sessionManager.getTwoFactor(sessionId);
if(session != null) {//有会话
Authentication twoFactorAuth = null;
SignPrincipal principal =(SignPrincipal) session.getAuthentication().getPrincipal();
String loginType;
switch(principal.getTwoFactor()) {
case ConstsTwoFactor.TOTP -> {
loginType = ConstsLoginType.TwoFactor.TWO_FACTOR_TOTP;
}
case ConstsTwoFactor.EMAIL -> {
loginType = ConstsLoginType.TwoFactor.TWO_FACTOR_EMAIL;
}
case ConstsTwoFactor.SMS -> {
loginType = ConstsLoginType.TwoFactor.TWO_FACTOR_MOBILE;
}
default ->{
loginType = ConstsLoginType.TwoFactor.TWO_FACTOR_TOTP;
}
}
logger.debug("loginType {}",loginType);
AbstractAuthenticationProvider authenticationProvider = twoFactorProvider.get(principal.getTwoFactor()+"");
logger.debug("Provider {}",authenticationProvider.getProviderName());
UserInfo user = authenticationRealm.loadUserInfoById(userId);
//进行二次认证校验
twoFactorAuth = authenticationProvider.doTwoFactorAuthenticate(credential , user);
if(authTokenService.validateJwtToken(credential.getJwtToken())) {
//解析refreshToken转换会话id
JWTClaimsSet claim = authTokenService.resolve(credential.getJwtToken());
String sessionId = claim.getJWTID();
String userId = claim.getClaim(ConstsJwt.USER_ID).toString();
//String style = claim.getClaim(AuthorizationUtils.STYLE).toString();
//尝试刷新会话
logger.trace("Try to get user {} , sessionId [{}]" , userId, sessionId);
Session session = sessionManager.getTwoFactor(sessionId);
if(session != null) {//有会话
Authentication twoFactorAuth = null;
SignPrincipal principal =(SignPrincipal) session.getAuthentication().getPrincipal();
String loginType;
switch(principal.getTwoFactor()) {
case ConstsTwoFactor.TOTP -> {
loginType = ConstsLoginType.TwoFactor.TWO_FACTOR_TOTP;
}
case ConstsTwoFactor.EMAIL -> {
loginType = ConstsLoginType.TwoFactor.TWO_FACTOR_EMAIL;
}
case ConstsTwoFactor.SMS -> {
loginType = ConstsLoginType.TwoFactor.TWO_FACTOR_MOBILE;
}
default ->{
loginType = ConstsLoginType.TwoFactor.TWO_FACTOR_TOTP;
}
}
logger.debug("loginType {}",loginType);
AbstractAuthenticationProvider authenticationProvider = twoFactorProvider.get(principal.getTwoFactor()+"");
logger.debug("Provider {}",authenticationProvider.getProviderName());
UserInfo user = authenticationRealm.loadUserInfoById(userId);
//进行二次认证校验
twoFactorAuth = authenticationProvider.doTwoFactorAuthenticate(credential , user);
if(twoFactorAuth != null) {
logger.debug("twoFactorAuth success .");
//设置正常状态
principal.clearTwoFactor();
//重新设置令牌参数
sessionManager.create(sessionId, session);
sessionManager.removeTwoFactor(sessionId);
AuthorizationUtils.setAuthentication(session.getAuthentication());
authenticationRealm.insertLoginHistory(user,
loginType,
"",
"xe00000004",
WebConstants.LOGIN_RESULT.SUCCESS);
return session.getAuthentication();
}else {
logger.debug("twoFactorAuth fail .");
}
}else {//无会话
logger.debug("Session is timeout , sessionId [{}]" , sessionId);
}
}else {//验证失效
logger.debug("jwt token is not validate .");
}
if(twoFactorAuth != null) {
logger.debug("twoFactorAuth success .");
//设置正常状态
principal.clearTwoFactor();
//重新设置令牌参数
sessionManager.create(sessionId, session);
sessionManager.removeTwoFactor(sessionId);
AuthorizationUtils.setAuthentication(session.getAuthentication());
authenticationRealm.insertLoginHistory(user,
loginType,
"",
"xe00000004",
WebConstants.LOGIN_RESULT.SUCCESS);
return session.getAuthentication();
}else {
logger.debug("twoFactorAuth fail .");
}
}else {//无会话
logger.debug("Session is timeout , sessionId [{}]" , sessionId);
}
}else {//验证失效
logger.debug("jwt token is not validate .");
}
}catch(Exception e) {
logger.error("Exception !",e);
}
logger.error("Exception !",e);
}
return null;
}

View File

@ -34,24 +34,24 @@ public class TwoFactorEmailAuthenticationProvider extends AbstractAuthentication
}
public TwoFactorEmailAuthenticationProvider(MailOtpAuthnService mailOtpAuthnService) {
this.mailOtpAuthnService = mailOtpAuthnService;
}
this.mailOtpAuthnService = mailOtpAuthnService;
}
@Override
public Authentication doAuthenticate(LoginCredential credential) {
return null;
public Authentication doAuthenticate(LoginCredential credential) {
return null;
}
@Override
public Authentication doTwoFactorAuthenticate(LoginCredential credential,UserInfo user) {
UsernamePasswordAuthenticationToken authenticationToken = null;
logger.debug("loginCredential {}" , credential);
public Authentication doTwoFactorAuthenticate(LoginCredential credential,UserInfo user) {
UsernamePasswordAuthenticationToken authenticationToken = null;
logger.debug("loginCredential {}" , credential);
try {
//短信验证码校验
matches(credential.getOtpCaptcha(),user);
authenticationToken = new UsernamePasswordAuthenticationToken(credential.getUsername(),"email");
//短信验证码校验
matches(credential.getOtpCaptcha(),user);
authenticationToken = new UsernamePasswordAuthenticationToken(credential.getUsername(),"email");
} catch (AuthenticationException e) {
logger.error("Failed to authenticate user {} via {}: {}",credential.getPrincipal(),
getProviderName(),
@ -75,7 +75,7 @@ public class TwoFactorEmailAuthenticationProvider extends AbstractAuthentication
* @param userInfo UserInfo
*/
protected void matches(String captcha, UserInfo userInfo) {
// for mobile password
// for mobile password
UserInfo validUserInfo = new UserInfo();
validUserInfo.setUsername(userInfo.getUsername());
validUserInfo.setId(userInfo.getId());

View File

@ -34,24 +34,24 @@ public class TwoFactorMobileAuthenticationProvider extends AbstractAuthenticatio
}
public TwoFactorMobileAuthenticationProvider(SmsOtpAuthnService smsOtpAuthnService) {
this.smsOtpAuthnService = smsOtpAuthnService;
}
this.smsOtpAuthnService = smsOtpAuthnService;
}
@Override
public Authentication doAuthenticate(LoginCredential credential) {
return null;
public Authentication doAuthenticate(LoginCredential credential) {
return null;
}
@Override
public Authentication doTwoFactorAuthenticate(LoginCredential credential,UserInfo user) {
UsernamePasswordAuthenticationToken authenticationToken = null;
logger.debug("loginCredential {}" , credential);
public Authentication doTwoFactorAuthenticate(LoginCredential credential,UserInfo user) {
UsernamePasswordAuthenticationToken authenticationToken = null;
logger.debug("loginCredential {}" , credential);
try {
//短信验证码校验
matches(credential.getOtpCaptcha(),user);
authenticationToken = new UsernamePasswordAuthenticationToken(credential.getUsername(),"mobile");
//短信验证码校验
matches(credential.getOtpCaptcha(),user);
authenticationToken = new UsernamePasswordAuthenticationToken(credential.getUsername(),"mobile");
} catch (AuthenticationException e) {
logger.error("Failed to authenticate user {} via {}: {}",credential.getPrincipal(),
getProviderName(),
@ -73,7 +73,7 @@ public class TwoFactorMobileAuthenticationProvider extends AbstractAuthenticatio
* @param userInfo UserInfo
*/
protected void matches(String captcha, UserInfo userInfo) {
// for mobile password
// for mobile password
UserInfo validUserInfo = new UserInfo();
validUserInfo.setUsername(userInfo.getUsername());
validUserInfo.setId(userInfo.getId());

View File

@ -31,27 +31,27 @@ public class TwoFactorTotpAuthenticationProvider extends AbstractAuthenticationP
}
public TwoFactorTotpAuthenticationProvider(AbstractAuthenticationRealm authenticationRealm,AbstractOtpAuthn tfaOtpAuthn) {
this.authenticationRealm = authenticationRealm;
this.tfaOtpAuthn = tfaOtpAuthn;
}
this.authenticationRealm = authenticationRealm;
this.tfaOtpAuthn = tfaOtpAuthn;
}
@Override
public Authentication doAuthenticate(LoginCredential credential) {
return null;
public Authentication doAuthenticate(LoginCredential credential) {
return null;
}
@Override
public Authentication doTwoFactorAuthenticate(LoginCredential credential,UserInfo user) {
UsernamePasswordAuthenticationToken authenticationToken = null;
logger.debug("loginCredential {}" , credential);
public Authentication doTwoFactorAuthenticate(LoginCredential credential,UserInfo user) {
UsernamePasswordAuthenticationToken authenticationToken = null;
logger.debug("loginCredential {}" , credential);
try {
//验证码校验
UserInfo userTotp = authenticationRealm.loadUserInfoById(user.getId());
matches(credential.getOtpCaptcha(),userTotp.getSharedSecret());
authenticationToken = new UsernamePasswordAuthenticationToken(credential.getUsername(),"TOTP");
//验证码校验
UserInfo userTotp = authenticationRealm.loadUserInfoById(user.getId());
matches(credential.getOtpCaptcha(),userTotp.getSharedSecret());
authenticationToken = new UsernamePasswordAuthenticationToken(credential.getUsername(),"TOTP");
} catch (AuthenticationException e) {
logger.error("Failed to authenticate user {} via {}: {}",credential.getPrincipal(),
getProviderName(),

View File

@ -131,8 +131,8 @@ public abstract class AbstractAuthenticationRealm {
historyLogin.setSessionStatus(7);
Authentication authentication = (Authentication ) WebContext.getAttribute(WebConstants.AUTHENTICATION);
if(authentication != null
&& authentication.getPrincipal() instanceof SignPrincipal) {
historyLogin.setSessionStatus(1);
&& authentication.getPrincipal() instanceof SignPrincipal) {
historyLogin.setSessionStatus(1);
historyLogin.setSessionId(userInfo.getSessionId());
}
@ -157,15 +157,15 @@ public abstract class AbstractAuthenticationRealm {
Region ipRegion =ipLocationParser.region(userInfo.getLastLoginIp());
if(ipRegion != null) {
historyLogin.setCountry(ipRegion.getCountry());
historyLogin.setProvince(ipRegion.getProvince());
historyLogin.setCity(ipRegion.getCity());
historyLogin.setLocation(ipRegion.getAddr());
historyLogin.setCountry(ipRegion.getCountry());
historyLogin.setProvince(ipRegion.getProvince());
historyLogin.setCity(ipRegion.getCity());
historyLogin.setLocation(ipRegion.getAddr());
}
historyLoginService.login(historyLogin);
if(WebConstants.LOGIN_RESULT.SUCCESS.equalsIgnoreCase(message)) {
loginService.updateLastLogin(userInfo);
loginService.updateLastLogin(userInfo);
}
return true;

View File

@ -57,40 +57,40 @@ public class JdbcAuthenticationRealm extends AbstractAuthenticationRealm {
}
public JdbcAuthenticationRealm(
PasswordEncoder passwordEncoder,
PasswordPolicyValidatorService passwordPolicyValidatorService,
LoginService loginService,
HistoryLoginService historyLoginService,
UserInfoService userInfoService,
IpLocationParser ipLocationParser,
JdbcTemplate jdbcTemplate) {
this.passwordEncoder =passwordEncoder;
this.passwordPolicyValidatorService=passwordPolicyValidatorService;
this.loginService = loginService;
this.historyLoginService = historyLoginService;
this.userInfoService = userInfoService;
this.ipLocationParser = ipLocationParser;
PasswordEncoder passwordEncoder,
PasswordPolicyValidatorService passwordPolicyValidatorService,
LoginService loginService,
HistoryLoginService historyLoginService,
UserInfoService userInfoService,
IpLocationParser ipLocationParser,
JdbcTemplate jdbcTemplate) {
this.passwordEncoder =passwordEncoder;
this.passwordPolicyValidatorService=passwordPolicyValidatorService;
this.loginService = loginService;
this.historyLoginService = historyLoginService;
this.userInfoService = userInfoService;
this.ipLocationParser = ipLocationParser;
this.jdbcTemplate = jdbcTemplate;
}
public JdbcAuthenticationRealm(
PasswordEncoder passwordEncoder,
PasswordPolicyValidatorService passwordPolicyValidatorService,
LoginService loginService,
HistoryLoginService historyLoginService,
UserInfoService userInfoService,
IpLocationParser ipLocationParser,
JdbcTemplate jdbcTemplate,
LdapAuthenticationRealmService ldapAuthenticationRealmService) {
this.passwordEncoder = passwordEncoder;
this.passwordPolicyValidatorService = passwordPolicyValidatorService;
this.loginService = loginService;
this.historyLoginService = historyLoginService;
this.userInfoService = userInfoService;
this.ipLocationParser = ipLocationParser;
this.jdbcTemplate = jdbcTemplate;
this.ldapAuthenticationRealmService = ldapAuthenticationRealmService;
PasswordEncoder passwordEncoder,
PasswordPolicyValidatorService passwordPolicyValidatorService,
LoginService loginService,
HistoryLoginService historyLoginService,
UserInfoService userInfoService,
IpLocationParser ipLocationParser,
JdbcTemplate jdbcTemplate,
LdapAuthenticationRealmService ldapAuthenticationRealmService) {
this.passwordEncoder = passwordEncoder;
this.passwordPolicyValidatorService = passwordPolicyValidatorService;
this.loginService = loginService;
this.historyLoginService = historyLoginService;
this.userInfoService = userInfoService;
this.ipLocationParser = ipLocationParser;
this.jdbcTemplate = jdbcTemplate;
this.ldapAuthenticationRealmService = ldapAuthenticationRealmService;
}
/**
@ -105,28 +105,28 @@ public class JdbcAuthenticationRealm extends AbstractAuthenticationRealm {
passwordMatches = passwordEncoder.matches(password,userInfo.getPassword());
if(ldapAuthenticationRealmService != null) {
//passwordMatches == false and ldapSupport ==true
//validate password with LDAP
try {
LdapAuthenticationRealm ldapRealm = ldapAuthenticationRealmService.getByInstId(userInfo.getInstId());
if(!passwordMatches && ldapRealm != null
&& ldapRealm.isLdapSupport()
&& userInfo.getIsLocked() == ConstsStatus.ACTIVE) {
passwordMatches = ldapRealm.passwordMatches(userInfo, password);
if(passwordMatches) {
//write password to database Realm
ChangePassword changePassword = new ChangePassword(userInfo);
changePassword.setPassword(password);
userInfoService.changePassword(changePassword, false);
}
}
}catch(Exception e) {
_logger.debug("passwordvalid Exception : {}" , e);
}
//passwordMatches == false and ldapSupport ==true
//validate password with LDAP
try {
LdapAuthenticationRealm ldapRealm = ldapAuthenticationRealmService.getByInstId(userInfo.getInstId());
if(!passwordMatches && ldapRealm != null
&& ldapRealm.isLdapSupport()
&& userInfo.getIsLocked() == ConstsStatus.ACTIVE) {
passwordMatches = ldapRealm.passwordMatches(userInfo, password);
if(passwordMatches) {
//write password to database Realm
ChangePassword changePassword = new ChangePassword(userInfo);
changePassword.setPassword(password);
userInfoService.changePassword(changePassword, false);
}
}
}catch(Exception e) {
_logger.debug("passwordvalid Exception : {}" , e);
}
}
_logger.debug("passwordvalid : {}" , passwordMatches);
if (!passwordMatches) {
loginService.plusBadPasswordCount(userInfo);
loginService.plusBadPasswordCount(userInfo);
insertLoginHistory(userInfo, ConstsLoginType.LOCAL, "", "xe00000004", WebConstants.LOGIN_RESULT.PASSWORD_ERROE);
CnfPasswordPolicy passwordPolicy = passwordPolicyValidatorService.getPasswordPolicy();
if(userInfo.getBadPasswordCount()>=(passwordPolicy.getAttempts()/2)) {

View File

@ -30,59 +30,59 @@ import org.slf4j.LoggerFactory;
*
*/
public final class ActiveDirectoryServer implements IAuthenticationServer {
private static final Logger _logger = LoggerFactory.getLogger(ActiveDirectoryServer.class);
private static final Logger _logger = LoggerFactory.getLogger(ActiveDirectoryServer.class);
ActiveDirectoryUtils activeDirectoryUtils;
ActiveDirectoryUtils activeDirectoryUtils;
String filter;
boolean mapping;
/* (non-Javadoc)
* @see com.connsec.web.authentication.realm.IAuthenticationServer#authenticate(java.lang.String, java.lang.String)
*/
@Override
public boolean authenticate(String username, String password) {
ActiveDirectoryUtils ldapPassWordValid =
new ActiveDirectoryUtils(
activeDirectoryUtils.getProviderUrl(),
username,
password,
activeDirectoryUtils.getDomain()
);
ldapPassWordValid.openConnection();
if(ldapPassWordValid.getCtx()!=null){
_logger.debug("Active Directory user " + username + " is validate .");
ldapPassWordValid.close();
return true;
}
ldapPassWordValid.close();
return false;
}
String filter;
boolean mapping;
/* (non-Javadoc)
* @see com.connsec.web.authentication.realm.IAuthenticationServer#authenticate(java.lang.String, java.lang.String)
*/
@Override
public boolean authenticate(String username, String password) {
ActiveDirectoryUtils ldapPassWordValid =
new ActiveDirectoryUtils(
activeDirectoryUtils.getProviderUrl(),
username,
password,
activeDirectoryUtils.getDomain()
);
ldapPassWordValid.openConnection();
if(ldapPassWordValid.getCtx()!=null){
_logger.debug("Active Directory user " + username + " is validate .");
ldapPassWordValid.close();
return true;
}
ldapPassWordValid.close();
return false;
}
public ActiveDirectoryUtils getActiveDirectoryUtils() {
return activeDirectoryUtils;
}
public ActiveDirectoryUtils getActiveDirectoryUtils() {
return activeDirectoryUtils;
}
public void setActiveDirectoryUtils(ActiveDirectoryUtils activeDirectoryUtils) {
this.activeDirectoryUtils = activeDirectoryUtils;
}
public void setActiveDirectoryUtils(ActiveDirectoryUtils activeDirectoryUtils) {
this.activeDirectoryUtils = activeDirectoryUtils;
}
public String getFilter() {
return filter;
}
public String getFilter() {
return filter;
}
public void setFilter(String filter) {
this.filter = filter;
}
public void setFilter(String filter) {
this.filter = filter;
}
@Override
public boolean isMapping() {
return mapping;
}
@Override
public boolean isMapping() {
return mapping;
}
public void setMapping(boolean mapping) {
this.mapping = mapping;
}
public void setMapping(boolean mapping) {
this.mapping = mapping;
}
}

View File

@ -30,65 +30,65 @@ import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
public class LdapAuthenticationRealm extends AbstractAuthenticationRealm{
private static final Logger _logger = LoggerFactory.getLogger(LdapAuthenticationRealm.class);
@NotNull
private static final Logger _logger = LoggerFactory.getLogger(LdapAuthenticationRealm.class);
@NotNull
@Size(min=1)
private List<IAuthenticationServer> ldapServers;
private boolean ldapSupport;
/**
*
*/
public LdapAuthenticationRealm() {
}
private boolean ldapSupport;
/**
*
*/
public LdapAuthenticationRealm() {
}
public LdapAuthenticationRealm(boolean ldapSupport) {
this.ldapSupport = ldapSupport;
}
/**
* @param jdbcTemplate
*/
public LdapAuthenticationRealm(JdbcTemplate jdbcTemplate) {
super(jdbcTemplate);
}
@Override
public boolean passwordMatches(UserInfo userInfo, String password) {
boolean isAuthenticated=false;
for (final IAuthenticationServer ldapServer : this.ldapServers) {
String username = userInfo.getUsername();
if(ldapServer.isMapping()) {//if ldap Context accountMapping equals YES
username = userInfo.getWindowsAccount();
}
public LdapAuthenticationRealm(boolean ldapSupport) {
this.ldapSupport = ldapSupport;
}
/**
* @param jdbcTemplate
*/
public LdapAuthenticationRealm(JdbcTemplate jdbcTemplate) {
super(jdbcTemplate);
}
@Override
public boolean passwordMatches(UserInfo userInfo, String password) {
boolean isAuthenticated=false;
for (final IAuthenticationServer ldapServer : this.ldapServers) {
String username = userInfo.getUsername();
if(ldapServer.isMapping()) {//if ldap Context accountMapping equals YES
username = userInfo.getWindowsAccount();
}
_logger.debug("Attempting to authenticate {} at {}", username, ldapServer);
try {
isAuthenticated = ldapServer.authenticate(username, password);
isAuthenticated = ldapServer.authenticate(username, password);
}catch(Exception e) {
_logger.debug("Attempting Authenticated fail .");
_logger.debug("Attempting Authenticated fail .");
}
if (isAuthenticated ) {
return true;
return true;
}
}
return false;
}
}
return false;
}
public void setLdapServers(List<IAuthenticationServer> ldapServers) {
this.ldapServers = ldapServers;
}
public void setLdapServers(List<IAuthenticationServer> ldapServers) {
this.ldapServers = ldapServers;
}
public boolean isLdapSupport() {
return ldapSupport;
}
public boolean isLdapSupport() {
return ldapSupport;
}
public void setLdapSupport(boolean ldapSupport) {
this.ldapSupport = ldapSupport;
}
public void setLdapSupport(boolean ldapSupport) {
this.ldapSupport = ldapSupport;
}
}

View File

@ -40,54 +40,54 @@ public class LdapAuthenticationRealmService {
public LdapAuthenticationRealmService(CnfLdapContextService ldapContextService) {
this.ldapContextService = ldapContextService;
}
this.ldapContextService = ldapContextService;
}
public LdapAuthenticationRealm getByInstId(String instId) {
LdapAuthenticationRealm authenticationRealm = ldapRealmStore.getIfPresent(instId);
if(authenticationRealm == null) {
List<CnfLdapContext> ldapContexts =
ldapContextService.find("where instid = ? and status = 1 ", new Object[]{instId}, new int[]{Types.VARCHAR});
authenticationRealm = new LdapAuthenticationRealm(false);
if(ldapContexts != null && ldapContexts.size()>0) {
authenticationRealm.setLdapSupport(true);
List<IAuthenticationServer> ldapAuthenticationServers = new ArrayList<IAuthenticationServer>();
for(CnfLdapContext ldapContext : ldapContexts) {
if(ldapContext.getProduct().equalsIgnoreCase("ActiveDirectory")) {
ActiveDirectoryServer ldapServer = new ActiveDirectoryServer();
ActiveDirectoryUtils ldapUtils = new ActiveDirectoryUtils(
ldapContext.getProviderUrl(),
ldapContext.getPrincipal(),
PasswordReciprocal.getInstance().decoder(
ldapContext.getCredentials()),
ldapContext.getMsadDomain());
ldapServer.setActiveDirectoryUtils(ldapUtils);
if(ldapContext.getAccountMapping().equalsIgnoreCase("YES")) {
ldapServer.setMapping(true);
}
ldapAuthenticationServers.add(ldapServer);
}else {
StandardLdapServer standardLdapServer=new StandardLdapServer();
LdapUtils ldapUtils = new LdapUtils(
ldapContext.getProviderUrl(),
ldapContext.getPrincipal(),
PasswordReciprocal.getInstance().decoder(
ldapContext.getCredentials()),
ldapContext.getBasedn());
standardLdapServer.setLdapUtils(ldapUtils);
standardLdapServer.setFilterAttribute(ldapContext.getFilters());
if(ldapContext.getAccountMapping().equalsIgnoreCase("YES")) {
standardLdapServer.setMapping(true);
}
ldapAuthenticationServers.add(standardLdapServer);
}
}
authenticationRealm.setLdapServers(ldapAuthenticationServers);
}
ldapRealmStore.put(instId, authenticationRealm);
}
return authenticationRealm;
public LdapAuthenticationRealm getByInstId(String instId) {
LdapAuthenticationRealm authenticationRealm = ldapRealmStore.getIfPresent(instId);
if(authenticationRealm == null) {
List<CnfLdapContext> ldapContexts =
ldapContextService.find("where instid = ? and status = 1 ", new Object[]{instId}, new int[]{Types.VARCHAR});
authenticationRealm = new LdapAuthenticationRealm(false);
if(ldapContexts != null && ldapContexts.size()>0) {
authenticationRealm.setLdapSupport(true);
List<IAuthenticationServer> ldapAuthenticationServers = new ArrayList<IAuthenticationServer>();
for(CnfLdapContext ldapContext : ldapContexts) {
if(ldapContext.getProduct().equalsIgnoreCase("ActiveDirectory")) {
ActiveDirectoryServer ldapServer = new ActiveDirectoryServer();
ActiveDirectoryUtils ldapUtils = new ActiveDirectoryUtils(
ldapContext.getProviderUrl(),
ldapContext.getPrincipal(),
PasswordReciprocal.getInstance().decoder(
ldapContext.getCredentials()),
ldapContext.getMsadDomain());
ldapServer.setActiveDirectoryUtils(ldapUtils);
if(ldapContext.getAccountMapping().equalsIgnoreCase("YES")) {
ldapServer.setMapping(true);
}
ldapAuthenticationServers.add(ldapServer);
}else {
StandardLdapServer standardLdapServer=new StandardLdapServer();
LdapUtils ldapUtils = new LdapUtils(
ldapContext.getProviderUrl(),
ldapContext.getPrincipal(),
PasswordReciprocal.getInstance().decoder(
ldapContext.getCredentials()),
ldapContext.getBasedn());
standardLdapServer.setLdapUtils(ldapUtils);
standardLdapServer.setFilterAttribute(ldapContext.getFilters());
if(ldapContext.getAccountMapping().equalsIgnoreCase("YES")) {
standardLdapServer.setMapping(true);
}
ldapAuthenticationServers.add(standardLdapServer);
}
}
authenticationRealm.setLdapServers(ldapAuthenticationServers);
}
ldapRealmStore.put(instId, authenticationRealm);
}
return authenticationRealm;
}
}

View File

@ -35,75 +35,75 @@ import org.slf4j.LoggerFactory;
*
*/
public final class StandardLdapServer implements IAuthenticationServer {
private static final Logger _logger = LoggerFactory.getLogger(StandardLdapServer.class);
LdapUtils ldapUtils;
String filterAttribute;
boolean mapping;
/* (non-Javadoc)
* @see com.connsec.web.authentication.realm.IAuthenticationServer#authenticate(java.lang.String, java.lang.String)
*/
@Override
public boolean authenticate(String username, String password) {
String queryFilter = String.format(filterAttribute, username);
_logger.info(" filter : " + queryFilter);
String dn="";
SearchControls constraints = new SearchControls();
constraints.setSearchScope(ldapUtils.getSearchScope());
try {
NamingEnumeration<SearchResult> results = ldapUtils.getConnection()
.search(ldapUtils.getBaseDN(), queryFilter, constraints);
if (results == null || !results.hasMore()) {
_logger.error("Ldap user "+username +" not found . ");
return false;
}else{
while (results != null && results.hasMore()) {
SearchResult sr = (SearchResult) results.next();
//String rdn = sr.getName();
dn = sr.getNameInNamespace();
_logger.debug("Directory user dn is "+dn+" .");
}
}
} catch (NamingException e) {
_logger.error("query throw NamingException:" + e.getMessage());
} finally {
//ldapUtils.close();
}
LdapUtils ldapPassWordValid=new LdapUtils(ldapUtils.getProviderUrl(),dn,password);
ldapPassWordValid.openConnection();
if(ldapPassWordValid.getCtx()!=null){
_logger.debug("Directory user " + username + " is validate .");
ldapPassWordValid.close();
return true;
}
return false;
}
public LdapUtils getLdapUtils() {
return ldapUtils;
}
public void setLdapUtils(LdapUtils ldapUtils) {
this.ldapUtils = ldapUtils;
}
public String getFilterAttribute() {
return filterAttribute;
}
public void setFilterAttribute(String filterAttribute) {
this.filterAttribute = filterAttribute;
}
private static final Logger _logger = LoggerFactory.getLogger(StandardLdapServer.class);
LdapUtils ldapUtils;
String filterAttribute;
boolean mapping;
/* (non-Javadoc)
* @see com.connsec.web.authentication.realm.IAuthenticationServer#authenticate(java.lang.String, java.lang.String)
*/
@Override
public boolean authenticate(String username, String password) {
String queryFilter = String.format(filterAttribute, username);
_logger.info(" filter : " + queryFilter);
String dn="";
SearchControls constraints = new SearchControls();
constraints.setSearchScope(ldapUtils.getSearchScope());
try {
NamingEnumeration<SearchResult> results = ldapUtils.getConnection()
.search(ldapUtils.getBaseDN(), queryFilter, constraints);
if (results == null || !results.hasMore()) {
_logger.error("Ldap user "+username +" not found . ");
return false;
}else{
while (results != null && results.hasMore()) {
SearchResult sr = (SearchResult) results.next();
//String rdn = sr.getName();
dn = sr.getNameInNamespace();
_logger.debug("Directory user dn is "+dn+" .");
}
}
} catch (NamingException e) {
_logger.error("query throw NamingException:" + e.getMessage());
} finally {
//ldapUtils.close();
}
LdapUtils ldapPassWordValid=new LdapUtils(ldapUtils.getProviderUrl(),dn,password);
ldapPassWordValid.openConnection();
if(ldapPassWordValid.getCtx()!=null){
_logger.debug("Directory user " + username + " is validate .");
ldapPassWordValid.close();
return true;
}
return false;
}
public LdapUtils getLdapUtils() {
return ldapUtils;
}
public void setLdapUtils(LdapUtils ldapUtils) {
this.ldapUtils = ldapUtils;
}
public String getFilterAttribute() {
return filterAttribute;
}
public void setFilterAttribute(String filterAttribute) {
this.filterAttribute = filterAttribute;
}
@Override
public boolean isMapping() {
return mapping;
}
@Override
public boolean isMapping() {
return mapping;
}
public void setMapping(boolean mapping) {
this.mapping = mapping;
}
public void setMapping(boolean mapping) {
this.mapping = mapping;
}
}

View File

@ -35,116 +35,116 @@ import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
public class BasicEntryPoint implements AsyncHandlerInterceptor {
private static final Logger _logger = LoggerFactory.getLogger(BasicEntryPoint.class);
boolean enable;
@Autowired
private static final Logger _logger = LoggerFactory.getLogger(BasicEntryPoint.class);
boolean enable;
@Autowired
@Qualifier("authenticationProvider")
AbstractAuthenticationProvider authenticationProvider ;
public BasicEntryPoint() {
AbstractAuthenticationProvider authenticationProvider ;
public BasicEntryPoint() {
}
public BasicEntryPoint(boolean enable) {
public BasicEntryPoint(boolean enable) {
super();
this.enable = enable;
}
String []skipRequestURI={
"/oauth/v20/token",
"/oauth/v10a/request_token",
"/oauth/v10a/access_token"
};
@Override
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
if(!enable){
return true;
}
String requestPath=request.getServletPath();
_logger.debug("HttpHeader Login Start ...");
_logger.info("Request url : "+ request.getRequestURL());
_logger.info("Request URI : "+ request.getRequestURI());
_logger.info("Request ContextPath : "+ request.getContextPath());
_logger.info("Request ServletPath : "+ request.getServletPath());
_logger.debug("RequestSessionId : "+ request.getRequestedSessionId());
_logger.debug("isRequestedSessionIdValid : "+ request.isRequestedSessionIdValid());
_logger.debug("getSession : "+ request.getSession(false));
for(int i=0;i<skipRequestURI.length;i++){
if(skipRequestURI[i].indexOf(requestPath)>-1){
_logger.info("skip uri : "+ requestPath);
return true;
}
}
// session not existssession timeoutrecreate new session
if(request.getSession(false) == null) {
_logger.info("recreate new session .");
request.getSession(true);
}
String basicCredential =request.getHeader(AuthorizationHeaderUtils.HEADER_Authorization);
_logger.info("getSession.getId : "+ request.getSession().getId());
_logger.info("Authorization : " + basicCredential);
if(basicCredential==null||basicCredential.equals("")){
_logger.info("Authentication fail header Authorization is null . ");
return false;
}
AuthorizationHeader headerCredential = null;
if(AuthorizationHeaderUtils.isBasic(basicCredential)){
headerCredential=AuthorizationHeaderUtils.resolve(basicCredential);
}else{
return false;
}
if(headerCredential.getUsername()==null||headerCredential.getUsername().equals("")){
_logger.info("Authentication fail username is null . ");
return false;
}
if(headerCredential.getCredential()==null||headerCredential.getCredential().equals("")){
_logger.info("Authentication fail password is null . ");
return false;
}
boolean isAuthenticated=false;
if(SecurityContextHolder.getContext().getAuthentication() == null) {
_logger.info("Security Authentication is null .");
isAuthenticated=false;
}else {
_logger.info("Security Authentication not null . ");
UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
String lastSessionUserName = authenticationToken.getPrincipal().toString();
_logger.info("Authentication Principal : " + lastSessionUserName);
if (lastSessionUserName != null && !lastSessionUserName.equals(headerCredential.getUsername())) {
isAuthenticated=false;
}else{
isAuthenticated=true;
}
}
if(!isAuthenticated){
LoginCredential loginCredential =new LoginCredential(headerCredential.getUsername(),"",ConstsLoginType.BASIC);
authenticationProvider.authenticate(loginCredential,true);
_logger.info("Authentication "+headerCredential.getUsername()+" successful .");
}
return true;
}
"/oauth/v20/token",
"/oauth/v10a/request_token",
"/oauth/v10a/access_token"
};
@Override
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
if(!enable){
return true;
}
String requestPath=request.getServletPath();
_logger.debug("HttpHeader Login Start ...");
_logger.info("Request url : "+ request.getRequestURL());
_logger.info("Request URI : "+ request.getRequestURI());
_logger.info("Request ContextPath : "+ request.getContextPath());
_logger.info("Request ServletPath : "+ request.getServletPath());
_logger.debug("RequestSessionId : "+ request.getRequestedSessionId());
_logger.debug("isRequestedSessionIdValid : "+ request.isRequestedSessionIdValid());
_logger.debug("getSession : "+ request.getSession(false));
for(int i=0;i<skipRequestURI.length;i++){
if(skipRequestURI[i].indexOf(requestPath)>-1){
_logger.info("skip uri : "+ requestPath);
return true;
}
}
// session not existssession timeoutrecreate new session
if(request.getSession(false) == null) {
_logger.info("recreate new session .");
request.getSession(true);
}
String basicCredential =request.getHeader(AuthorizationHeaderUtils.HEADER_Authorization);
_logger.info("getSession.getId : "+ request.getSession().getId());
_logger.info("Authorization : " + basicCredential);
if(basicCredential==null||basicCredential.equals("")){
_logger.info("Authentication fail header Authorization is null . ");
return false;
}
AuthorizationHeader headerCredential = null;
if(AuthorizationHeaderUtils.isBasic(basicCredential)){
headerCredential=AuthorizationHeaderUtils.resolve(basicCredential);
}else{
return false;
}
if(headerCredential.getUsername()==null||headerCredential.getUsername().equals("")){
_logger.info("Authentication fail username is null . ");
return false;
}
if(headerCredential.getCredential()==null||headerCredential.getCredential().equals("")){
_logger.info("Authentication fail password is null . ");
return false;
}
boolean isAuthenticated=false;
if(SecurityContextHolder.getContext().getAuthentication() == null) {
_logger.info("Security Authentication is null .");
isAuthenticated=false;
}else {
_logger.info("Security Authentication not null . ");
UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
String lastSessionUserName = authenticationToken.getPrincipal().toString();
_logger.info("Authentication Principal : " + lastSessionUserName);
if (lastSessionUserName != null && !lastSessionUserName.equals(headerCredential.getUsername())) {
isAuthenticated=false;
}else{
isAuthenticated=true;
}
}
if(!isAuthenticated){
LoginCredential loginCredential =new LoginCredential(headerCredential.getUsername(),"",ConstsLoginType.BASIC);
authenticationProvider.authenticate(loginCredential,true);
_logger.info("Authentication "+headerCredential.getUsername()+" successful .");
}
return true;
}
/**
* @param enable the enable to set
*/
public void setEnable(boolean enable) {
this.enable = enable;
}
/**
* @param enable the enable to set
*/
public void setEnable(boolean enable) {
this.enable = enable;
}
}

View File

@ -31,11 +31,11 @@ import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
public class HttpCertsEntryPoint implements AsyncHandlerInterceptor {
private static final Logger _logger = LoggerFactory.getLogger(HttpHeaderEntryPoint.class);
static String CERTIFICATE_ATTRIBUTE = "javax.servlet.request.X509Certificate";
static String PEER_CERTIFICATES_ATTRIBUTE = "javax.net.ssl.peer_certificates";
private static final Logger _logger = LoggerFactory.getLogger(HttpHeaderEntryPoint.class);
static String CERTIFICATE_ATTRIBUTE = "javax.servlet.request.X509Certificate";
static String PEER_CERTIFICATES_ATTRIBUTE = "javax.net.ssl.peer_certificates";
boolean enable;
@Autowired
@ -43,56 +43,56 @@ public class HttpCertsEntryPoint implements AsyncHandlerInterceptor {
AbstractAuthenticationProvider authenticationProvider ;
@Override
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
if(!enable){
return true;
}
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
if(!enable){
return true;
}
_logger.debug("Certificate Login Start ...");
_logger.debug("Request url : "+ request.getRequestURL());
_logger.debug("Request URI : "+ request.getRequestURI());
_logger.trace("Request ContextPath : "+ request.getContextPath());
_logger.trace("Request ServletPath : "+ request.getServletPath());
_logger.trace("RequestSessionId : "+ request.getRequestedSessionId());
_logger.trace("isRequestedSessionIdValid : "+ request.isRequestedSessionIdValid());
_logger.trace("getSession : "+ request.getSession(false));
X509Certificate[] certificates= (X509Certificate[])request.getAttribute(CERTIFICATE_ATTRIBUTE); // 2.2 spec
if (certificates == null) {
certificates = (X509Certificate[]) request.getAttribute(PEER_CERTIFICATES_ATTRIBUTE); // 2.1 spec
_logger.debug("Certificate Login Start ...");
_logger.debug("Request url : "+ request.getRequestURL());
_logger.debug("Request URI : "+ request.getRequestURI());
_logger.trace("Request ContextPath : "+ request.getContextPath());
_logger.trace("Request ServletPath : "+ request.getServletPath());
_logger.trace("RequestSessionId : "+ request.getRequestedSessionId());
_logger.trace("isRequestedSessionIdValid : "+ request.isRequestedSessionIdValid());
_logger.trace("getSession : "+ request.getSession(false));
X509Certificate[] certificates= (X509Certificate[])request.getAttribute(CERTIFICATE_ATTRIBUTE); // 2.2 spec
if (certificates == null) {
certificates = (X509Certificate[]) request.getAttribute(PEER_CERTIFICATES_ATTRIBUTE); // 2.1 spec
}
for (X509Certificate cert : certificates) {
cert.checkValidity();
_logger.debug("cert validated");
_logger.debug("cert infos {}" , cert.toString());
_logger.debug("Version {}" , cert.getVersion());
_logger.debug("SerialNumber {}" , cert.getSerialNumber().toString(16));
_logger.debug("SubjectDN {}" , cert.getSubjectDN());
_logger.debug("IssuerDN {}" , cert.getIssuerDN());
_logger.debug("NotBefore {}" , cert.getNotBefore());
_logger.debug("SigAlgName {}" , cert.getSigAlgName());
byte[] sign = cert.getSignature();
_logger.debug("Signature ");
for (int j = 0; j < sign.length; j++){
_logger.debug("{} , ",sign[j] );
}
java.security.PublicKey pk = cert.getPublicKey();
byte[] pkenc = pk.getEncoded();
_logger.debug("PublicKey ");
for (int j = 0; j < pkenc.length; j++){
_logger.debug("{} ,",pkenc[j]);
}
}
return true;
for (X509Certificate cert : certificates) {
cert.checkValidity();
_logger.debug("cert validated");
_logger.debug("cert infos {}" , cert.toString());
_logger.debug("Version {}" , cert.getVersion());
_logger.debug("SerialNumber {}" , cert.getSerialNumber().toString(16));
_logger.debug("SubjectDN {}" , cert.getSubjectDN());
_logger.debug("IssuerDN {}" , cert.getIssuerDN());
_logger.debug("NotBefore {}" , cert.getNotBefore());
_logger.debug("SigAlgName {}" , cert.getSigAlgName());
byte[] sign = cert.getSignature();
_logger.debug("Signature ");
for (int j = 0; j < sign.length; j++){
_logger.debug("{} , ",sign[j] );
}
java.security.PublicKey pk = cert.getPublicKey();
byte[] pkenc = pk.getEncoded();
_logger.debug("PublicKey ");
for (int j = 0; j < pkenc.length; j++){
_logger.debug("{} ,",pkenc[j]);
}
}
return true;
}
public HttpCertsEntryPoint(boolean enable, AbstractAuthenticationProvider authenticationProvider) {
super();
this.enable = enable;
this.authenticationProvider = authenticationProvider;
}
public HttpCertsEntryPoint(boolean enable, AbstractAuthenticationProvider authenticationProvider) {
super();
this.enable = enable;
this.authenticationProvider = authenticationProvider;
}
}

View File

@ -33,93 +33,93 @@ import jakarta.servlet.http.HttpServletResponse;
public class HttpHeaderEntryPoint implements AsyncHandlerInterceptor {
private static final Logger _logger = LoggerFactory.getLogger(HttpHeaderEntryPoint.class);
String headerName;
private static final Logger _logger = LoggerFactory.getLogger(HttpHeaderEntryPoint.class);
String headerName;
boolean enable;
@Autowired
@Qualifier("authenticationProvider")
AbstractAuthenticationProvider authenticationProvider ;
String []skipRequestURI={
"/oauth/v20/token",
"/oauth/v10a/request_token",
"/oauth/v10a/access_token"
};
@Override
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
if(!enable){
return true;
}
String requestPath=request.getServletPath();
_logger.trace("HttpHeader Login Start ...");
_logger.trace("Request url : "+ request.getRequestURL());
_logger.trace("Request URI : "+ request.getRequestURI());
_logger.trace("Request ContextPath : "+ request.getContextPath());
_logger.trace("Request ServletPath : "+ request.getServletPath());
_logger.trace("RequestSessionId : "+ request.getRequestedSessionId());
_logger.trace("isRequestedSessionIdValid : "+ request.isRequestedSessionIdValid());
_logger.trace("getSession : "+ request.getSession(false));
for(int i=0;i<skipRequestURI.length;i++){
if(skipRequestURI[i].indexOf(requestPath)>-1){
_logger.trace("skip uri : "+ requestPath);
return true;
}
}
// session not existssession timeoutrecreate new session
if(request.getSession(false) == null) {
_logger.trace("recreate new session .");
request.getSession(true);
}
_logger.trace("getSession.getId : "+ request.getSession().getId());
String httpHeaderUsername = request.getHeader(headerName);
String []skipRequestURI={
"/oauth/v20/token",
"/oauth/v10a/request_token",
"/oauth/v10a/access_token"
};
@Override
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
if(!enable){
return true;
}
String requestPath=request.getServletPath();
_logger.trace("HttpHeader Login Start ...");
_logger.trace("Request url : "+ request.getRequestURL());
_logger.trace("Request URI : "+ request.getRequestURI());
_logger.trace("Request ContextPath : "+ request.getContextPath());
_logger.trace("Request ServletPath : "+ request.getServletPath());
_logger.trace("RequestSessionId : "+ request.getRequestedSessionId());
_logger.trace("isRequestedSessionIdValid : "+ request.isRequestedSessionIdValid());
_logger.trace("getSession : "+ request.getSession(false));
for(int i=0;i<skipRequestURI.length;i++){
if(skipRequestURI[i].indexOf(requestPath)>-1){
_logger.trace("skip uri : "+ requestPath);
return true;
}
}
// session not existssession timeoutrecreate new session
if(request.getSession(false) == null) {
_logger.trace("recreate new session .");
request.getSession(true);
}
_logger.trace("getSession.getId : "+ request.getSession().getId());
String httpHeaderUsername = request.getHeader(headerName);
_logger.trace("HttpHeader username : " + httpHeaderUsername);
if(httpHeaderUsername==null||httpHeaderUsername.equals("")){
_logger.info("Authentication fail HttpHeader is null . ");
return false;
}
boolean isAuthenticated=false;
if(SecurityContextHolder.getContext().getAuthentication() == null) {
_logger.info("Security Authentication is null .");
isAuthenticated=false;
}else {
_logger.info("Security Authentication not null . ");
UsernamePasswordAuthenticationToken authenticationToken =
(UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
String lastSessionUserName = authenticationToken.getPrincipal().toString();
_logger.info("Authentication Principal : " + lastSessionUserName);
if (lastSessionUserName != null && !lastSessionUserName.equals(httpHeaderUsername)) {
isAuthenticated=false;
}else{
isAuthenticated=true;
}
}
if(!isAuthenticated){
LoginCredential loginCredential =new LoginCredential(httpHeaderUsername,"",ConstsLoginType.HTTPHEADER);
_logger.trace("HttpHeader username : " + httpHeaderUsername);
if(httpHeaderUsername==null||httpHeaderUsername.equals("")){
_logger.info("Authentication fail HttpHeader is null . ");
return false;
}
boolean isAuthenticated=false;
if(SecurityContextHolder.getContext().getAuthentication() == null) {
_logger.info("Security Authentication is null .");
isAuthenticated=false;
}else {
_logger.info("Security Authentication not null . ");
UsernamePasswordAuthenticationToken authenticationToken =
(UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
String lastSessionUserName = authenticationToken.getPrincipal().toString();
_logger.info("Authentication Principal : " + lastSessionUserName);
if (lastSessionUserName != null && !lastSessionUserName.equals(httpHeaderUsername)) {
isAuthenticated=false;
}else{
isAuthenticated=true;
}
}
if(!isAuthenticated){
LoginCredential loginCredential =new LoginCredential(httpHeaderUsername,"",ConstsLoginType.HTTPHEADER);
authenticationProvider.authenticate(loginCredential,true);
_logger.info("Authentication "+httpHeaderUsername+" successful .");
}
return true;
}
_logger.info("Authentication "+httpHeaderUsername+" successful .");
}
return true;
}
public HttpHeaderEntryPoint() {
super();
}
public HttpHeaderEntryPoint() {
super();
}
public HttpHeaderEntryPoint(String headerName, boolean enable) {
super();
@ -142,6 +142,6 @@ public class HttpHeaderEntryPoint implements AsyncHandlerInterceptor {
public void setEnable(boolean enable) {
this.enable = enable;
}
}

View File

@ -40,80 +40,80 @@ import com.nimbusds.jwt.SignedJWT;
@RestController
@RequestMapping(value = "/login")
public class HttpJwtEntryPoint {
private static final Logger _logger = LoggerFactory.getLogger(HttpJwtEntryPoint.class);
private static final Logger _logger = LoggerFactory.getLogger(HttpJwtEntryPoint.class);
@Autowired
ApplicationConfig applicationConfig;
@Autowired
AbstractAuthenticationProvider authenticationProvider ;
@Autowired
AuthTokenService authTokenService;
@Autowired
JwtLoginService jwtLoginService;
@RequestMapping(value={"/jwt"}, produces = {MediaType.APPLICATION_JSON_VALUE},method={RequestMethod.GET,RequestMethod.POST})
public Message<AuthJwt> jwt(@RequestParam(value = WebConstants.JWT_TOKEN_PARAMETER, required = true) String jwt) {
try {
//for jwt Login
_logger.debug("jwt : {}" , jwt);
SignedJWT signedJWT = jwtLoginService.jwtTokenValidation(jwt);
if(signedJWT != null) {
String username =signedJWT.getJWTClaimsSet().getSubject();
LoginCredential loginCredential =new LoginCredential(username,"",ConstsLoginType.JWT);
Authentication authentication = authenticationProvider.authenticate(loginCredential,true);
_logger.debug("JWT Logined in , username {}" , username);
AuthJwt authJwt = authTokenService.genAuthJwt(authentication);
return new Message<>(authJwt);
}
}catch(Exception e) {
_logger.error("Exception ",e);
}
return new Message<>(Message.FAIL);
}
/**
* trust same HS512
* @param jwt
* @return
*/
@RequestMapping(value={"/jwt/trust"}, produces = {MediaType.APPLICATION_JSON_VALUE},method={RequestMethod.GET,RequestMethod.POST})
public Message<AuthJwt> jwtTrust(@RequestParam(value = WebConstants.JWT_TOKEN_PARAMETER, required = true) String jwt) {
try {
//for jwt Login
_logger.debug("jwt : {}" , jwt);
ApplicationConfig applicationConfig;
@Autowired
AbstractAuthenticationProvider authenticationProvider ;
@Autowired
AuthTokenService authTokenService;
@Autowired
JwtLoginService jwtLoginService;
@RequestMapping(value={"/jwt"}, produces = {MediaType.APPLICATION_JSON_VALUE},method={RequestMethod.GET,RequestMethod.POST})
public Message<AuthJwt> jwt(@RequestParam(value = WebConstants.JWT_TOKEN_PARAMETER, required = true) String jwt) {
try {
//for jwt Login
_logger.debug("jwt : {}" , jwt);
SignedJWT signedJWT = jwtLoginService.jwtTokenValidation(jwt);
if(signedJWT != null) {
String username =signedJWT.getJWTClaimsSet().getSubject();
LoginCredential loginCredential =new LoginCredential(username,"",ConstsLoginType.JWT);
Authentication authentication = authenticationProvider.authenticate(loginCredential,true);
_logger.debug("JWT Logined in , username {}" , username);
AuthJwt authJwt = authTokenService.genAuthJwt(authentication);
return new Message<>(authJwt);
}
}catch(Exception e) {
_logger.error("Exception ",e);
}
return new Message<>(Message.FAIL);
}
/**
* trust same HS512
* @param jwt
* @return
*/
@RequestMapping(value={"/jwt/trust"}, produces = {MediaType.APPLICATION_JSON_VALUE},method={RequestMethod.GET,RequestMethod.POST})
public Message<AuthJwt> jwtTrust(@RequestParam(value = WebConstants.JWT_TOKEN_PARAMETER, required = true) String jwt) {
try {
//for jwt Login
_logger.debug("jwt : {}" , jwt);
if(authTokenService.validateJwtToken(jwt)) {
String username =authTokenService.resolve(jwt).getSubject();
LoginCredential loginCredential =new LoginCredential(username,"",ConstsLoginType.JWT);
Authentication authentication = authenticationProvider.authenticate(loginCredential,true);
_logger.debug("JWT Logined in , username {}" , username);
AuthJwt authJwt = authTokenService.genAuthJwt(authentication);
return new Message<>(authJwt);
}
}catch(Exception e) {
_logger.error("Exception ",e);
}
return new Message<>(Message.FAIL);
}
if(authTokenService.validateJwtToken(jwt)) {
String username =authTokenService.resolve(jwt).getSubject();
LoginCredential loginCredential =new LoginCredential(username,"",ConstsLoginType.JWT);
Authentication authentication = authenticationProvider.authenticate(loginCredential,true);
_logger.debug("JWT Logined in , username {}" , username);
AuthJwt authJwt = authTokenService.genAuthJwt(authentication);
return new Message<>(authJwt);
}
}catch(Exception e) {
_logger.error("Exception ",e);
}
return new Message<>(Message.FAIL);
}
public void setApplicationConfig(ApplicationConfig applicationConfig) {
this.applicationConfig = applicationConfig;
}
public void setApplicationConfig(ApplicationConfig applicationConfig) {
this.applicationConfig = applicationConfig;
}
public void setAuthenticationProvider(AbstractAuthenticationProvider authenticationProvider) {
this.authenticationProvider = authenticationProvider;
}
public void setAuthenticationProvider(AbstractAuthenticationProvider authenticationProvider) {
this.authenticationProvider = authenticationProvider;
}
public void setJwtLoginService(JwtLoginService jwtLoginService) {
this.jwtLoginService = jwtLoginService;
}
public void setJwtLoginService(JwtLoginService jwtLoginService) {
this.jwtLoginService = jwtLoginService;
}
}

View File

@ -87,11 +87,11 @@ public class JwtLoginService {
signedJWT = SignedJWT.parse(jwt);
if (signedJWT.verify(rsaSSAVerifier)) {
jwtClaimsSet = signedJWT.getJWTClaimsSet();
boolean isIssuerMatches = jwtClaimsSet.getIssuer().equals(getIssuer());
boolean isExpiration = (new DateTime()).isBefore(
jwtClaimsSet.getExpirationTime().getTime());
jwtClaimsSet = signedJWT.getJWTClaimsSet();
boolean isIssuerMatches = jwtClaimsSet.getIssuer().equals(getIssuer());
boolean isExpiration = (new DateTime()).isBefore(
jwtClaimsSet.getExpirationTime().getTime());
_logger.debug("Signed JWT {}" , signedJWT.getPayload());
_logger.debug("Subject is {}" , jwtClaimsSet.getSubject());
_logger.debug("ExpirationTime Validation {}" ,isExpiration);
@ -118,9 +118,9 @@ public class JwtLoginService {
this.jwtSignerValidationService = jwtSignerValidationService;
}
public DefaultJwtSigningAndValidationService getJwtSignerValidationService() {
return jwtSignerValidationService;
}
public DefaultJwtSigningAndValidationService getJwtSignerValidationService() {
return jwtSignerValidationService;
}
public String getIssuer() {
return issuer;

View File

@ -36,78 +36,78 @@ import jakarta.servlet.http.HttpServletResponse;
public class HttpKerberosEntryPoint implements AsyncHandlerInterceptor {
private static final Logger _logger = LoggerFactory.getLogger(HttpKerberosEntryPoint.class);
private static final Logger _logger = LoggerFactory.getLogger(HttpKerberosEntryPoint.class);
boolean enable;
ApplicationConfig applicationConfig;
ApplicationConfig applicationConfig;
AbstractAuthenticationProvider authenticationProvider ;
KerberosService kerberosService;
@Override
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
boolean isAuthenticated= AuthorizationUtils.isAuthenticated();
String kerberosTokenString = request.getParameter(WebConstants.KERBEROS_TOKEN_PARAMETER);
String kerberosUserDomain = request.getParameter(WebConstants.KERBEROS_USERDOMAIN_PARAMETER);
if(!enable
|| isAuthenticated
|| kerberosTokenString == null){
return true;
}
_logger.trace("Kerberos Login Start ...");
_logger.trace("Request url : "+ request.getRequestURL());
_logger.trace("Request URI : "+ request.getRequestURI());
_logger.trace("Request ContextPath : "+ request.getContextPath());
_logger.trace("Request ServletPath : "+ request.getServletPath());
_logger.trace("RequestSessionId : "+ request.getRequestedSessionId());
_logger.trace("isRequestedSessionIdValid : "+ request.isRequestedSessionIdValid());
_logger.trace("getSession : "+ request.getSession(false));
// session not existssession timeoutrecreate new session
if(request.getSession(false) == null) {
_logger.trace("recreate new session .");
request.getSession(true);
}
_logger.trace("getSession.getId : "+ request.getSession().getId());
KerberosService kerberosService;
@Override
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
boolean isAuthenticated= AuthorizationUtils.isAuthenticated();
String kerberosTokenString = request.getParameter(WebConstants.KERBEROS_TOKEN_PARAMETER);
String kerberosUserDomain = request.getParameter(WebConstants.KERBEROS_USERDOMAIN_PARAMETER);
if(!enable
|| isAuthenticated
|| kerberosTokenString == null){
return true;
}
_logger.trace("Kerberos Login Start ...");
_logger.trace("Request url : "+ request.getRequestURL());
_logger.trace("Request URI : "+ request.getRequestURI());
_logger.trace("Request ContextPath : "+ request.getContextPath());
_logger.trace("Request ServletPath : "+ request.getServletPath());
_logger.trace("RequestSessionId : "+ request.getRequestedSessionId());
_logger.trace("isRequestedSessionIdValid : "+ request.isRequestedSessionIdValid());
_logger.trace("getSession : "+ request.getSession(false));
// session not existssession timeoutrecreate new session
if(request.getSession(false) == null) {
_logger.trace("recreate new session .");
request.getSession(true);
}
_logger.trace("getSession.getId : "+ request.getSession().getId());
//for Kerberos Login
_logger.debug("Try Kerberos login ");
_logger.debug("encoder Kerberos Token "+kerberosTokenString);
_logger.debug("kerberos UserDomain "+kerberosUserDomain);
String decoderKerberosToken=null;
for(KerberosProxy kerberosProxy : kerberosService.getKerberosProxys()){
if(kerberosProxy.getUserdomain().equalsIgnoreCase(kerberosUserDomain)){
decoderKerberosToken=ReciprocalUtils.aesDecoder(kerberosTokenString, kerberosProxy.getCrypto());
break;
}
}
_logger.debug("decoder Kerberos Token "+decoderKerberosToken);
KerberosToken kerberosToken=new KerberosToken();
kerberosToken=(KerberosToken)JsonUtils.stringToObject(decoderKerberosToken, kerberosToken);
_logger.debug("Kerberos Token "+kerberosToken);
DateTime notOnOrAfter=DateUtils.toUtcDate(kerberosToken.getNotOnOrAfter());
_logger.debug("Kerberos Token is After Now "+notOnOrAfter.isAfterNow());
if(notOnOrAfter.isAfterNow()){
LoginCredential loginCredential =new LoginCredential(kerberosToken.getPrincipal(),"",ConstsLoginType.KERBEROS);
loginCredential.setProvider(kerberosUserDomain);
//for Kerberos Login
_logger.debug("Try Kerberos login ");
_logger.debug("encoder Kerberos Token "+kerberosTokenString);
_logger.debug("kerberos UserDomain "+kerberosUserDomain);
String decoderKerberosToken=null;
for(KerberosProxy kerberosProxy : kerberosService.getKerberosProxys()){
if(kerberosProxy.getUserdomain().equalsIgnoreCase(kerberosUserDomain)){
decoderKerberosToken=ReciprocalUtils.aesDecoder(kerberosTokenString, kerberosProxy.getCrypto());
break;
}
}
_logger.debug("decoder Kerberos Token "+decoderKerberosToken);
KerberosToken kerberosToken=new KerberosToken();
kerberosToken=(KerberosToken)JsonUtils.stringToObject(decoderKerberosToken, kerberosToken);
_logger.debug("Kerberos Token "+kerberosToken);
DateTime notOnOrAfter=DateUtils.toUtcDate(kerberosToken.getNotOnOrAfter());
_logger.debug("Kerberos Token is After Now "+notOnOrAfter.isAfterNow());
if(notOnOrAfter.isAfterNow()){
LoginCredential loginCredential =new LoginCredential(kerberosToken.getPrincipal(),"",ConstsLoginType.KERBEROS);
loginCredential.setProvider(kerberosUserDomain);
authenticationProvider.authenticate(loginCredential,true);
_logger.debug("Kerberos Logined in , username " + kerberosToken.getPrincipal());
}
return true;
}
_logger.debug("Kerberos Logined in , username " + kerberosToken.getPrincipal());
}
return true;
}
public HttpKerberosEntryPoint() {
super();
}
public HttpKerberosEntryPoint() {
super();
}
public HttpKerberosEntryPoint (boolean enable) {
super();
@ -115,15 +115,15 @@ public class HttpKerberosEntryPoint implements AsyncHandlerInterceptor {
}
public HttpKerberosEntryPoint(AbstractAuthenticationProvider authenticationProvider, KerberosService kerberosService,
ApplicationConfig applicationConfig, boolean enable) {
super();
this.authenticationProvider = authenticationProvider;
this.kerberosService = kerberosService;
this.applicationConfig = applicationConfig;
this.enable = enable;
}
ApplicationConfig applicationConfig, boolean enable) {
super();
this.authenticationProvider = authenticationProvider;
this.kerberosService = kerberosService;
this.applicationConfig = applicationConfig;
this.enable = enable;
}
public boolean isEnable() {
public boolean isEnable() {
return enable;
}
@ -131,14 +131,14 @@ public class HttpKerberosEntryPoint implements AsyncHandlerInterceptor {
this.enable = enable;
}
public void setApplicationConfig(ApplicationConfig applicationConfig) {
this.applicationConfig = applicationConfig;
}
public void setApplicationConfig(ApplicationConfig applicationConfig) {
this.applicationConfig = applicationConfig;
}
public void setAuthenticationProvider(AbstractAuthenticationProvider authenticationProvider) {
this.authenticationProvider = authenticationProvider;
}
public void setAuthenticationProvider(AbstractAuthenticationProvider authenticationProvider) {
this.authenticationProvider = authenticationProvider;
}
}

View File

@ -18,63 +18,63 @@
package org.dromara.maxkey.authn.support.kerberos;
public class KerberosProxy {
String userdomain;
String fullUserdomain;
String crypto;
String redirectUri;
String userdomain;
String fullUserdomain;
String crypto;
String redirectUri;
/**
*
*/
public KerberosProxy() {
super();
}
/**
*
*/
public KerberosProxy() {
super();
}
public String getUserdomain() {
return userdomain;
}
public String getUserdomain() {
return userdomain;
}
public void setUserdomain(String userdomain) {
this.userdomain = userdomain.toUpperCase();
}
public void setUserdomain(String userdomain) {
this.userdomain = userdomain.toUpperCase();
}
public String getFullUserdomain() {
return fullUserdomain;
}
public String getFullUserdomain() {
return fullUserdomain;
}
public void setFullUserdomain(String fullUserdomain) {
this.fullUserdomain = fullUserdomain.toUpperCase();
}
public void setFullUserdomain(String fullUserdomain) {
this.fullUserdomain = fullUserdomain.toUpperCase();
}
public String getCrypto() {
return crypto;
}
public String getCrypto() {
return crypto;
}
public void setCrypto(String crypto) {
this.crypto = crypto;
}
public void setCrypto(String crypto) {
this.crypto = crypto;
}
public String getRedirectUri() {
return redirectUri;
}
public String getRedirectUri() {
return redirectUri;
}
public void setRedirectUri(String redirectUri) {
this.redirectUri = redirectUri;
}
public void setRedirectUri(String redirectUri) {
this.redirectUri = redirectUri;
}
@Override
public String toString() {
return "KerberosProxy [userdomain=" + userdomain + ", fullUserdomain="
+ fullUserdomain + ", crypto=" + crypto
+ ", redirectUri=" + redirectUri + "]";
}
@Override
public String toString() {
return "KerberosProxy [userdomain=" + userdomain + ", fullUserdomain="
+ fullUserdomain + ", crypto=" + crypto
+ ", redirectUri=" + redirectUri + "]";
}
}

View File

@ -20,9 +20,9 @@ package org.dromara.maxkey.authn.support.kerberos;
import java.util.List;
public interface KerberosService {
public List<KerberosProxy> getKerberosProxys();
public String buildKerberosProxys( );
public List<KerberosProxy> getKerberosProxys();
public String buildKerberosProxys( );
}

View File

@ -20,58 +20,58 @@ package org.dromara.maxkey.authn.support.kerberos;
public class KerberosToken {
private String principal;
private String fullPrincipal;
private String notOnOrAfter;
private String userDomain;
private String principal;
private String fullPrincipal;
private String notOnOrAfter;
private String userDomain;
/**
*
*/
public KerberosToken() {
super();
}
/**
*
*/
public KerberosToken() {
super();
}
public String getPrincipal() {
return principal;
}
public String getPrincipal() {
return principal;
}
public void setPrincipal(String principal) {
this.principal = principal;
}
public void setPrincipal(String principal) {
this.principal = principal;
}
public String getFullPrincipal() {
return fullPrincipal;
}
public String getFullPrincipal() {
return fullPrincipal;
}
public void setFullPrincipal(String fullPrincipal) {
this.fullPrincipal = fullPrincipal;
}
public String getNotOnOrAfter() {
return notOnOrAfter;
}
public void setFullPrincipal(String fullPrincipal) {
this.fullPrincipal = fullPrincipal;
}
public String getNotOnOrAfter() {
return notOnOrAfter;
}
public void setNotOnOrAfter(String notOnOrAfter) {
this.notOnOrAfter = notOnOrAfter;
}
public void setNotOnOrAfter(String notOnOrAfter) {
this.notOnOrAfter = notOnOrAfter;
}
public String getUserDomain() {
return userDomain;
}
public String getUserDomain() {
return userDomain;
}
public void setUserDomain(String userDomain) {
this.userDomain = userDomain;
}
public void setUserDomain(String userDomain) {
this.userDomain = userDomain;
}
@Override
public String toString() {
return "KerberosToken [principal=" + principal + ", fullPrincipal="
+ fullPrincipal + ", notOnOrAfter=" + notOnOrAfter
+ ", userDomain=" + userDomain + "]";
}
@Override
public String toString() {
return "KerberosToken [principal=" + principal + ", fullPrincipal="
+ fullPrincipal + ", notOnOrAfter=" + notOnOrAfter
+ ", userDomain=" + userDomain + "]";
}
}

View File

@ -27,30 +27,30 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RemoteKerberosService implements KerberosService{
private static Logger _logger = LoggerFactory.getLogger(RemoteKerberosService.class);
List<KerberosProxy> kerberosProxys;
private static Logger _logger = LoggerFactory.getLogger(RemoteKerberosService.class);
List<KerberosProxy> kerberosProxys;
@Override
public List<KerberosProxy> getKerberosProxys() {
return kerberosProxys;
}
@Override
public List<KerberosProxy> getKerberosProxys() {
return kerberosProxys;
}
public void setKerberosProxys(List<KerberosProxy> kerberosProxys) {
this.kerberosProxys = kerberosProxys;
}
@Override
public String buildKerberosProxys(){
List<Map<String,String>>userDomainUrlList=new ArrayList<Map<String,String>>();
for (KerberosProxy kerberosProxy :kerberosProxys){
Map<String,String> userDomainUrl =new HashMap<String,String>();
userDomainUrl.put("userDomain", kerberosProxy.getUserdomain());
userDomainUrl.put("redirectUri", kerberosProxy.getRedirectUri());
userDomainUrlList.add(userDomainUrl);
}
_logger.debug(""+userDomainUrlList);
String userDomainUrlJson=JsonUtils.toString(userDomainUrlList);
_logger.debug("userDomain Url Json "+userDomainUrlJson);
return userDomainUrlJson;
}
public void setKerberosProxys(List<KerberosProxy> kerberosProxys) {
this.kerberosProxys = kerberosProxys;
}
@Override
public String buildKerberosProxys(){
List<Map<String,String>>userDomainUrlList=new ArrayList<Map<String,String>>();
for (KerberosProxy kerberosProxy :kerberosProxys){
Map<String,String> userDomainUrl =new HashMap<String,String>();
userDomainUrl.put("userDomain", kerberosProxy.getUserdomain());
userDomainUrl.put("redirectUri", kerberosProxy.getRedirectUri());
userDomainUrlList.add(userDomainUrl);
}
_logger.debug(""+userDomainUrlList);
String userDomainUrlJson=JsonUtils.toString(userDomainUrlList);
_logger.debug("userDomain Url Json "+userDomainUrlJson);
return userDomainUrlJson;
}
}

View File

@ -57,10 +57,10 @@ public abstract class AbstractRemeberMeManager {
// end persist
public String createRemeberMe(Authentication authentication,
HttpServletRequest request, HttpServletResponse response) {
HttpServletRequest request, HttpServletResponse response) {
if (applicationConfig.getLoginConfig().isRemeberMe()) {
SignPrincipal principal = ((SignPrincipal)authentication.getPrincipal());
UserInfo userInfo = principal.getUserInfo();
SignPrincipal principal = ((SignPrincipal)authentication.getPrincipal());
UserInfo userInfo = principal.getUserInfo();
_logger.debug("Remeber Me ...");
RemeberMe remeberMe = new RemeberMe();
remeberMe.setId(WebContext.genId());
@ -91,37 +91,37 @@ public abstract class AbstractRemeberMeManager {
}
public RemeberMe resolve(String rememberMeJwt) throws ParseException {
JWTClaimsSet claims = authTokenService.resolve(rememberMeJwt);
RemeberMe remeberMe = new RemeberMe();
remeberMe.setId(claims.getJWTID());
remeberMe.setUsername(claims.getSubject());
return read(remeberMe);
JWTClaimsSet claims = authTokenService.resolve(rememberMeJwt);
RemeberMe remeberMe = new RemeberMe();
remeberMe.setId(claims.getJWTID());
remeberMe.setUsername(claims.getSubject());
return read(remeberMe);
}
public String genRemeberMe(RemeberMe remeberMe ) {
_logger.debug("expiration Time : {}" , remeberMe.getExpirationTime());
JWTClaimsSet remeberMeJwtClaims =new JWTClaimsSet.Builder()
.issuer("")
.subject(remeberMe.getUsername())
.jwtID(remeberMe.getId())
.issueTime(remeberMe.getLastLoginTime())
.expirationTime(remeberMe.getExpirationTime())
.claim("kid", Hmac512Service.MXK_AUTH_JWK)
.build();
return authTokenService.signedJWT(remeberMeJwtClaims);
}
_logger.debug("expiration Time : {}" , remeberMe.getExpirationTime());
JWTClaimsSet remeberMeJwtClaims =new JWTClaimsSet.Builder()
.issuer("")
.subject(remeberMe.getUsername())
.jwtID(remeberMe.getId())
.issueTime(remeberMe.getLastLoginTime())
.expirationTime(remeberMe.getExpirationTime())
.claim("kid", Hmac512Service.MXK_AUTH_JWK)
.build();
return authTokenService.signedJWT(remeberMeJwtClaims);
}
public Integer getValidity() {
return validity;
}
public Integer getValidity() {
return validity;
}
public void setValidity(Integer validity) {
if(validity != 0 ) {
this.validity = validity;
}
}
public void setValidity(Integer validity) {
if(validity != 0 ) {
this.validity = validity;
}
}
}

View File

@ -48,15 +48,15 @@ public class JdbcRemeberMeManager extends AbstractRemeberMeManager {
private final JdbcTemplate jdbcTemplate;
public JdbcRemeberMeManager(
JdbcTemplate jdbcTemplate,
ApplicationConfig applicationConfig,
AuthTokenService authTokenService,
int validity) {
JdbcTemplate jdbcTemplate,
ApplicationConfig applicationConfig,
AuthTokenService authTokenService,
int validity) {
this.jdbcTemplate = jdbcTemplate;
this.applicationConfig = applicationConfig;
this.authTokenService = authTokenService;
if(validity != 0) {
this.validity = validity;
this.validity = validity;
}
}
@ -64,18 +64,18 @@ public class JdbcRemeberMeManager extends AbstractRemeberMeManager {
public void save(RemeberMe remeberMe) {
jdbcTemplate.update(DEFAULT_DEFAULT_INSERT_STATEMENT,
new Object[] {
remeberMe.getId(),
remeberMe.getUserId(),
remeberMe.getUsername(),
remeberMe.getLastLoginTime(),
remeberMe.getExpirationTime()},
remeberMe.getId(),
remeberMe.getUserId(),
remeberMe.getUsername(),
remeberMe.getLastLoginTime(),
remeberMe.getExpirationTime()},
new int[] {
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.TIMESTAMP,
Types.TIMESTAMP
});
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.TIMESTAMP,
Types.TIMESTAMP
});
}
@Override
@ -92,7 +92,7 @@ public class JdbcRemeberMeManager extends AbstractRemeberMeManager {
public RemeberMe read(RemeberMe remeberMe) {
List<RemeberMe> listRemeberMe = jdbcTemplate.query(DEFAULT_DEFAULT_SELECT_STATEMENT,
new RowMapper<RemeberMe>() {
@Override
@Override
public RemeberMe mapRow(ResultSet rs, int rowNum) throws SQLException {
RemeberMe remeberMe = new RemeberMe();
remeberMe.setId(rs.getString(1));

View File

@ -35,10 +35,10 @@ public class RemeberMe implements Serializable {
Date expirationTime;
public RemeberMe() {
super();
}
super();
}
public String getId() {
public String getId() {
return id;
}
@ -47,14 +47,14 @@ public class RemeberMe implements Serializable {
}
public String getUserId() {
return userId;
}
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUsername() {
public String getUsername() {
return username;
}
@ -63,35 +63,35 @@ public class RemeberMe implements Serializable {
}
public Date getLastLoginTime() {
return lastLoginTime;
}
return lastLoginTime;
}
public void setLastLoginTime(Date lastLoginTime) {
this.lastLoginTime = lastLoginTime;
}
public void setLastLoginTime(Date lastLoginTime) {
this.lastLoginTime = lastLoginTime;
}
public Date getExpirationTime() {
return expirationTime;
}
public Date getExpirationTime() {
return expirationTime;
}
public void setExpirationTime(Date expirationTime) {
this.expirationTime = expirationTime;
}
public void setExpirationTime(Date expirationTime) {
this.expirationTime = expirationTime;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("RemeberMe [id=");
builder.append(id);
builder.append(", userId=");
builder.append(userId);
builder.append(", username=");
builder.append(username);
builder.append(", lastLoginTime=");
builder.append(lastLoginTime);
builder.append(", expirationTime=");
builder.append(expirationTime);
builder.append("]");
return builder.toString();
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("RemeberMe [id=");
builder.append(id);
builder.append(", userId=");
builder.append(userId);
builder.append(", username=");
builder.append(username);
builder.append(", lastLoginTime=");
builder.append(lastLoginTime);
builder.append(", expirationTime=");
builder.append(expirationTime);
builder.append("]");
return builder.toString();
}
}

View File

@ -24,24 +24,24 @@ import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
public class RemeberMeManagerFactory {
private static final Logger _logger =
private static final Logger _logger =
LoggerFactory.getLogger(RemeberMeManagerFactory.class);
public AbstractRemeberMeManager getService(
int persistence,
JdbcTemplate jdbcTemplate,
RedisConnectionFactory redisConnFactory){
AbstractRemeberMeManager remeberMeService = null;
if (persistence == ConstsPersistence.INMEMORY) {
remeberMeService = new InMemoryRemeberMeManager();
_logger.debug("InMemoryRemeberMeService");
} else if (persistence == ConstsPersistence.JDBC) {
//remeberMeService = new JdbcRemeberMeService(jdbcTemplate);
_logger.debug("JdbcRemeberMeService not support ");
} else if (persistence == ConstsPersistence.REDIS) {
_logger.debug("RedisRemeberMeService not support ");
}
return remeberMeService;
}
public AbstractRemeberMeManager getService(
int persistence,
JdbcTemplate jdbcTemplate,
RedisConnectionFactory redisConnFactory){
AbstractRemeberMeManager remeberMeService = null;
if (persistence == ConstsPersistence.INMEMORY) {
remeberMeService = new InMemoryRemeberMeManager();
_logger.debug("InMemoryRemeberMeService");
} else if (persistence == ConstsPersistence.JDBC) {
//remeberMeService = new JdbcRemeberMeService(jdbcTemplate);
_logger.debug("JdbcRemeberMeService not support ");
} else if (persistence == ConstsPersistence.REDIS) {
_logger.debug("RedisRemeberMeService not support ");
}
return remeberMeService;
}
}

View File

@ -34,55 +34,55 @@ import jakarta.servlet.http.HttpServletResponse;
public class HttpWsFederationEntryPoint implements AsyncHandlerInterceptor {
private static final Logger _logger = LoggerFactory.getLogger(HttpWsFederationEntryPoint.class);
private static final Logger _logger = LoggerFactory.getLogger(HttpWsFederationEntryPoint.class);
boolean enable;
ApplicationConfig applicationConfig;
ApplicationConfig applicationConfig;
AbstractAuthenticationProvider authenticationProvider ;
WsFederationService wsFederationService;
@Override
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
boolean isAuthenticated= AuthorizationUtils.isAuthenticated();
String wsFederationWA = request.getParameter(WsFederationConstants.WA);
String wsFederationWResult = request.getParameter(WsFederationConstants.WRESULT);
if(!enable
|| isAuthenticated
|| !applicationConfig.getLoginConfig().isWsFederation()
|| wsFederationWA == null){
return true;
}
_logger.trace("WsFederation Login Start ...");
_logger.trace("Request url : "+ request.getRequestURL());
_logger.trace("Request URI : "+ request.getRequestURI());
_logger.trace("Request ContextPath : "+ request.getContextPath());
_logger.trace("Request ServletPath : "+ request.getServletPath());
_logger.trace("RequestSessionId : "+ request.getRequestedSessionId());
_logger.trace("isRequestedSessionIdValid : "+ request.isRequestedSessionIdValid());
_logger.trace("getSession : "+ request.getSession(false));
// session not existssession timeoutrecreate new session
if(request.getSession(false) == null) {
_logger.trace("recreate new session .");
request.getSession(true);
}
_logger.trace("getSession.getId : "+ request.getSession().getId());
WsFederationService wsFederationService;
@Override
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
boolean isAuthenticated= AuthorizationUtils.isAuthenticated();
String wsFederationWA = request.getParameter(WsFederationConstants.WA);
String wsFederationWResult = request.getParameter(WsFederationConstants.WRESULT);
if(!enable
|| isAuthenticated
|| !applicationConfig.getLoginConfig().isWsFederation()
|| wsFederationWA == null){
return true;
}
_logger.trace("WsFederation Login Start ...");
_logger.trace("Request url : "+ request.getRequestURL());
_logger.trace("Request URI : "+ request.getRequestURI());
_logger.trace("Request ContextPath : "+ request.getContextPath());
_logger.trace("Request ServletPath : "+ request.getServletPath());
_logger.trace("RequestSessionId : "+ request.getRequestedSessionId());
_logger.trace("isRequestedSessionIdValid : "+ request.isRequestedSessionIdValid());
_logger.trace("getSession : "+ request.getSession(false));
// session not existssession timeoutrecreate new session
if(request.getSession(false) == null) {
_logger.trace("recreate new session .");
request.getSession(true);
}
_logger.trace("getSession.getId : "+ request.getSession().getId());
//for WsFederation Login
_logger.debug("WsFederation : " + wsFederationWA +" , wsFederationWResult : " + wsFederationWResult);
if(applicationConfig.getLoginConfig().isWsFederation()
&& StringUtils.isNotEmpty(wsFederationWA)
&& wsFederationWA.equalsIgnoreCase(WsFederationConstants.WSIGNIN)){
_logger.debug("wresult : {}"+wsFederationWResult);
//for WsFederation Login
_logger.debug("WsFederation : " + wsFederationWA +" , wsFederationWResult : " + wsFederationWResult);
if(applicationConfig.getLoginConfig().isWsFederation()
&& StringUtils.isNotEmpty(wsFederationWA)
&& wsFederationWA.equalsIgnoreCase(WsFederationConstants.WSIGNIN)){
_logger.debug("wresult : {}"+wsFederationWResult);
final String wctx = request.getParameter(WsFederationConstants.WCTX);
_logger.debug("wctx : {}"+ wctx);
final String wctx = request.getParameter(WsFederationConstants.WCTX);
_logger.debug("wctx : {}"+ wctx);
// create credentials
final AssertionImpl assertion = WsFederationUtils.parseTokenFromString(wsFederationWResult);
@ -91,14 +91,14 @@ public class HttpWsFederationEntryPoint implements AsyncHandlerInterceptor {
final WsFederationCredential wsFederationCredential = WsFederationUtils.createCredentialFromToken(assertion);
if (wsFederationCredential != null && wsFederationCredential.isValid(wsFederationService.getWsFederationConfiguration().getRelyingParty(),
wsFederationService.getWsFederationConfiguration().getIdentifier(),
wsFederationService.getWsFederationConfiguration().getTolerance())) {
wsFederationService.getWsFederationConfiguration().getIdentifier(),
wsFederationService.getWsFederationConfiguration().getTolerance())) {
//Give the library user a chance to change the attributes as necessary
if (wsFederationService.getWsFederationConfiguration().getAttributeMutator() != null) {
wsFederationService.getWsFederationConfiguration().getAttributeMutator().modifyAttributes(
wsFederationCredential.getAttributes(),
wsFederationService.getWsFederationConfiguration().getUpnSuffix());
wsFederationService.getWsFederationConfiguration().getAttributeMutator().modifyAttributes(
wsFederationCredential.getAttributes(),
wsFederationService.getWsFederationConfiguration().getUpnSuffix());
}
LoginCredential loginCredential =new LoginCredential(
wsFederationCredential.getAttributes().get("").toString(),"",ConstsLoginType.WSFEDERATION);
@ -110,14 +110,14 @@ public class HttpWsFederationEntryPoint implements AsyncHandlerInterceptor {
} else {
_logger.error("WS Requested Security Token is blank or the signature is not valid.");
}
}
return true;
}
}
return true;
}
public HttpWsFederationEntryPoint() {
super();
}
public HttpWsFederationEntryPoint() {
super();
}
public HttpWsFederationEntryPoint (boolean enable) {
super();
@ -125,15 +125,15 @@ public class HttpWsFederationEntryPoint implements AsyncHandlerInterceptor {
}
public HttpWsFederationEntryPoint(AbstractAuthenticationProvider authenticationProvider, WsFederationService wsFederationService,
ApplicationConfig applicationConfig, boolean enable) {
super();
this.authenticationProvider = authenticationProvider;
this.wsFederationService = wsFederationService;
this.applicationConfig = applicationConfig;
this.enable = enable;
}
ApplicationConfig applicationConfig, boolean enable) {
super();
this.authenticationProvider = authenticationProvider;
this.wsFederationService = wsFederationService;
this.applicationConfig = applicationConfig;
this.enable = enable;
}
public boolean isEnable() {
public boolean isEnable() {
return enable;
}
@ -141,18 +141,18 @@ public class HttpWsFederationEntryPoint implements AsyncHandlerInterceptor {
this.enable = enable;
}
public void setApplicationConfig(ApplicationConfig applicationConfig) {
this.applicationConfig = applicationConfig;
}
public void setApplicationConfig(ApplicationConfig applicationConfig) {
this.applicationConfig = applicationConfig;
}
public void setAuthenticationProvider(AbstractAuthenticationProvider authenticationProvider) {
this.authenticationProvider = authenticationProvider;
}
public void setAuthenticationProvider(AbstractAuthenticationProvider authenticationProvider) {
this.authenticationProvider = authenticationProvider;
}
public void setWsFederationService(WsFederationService wsFederationService) {
this.wsFederationService = wsFederationService;
}
public void setWsFederationService(WsFederationService wsFederationService) {
this.wsFederationService = wsFederationService;
}
}

View File

@ -31,7 +31,7 @@ import java.util.List;
*
*/
public final class WsFederationConfiguration {
@NotNull
private String identifier;
@ -57,44 +57,44 @@ public final class WsFederationConfiguration {
private String logoutUrl;
public String getIdentifier() {
return identifier;
}
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getUrl() {
return url;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPrincipal() {
return principal;
}
public String getPrincipal() {
return principal;
}
public void setPrincipal(String principal) {
this.principal = principal;
}
public void setPrincipal(String principal) {
this.principal = principal;
}
public String getRelyingParty() {
return relyingParty;
}
public String getRelyingParty() {
return relyingParty;
}
public void setRelyingParty(String relyingParty) {
this.relyingParty = relyingParty;
}
public void setRelyingParty(String relyingParty) {
this.relyingParty = relyingParty;
}
public List<BasicX509Credential> getSigningWallet() {
return signingWallet;
}
public List<BasicX509Credential> getSigningWallet() {
return signingWallet;
}
public void setSigningWallet(List<BasicX509Credential> signingWallet) {
this.signingWallet = signingWallet;
}
public void setSigningWallet(List<BasicX509Credential> signingWallet) {
this.signingWallet = signingWallet;
}
/**
* gets the signing certificates.
@ -105,7 +105,7 @@ public final class WsFederationConfiguration {
return this.signingWallet;
}
/**
/**
* sets the signing certs.
*
* @param signingCertificateFiles a list of certificate files to read in.
@ -158,20 +158,20 @@ public final class WsFederationConfiguration {
this.attributeMutator = attributeMutator;
}
public String getUpnSuffix() {
return upnSuffix;
}
public String getUpnSuffix() {
return upnSuffix;
}
public void setUpnSuffix(String upnSuffix) {
this.upnSuffix = upnSuffix;
}
public void setUpnSuffix(String upnSuffix) {
this.upnSuffix = upnSuffix;
}
public String getLogoutUrl() {
return logoutUrl;
}
public String getLogoutUrl() {
return logoutUrl;
}
public void setLogoutUrl(String logoutUrl) {
this.logoutUrl = logoutUrl;
}
public void setLogoutUrl(String logoutUrl) {
this.logoutUrl = logoutUrl;
}
}

View File

@ -18,14 +18,14 @@
package org.dromara.maxkey.authn.support.wsfederation;
public class WsFederationConstants {
public static final String LOCALE = "locale";
public static final String METHOD = "method";
public static final String PROVIDERURL = "WsFederationIdentityProviderUrl";
public static final String QUERYSTRING = "?wa=wsignin1.0&wtrealm=";
public static final String SERVICE = "service";
public static final String THEME = "theme";
public static final String WA = "wa";
public static final String WCTX = "wctx";
public static final String WRESULT = "wresult";
public static final String WSIGNIN = "wsignin1.0";
public static final String LOCALE = "locale";
public static final String METHOD = "method";
public static final String PROVIDERURL = "WsFederationIdentityProviderUrl";
public static final String QUERYSTRING = "?wa=wsignin1.0&wtrealm=";
public static final String SERVICE = "service";
public static final String THEME = "theme";
public static final String WA = "wa";
public static final String WCTX = "wctx";
public static final String WRESULT = "wresult";
public static final String WSIGNIN = "wsignin1.0";
}

View File

@ -18,6 +18,6 @@
package org.dromara.maxkey.authn.support.wsfederation;
public interface WsFederationService {
public WsFederationConfiguration getWsFederationConfiguration();
public WsFederationConfiguration getWsFederationConfiguration();
}

View File

@ -22,20 +22,20 @@ import org.slf4j.LoggerFactory;
public class WsFederationServiceImpl implements WsFederationService{
static final Logger _logger = LoggerFactory.getLogger(WsFederationServiceImpl.class);
private WsFederationConfiguration wsFederationConfiguration;
static final Logger _logger = LoggerFactory.getLogger(WsFederationServiceImpl.class);
private WsFederationConfiguration wsFederationConfiguration;
public void setWsFederationConfiguration(
WsFederationConfiguration wsFederationConfiguration) {
this.wsFederationConfiguration = wsFederationConfiguration;
}
public void setWsFederationConfiguration(
WsFederationConfiguration wsFederationConfiguration) {
this.wsFederationConfiguration = wsFederationConfiguration;
}
@Override
public WsFederationConfiguration getWsFederationConfiguration() {
return wsFederationConfiguration;
}
@Override
public WsFederationConfiguration getWsFederationConfiguration() {
return wsFederationConfiguration;
}
}

View File

@ -55,102 +55,102 @@ public class AuthnProviderAutoConfiguration {
@Bean
AbstractAuthenticationProvider authenticationProvider(
NormalAuthenticationProvider normalAuthenticationProvider,
MobileAuthenticationProvider mobileAuthenticationProvider,
TrustedAuthenticationProvider trustedAuthenticationProvider,
ScanCodeAuthenticationProvider scanCodeAuthenticationProvider,
AppAuthenticationProvider appAuthenticationProvider,
TwoFactorAuthenticationProvider twoFactorAuthenticationProvider
) {
AuthenticationProviderFactory authenticationProvider = new AuthenticationProviderFactory();
authenticationProvider.addAuthenticationProvider(normalAuthenticationProvider);
authenticationProvider.addAuthenticationProvider(mobileAuthenticationProvider);
authenticationProvider.addAuthenticationProvider(trustedAuthenticationProvider);
authenticationProvider.addAuthenticationProvider(scanCodeAuthenticationProvider);
authenticationProvider.addAuthenticationProvider(appAuthenticationProvider);
NormalAuthenticationProvider normalAuthenticationProvider,
MobileAuthenticationProvider mobileAuthenticationProvider,
TrustedAuthenticationProvider trustedAuthenticationProvider,
ScanCodeAuthenticationProvider scanCodeAuthenticationProvider,
AppAuthenticationProvider appAuthenticationProvider,
TwoFactorAuthenticationProvider twoFactorAuthenticationProvider
) {
AuthenticationProviderFactory authenticationProvider = new AuthenticationProviderFactory();
authenticationProvider.addAuthenticationProvider(normalAuthenticationProvider);
authenticationProvider.addAuthenticationProvider(mobileAuthenticationProvider);
authenticationProvider.addAuthenticationProvider(trustedAuthenticationProvider);
authenticationProvider.addAuthenticationProvider(scanCodeAuthenticationProvider);
authenticationProvider.addAuthenticationProvider(appAuthenticationProvider);
//二次认证
authenticationProvider.addAuthenticationProvider(twoFactorAuthenticationProvider);
return authenticationProvider;
//二次认证
authenticationProvider.addAuthenticationProvider(twoFactorAuthenticationProvider);
return authenticationProvider;
}
@Bean
NormalAuthenticationProvider normalAuthenticationProvider(
AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig,
SessionManager sessionManager,
AuthTokenService authTokenService
) {
_logger.debug("init authentication Provider .");
return new NormalAuthenticationProvider(
authenticationRealm,
applicationConfig,
sessionManager,
authTokenService
);
AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig,
SessionManager sessionManager,
AuthTokenService authTokenService
) {
_logger.debug("init authentication Provider .");
return new NormalAuthenticationProvider(
authenticationRealm,
applicationConfig,
sessionManager,
authTokenService
);
}
@Bean
ScanCodeAuthenticationProvider scanCodeAuthenticationProvider(
AbstractAuthenticationRealm authenticationRealm,
SessionManager sessionManager
) {
return new ScanCodeAuthenticationProvider(
authenticationRealm,
sessionManager
);
}
@Bean
ScanCodeAuthenticationProvider scanCodeAuthenticationProvider(
AbstractAuthenticationRealm authenticationRealm,
SessionManager sessionManager
) {
return new ScanCodeAuthenticationProvider(
authenticationRealm,
sessionManager
);
}
@Bean
AppAuthenticationProvider appAuthenticationProvider(
AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig,
SessionManager sessionManager,
AuthTokenService authTokenService
) {
return new AppAuthenticationProvider(
authenticationRealm,
applicationConfig,
sessionManager,
authTokenService
);
}
@Bean
AppAuthenticationProvider appAuthenticationProvider(
AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig,
SessionManager sessionManager,
AuthTokenService authTokenService
) {
return new AppAuthenticationProvider(
authenticationRealm,
applicationConfig,
sessionManager,
authTokenService
);
}
@Bean
MobileAuthenticationProvider mobileAuthenticationProvider(
AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig,
SmsOtpAuthnService smsAuthnService,
SessionManager sessionManager
) {
_logger.debug("init Mobile authentication Provider .");
return new MobileAuthenticationProvider(
authenticationRealm,
applicationConfig,
smsAuthnService,
sessionManager
);
AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig,
SmsOtpAuthnService smsAuthnService,
SessionManager sessionManager
) {
_logger.debug("init Mobile authentication Provider .");
return new MobileAuthenticationProvider(
authenticationRealm,
applicationConfig,
smsAuthnService,
sessionManager
);
}
@Bean
TrustedAuthenticationProvider trustedAuthenticationProvider(
AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig,
SessionManager sessionManager
) {
_logger.debug("init Mobile authentication Provider .");
return new TrustedAuthenticationProvider(
authenticationRealm,
applicationConfig,
sessionManager
);
AbstractAuthenticationRealm authenticationRealm,
ApplicationConfig applicationConfig,
SessionManager sessionManager
) {
_logger.debug("init Mobile authentication Provider .");
return new TrustedAuthenticationProvider(
authenticationRealm,
applicationConfig,
sessionManager
);
}
@Bean
PasswordPolicyValidatorService passwordPolicyValidatorService(
CnfPasswordPolicyService cnfPasswordPolicyService,
MessageSource messageSource) {
CnfPasswordPolicyService cnfPasswordPolicyService,
MessageSource messageSource) {
return new PasswordPolicyValidatorServiceImpl(cnfPasswordPolicyService,messageSource);
}
@ -165,14 +165,14 @@ public class AuthnProviderAutoConfiguration {
ApplicationConfig applicationConfig,
AuthTokenService authTokenService,
JdbcTemplate jdbcTemplate) {
_logger.trace("init RemeberMeManager , validity {}." , validity);
_logger.trace("init RemeberMeManager , validity {}." , validity);
return new JdbcRemeberMeManager(
jdbcTemplate,applicationConfig,authTokenService,validity);
jdbcTemplate,applicationConfig,authTokenService,validity);
}
@Bean
TwoFactorAuthenticationProvider twoFactorAuthenticationProvider(
AbstractAuthenticationRealm authenticationRealm,
AbstractAuthenticationRealm authenticationRealm,
SessionManager sessionManager,
LoginService loginService,
AuthTokenService authTokenService,
@ -180,37 +180,37 @@ public class AuthnProviderAutoConfiguration {
TwoFactorTotpAuthenticationProvider twoFactorTotpAuthenticationProvider,
TwoFactorMobileAuthenticationProvider twoFactorMobileAuthenticationProvider,
TwoFactorEmailAuthenticationProvider twoFactorEmailAuthenticationProvider) {
_logger.debug("init TwoFactor authentication Provider .");
TwoFactorAuthenticationProvider twoFactorProvider =new TwoFactorAuthenticationProvider(
authenticationRealm,
sessionManager,
loginService,
authTokenService
);
twoFactorProvider.addProvider(ConstsTwoFactor.TOTP, twoFactorTotpAuthenticationProvider);
twoFactorProvider.addProvider(ConstsTwoFactor.EMAIL, twoFactorEmailAuthenticationProvider);
twoFactorProvider.addProvider(ConstsTwoFactor.SMS, twoFactorMobileAuthenticationProvider);
return twoFactorProvider;
_logger.debug("init TwoFactor authentication Provider .");
TwoFactorAuthenticationProvider twoFactorProvider =new TwoFactorAuthenticationProvider(
authenticationRealm,
sessionManager,
loginService,
authTokenService
);
twoFactorProvider.addProvider(ConstsTwoFactor.TOTP, twoFactorTotpAuthenticationProvider);
twoFactorProvider.addProvider(ConstsTwoFactor.EMAIL, twoFactorEmailAuthenticationProvider);
twoFactorProvider.addProvider(ConstsTwoFactor.SMS, twoFactorMobileAuthenticationProvider);
return twoFactorProvider;
}
@Bean
TwoFactorTotpAuthenticationProvider twoFactorTotpAuthenticationProvider(@Qualifier("tfaOtpAuthn") AbstractOtpAuthn tfaOtpAuthn,
AbstractAuthenticationRealm authenticationRealm) {
_logger.debug("init TwoFactor authentication Provider .");
return new TwoFactorTotpAuthenticationProvider(authenticationRealm,tfaOtpAuthn);
AbstractAuthenticationRealm authenticationRealm) {
_logger.debug("init TwoFactor authentication Provider .");
return new TwoFactorTotpAuthenticationProvider(authenticationRealm,tfaOtpAuthn);
}
@Bean
TwoFactorMobileAuthenticationProvider twoFactorMobileAuthenticationProvider(SmsOtpAuthnService smsOtpAuthnService) {
_logger.debug("init TwoFactor Mobile authentication Provider .");
return new TwoFactorMobileAuthenticationProvider(smsOtpAuthnService);
_logger.debug("init TwoFactor Mobile authentication Provider .");
return new TwoFactorMobileAuthenticationProvider(smsOtpAuthnService);
}
@Bean
TwoFactorEmailAuthenticationProvider twoFactorEmailAuthenticationProvider(MailOtpAuthnService mailOtpAuthnService) {
_logger.debug("init TwoFactor Email authentication Provider .");
return new TwoFactorEmailAuthenticationProvider(mailOtpAuthnService);
_logger.debug("init TwoFactor Email authentication Provider .");
return new TwoFactorEmailAuthenticationProvider(mailOtpAuthnService);
}
}

View File

@ -28,41 +28,41 @@ import com.github.benmanes.caffeine.cache.Caffeine;
public class InMemoryMomentaryService implements MomentaryService{
private static final Logger _logger = LoggerFactory.getLogger(InMemoryMomentaryService.class);
protected static Cache<String, Object> momentaryStore =
Caffeine.newBuilder()
.expireAfterWrite(5, TimeUnit.MINUTES)
.maximumSize(200000)
.build();
public InMemoryMomentaryService() {
protected static Cache<String, Object> momentaryStore =
Caffeine.newBuilder()
.expireAfterWrite(5, TimeUnit.MINUTES)
.maximumSize(200000)
.build();
public InMemoryMomentaryService() {
super();
}
@Override
public void put(String sessionId , String name, Object value){
String sessionKey = getSessionKey(sessionId , name);
_logger.trace("key {}, value {}",sessionKey,value);
momentaryStore.put(sessionKey, value);
}
String sessionKey = getSessionKey(sessionId , name);
_logger.trace("key {}, value {}",sessionKey,value);
momentaryStore.put(sessionKey, value);
}
@Override
public Object remove(String sessionId , String name) {
String sessionKey = getSessionKey(sessionId , name);
Object value = momentaryStore.getIfPresent(sessionKey);
momentaryStore.invalidate(sessionKey);
_logger.trace("key {}, value {}",sessionKey,value);
return value;
}
@Override
public Object remove(String sessionId , String name) {
String sessionKey = getSessionKey(sessionId , name);
Object value = momentaryStore.getIfPresent(sessionKey);
momentaryStore.invalidate(sessionKey);
_logger.trace("key {}, value {}",sessionKey,value);
return value;
}
@Override
public Object get(String sessionId , String name) {
String sessionKey = getSessionKey(sessionId , name);
_logger.trace("key {}",sessionKey);
return momentaryStore.getIfPresent(sessionKey);
String sessionKey = getSessionKey(sessionId , name);
_logger.trace("key {}",sessionKey);
return momentaryStore.getIfPresent(sessionKey);
}
private String getSessionKey(String sessionId , String name) {
return sessionId + "_" + name;
return sessionId + "_" + name;
}
}

View File

@ -19,7 +19,7 @@ package org.dromara.maxkey.persistence.cache;
public interface MomentaryService {
public void put(String sessionId , String name, Object value);
public void put(String sessionId , String name, Object value);
public Object get(String sessionId , String name);

View File

@ -25,41 +25,41 @@ import org.slf4j.LoggerFactory;
public class RedisMomentaryService implements MomentaryService {
private static final Logger _logger = LoggerFactory.getLogger(RedisMomentaryService.class);
protected int validitySeconds = 60 * 5; //default 5 minutes.
RedisConnectionFactory connectionFactory;
public static final String PREFIX = "mxk:momentary:";
/**
* @param connectionFactory
*/
public RedisMomentaryService(
RedisConnectionFactory connectionFactory) {
super();
this.connectionFactory = connectionFactory;
}
/**
*
*/
public RedisMomentaryService() {
}
protected int validitySeconds = 60 * 5; //default 5 minutes.
RedisConnectionFactory connectionFactory;
public static final String PREFIX = "mxk:momentary:";
/**
* @param connectionFactory
*/
public RedisMomentaryService(
RedisConnectionFactory connectionFactory) {
super();
this.connectionFactory = connectionFactory;
}
/**
*
*/
public RedisMomentaryService() {
}
public void setConnectionFactory(RedisConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
public void setConnectionFactory(RedisConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
@Override
public void put(String sessionId , String name, Object value){
RedisConnection conn = connectionFactory.getConnection();
String sessionKey = getSessionKey(sessionId , name);
conn.setexObject(sessionKey, validitySeconds, value);
_logger.trace("key {}, validitySeconds {}, value {}",sessionKey,validitySeconds,value);
conn.close();
}
@Override
public void put(String sessionId , String name, Object value){
RedisConnection conn = connectionFactory.getConnection();
String sessionKey = getSessionKey(sessionId , name);
conn.setexObject(sessionKey, validitySeconds, value);
_logger.trace("key {}, validitySeconds {}, value {}",sessionKey,validitySeconds,value);
conn.close();
}
@Override
public Object get(String sessionId , String name) {
@ -71,19 +71,19 @@ public class RedisMomentaryService implements MomentaryService {
return value;
}
@Override
public Object remove(String sessionId, String name) {
RedisConnection conn = connectionFactory.getConnection();
String sessionKey = getSessionKey(sessionId , name);
@Override
public Object remove(String sessionId, String name) {
RedisConnection conn = connectionFactory.getConnection();
String sessionKey = getSessionKey(sessionId , name);
Object value = conn.getObject(sessionKey);
conn.delete(getSessionKey(sessionId , name));
conn.close();
_logger.trace("key {}, value {}",sessionKey,value);
return value;
}
}
private String getSessionKey(String sessionId , String name) {
return PREFIX + sessionId + name;
return PREFIX + sessionId + name;
}
}

View File

@ -28,146 +28,146 @@ import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
public class RedisConnection {
private static final Logger _logger = LoggerFactory.getLogger(RedisConnection.class);
Jedis conn ;
RedisConnectionFactory connectionFactory;
Pipeline pipeline ;
public RedisConnection() {
}
public RedisConnection(RedisConnectionFactory connectionFactory) {
this.conn=connectionFactory.open();
this.connectionFactory=connectionFactory;
}
private static final Logger _logger = LoggerFactory.getLogger(RedisConnection.class);
Jedis conn ;
RedisConnectionFactory connectionFactory;
Pipeline pipeline ;
public RedisConnection() {
}
public RedisConnection(RedisConnectionFactory connectionFactory) {
this.conn=connectionFactory.open();
this.connectionFactory=connectionFactory;
}
/**
* @param key
* @param value
*/
public void set(String key, String value){
conn.set(key, value);
}
/**
* @param key
* @param value
*/
public void set(String key, String value){
conn.set(key, value);
}
/**
* @param key
* @param value
*/
public void setObject(String key, Object value){
if(value instanceof Serializable) {
set(key, ObjectTransformer.serialize((Serializable)value));
}else {
_logger.error("value must implements of Serializable .");
}
}
public void setexObject(String key,int seconds, Object value){
if(value instanceof Serializable) {
setex(key, seconds, ObjectTransformer.serialize((Serializable)value));
}else {
_logger.error("value must implements of Serializable .");
}
}
/**
* @param key
* @param seconds
* @param value
*/
public void setex(String key,long seconds, String value){
_logger.trace("setex key {} ..." , key);
if(seconds==0){
conn.setex(key, RedisDefaultConfig.DEFAULT_LIFETIME, value);
}else{
conn.setex(key, seconds, value);
}
_logger.trace("setex successful .");
}
/**
* @param key
* @return String
*/
public String get(String key){
_logger.trace("get key {} ..." , key);
String value = null;
if(key != null){
value = conn.get(key);
}
return value;
}
/**
* @param key
* @return String
*/
public <T> T getObject(String key){
String value = null;
if(key != null){
value = get(key);
if(value!=null){
return ObjectTransformer.deserialize(value);
}
}
return null;
}
public void expire(String key,long seconds){
_logger.trace("expire key {} , {}" , key , seconds);
conn.expire(key, seconds);
}
public void delete(String key){
_logger.trace("del key {}" , key);
conn.del(key);
}
public void rPush(String key, Serializable object){
conn.rpush(key, ObjectTransformer.serialize(object));
}
public long lRem(String key,int count,String value){
return conn.lrem(key, count, value);
}
public List<String> lRange(String key,int start,int end){
return conn.lrange(key, start, end);
}
public void openPipeline(){
this.pipeline=conn.pipelined();
}
public List<Object> closePipeline(){
return pipeline.syncAndReturnAll();
}
/**
/**
* @param key
* @param value
*/
public void setObject(String key, Object value){
if(value instanceof Serializable) {
set(key, ObjectTransformer.serialize((Serializable)value));
}else {
_logger.error("value must implements of Serializable .");
}
}
public void setexObject(String key,int seconds, Object value){
if(value instanceof Serializable) {
setex(key, seconds, ObjectTransformer.serialize((Serializable)value));
}else {
_logger.error("value must implements of Serializable .");
}
}
/**
* @param key
* @param seconds
* @param value
*/
public void setex(String key,long seconds, String value){
_logger.trace("setex key {} ..." , key);
if(seconds==0){
conn.setex(key, RedisDefaultConfig.DEFAULT_LIFETIME, value);
}else{
conn.setex(key, seconds, value);
}
_logger.trace("setex successful .");
}
/**
* @param key
* @return String
*/
public String get(String key){
_logger.trace("get key {} ..." , key);
String value = null;
if(key != null){
value = conn.get(key);
}
return value;
}
/**
* @param key
* @return String
*/
public <T> T getObject(String key){
String value = null;
if(key != null){
value = get(key);
if(value!=null){
return ObjectTransformer.deserialize(value);
}
}
return null;
}
public void expire(String key,long seconds){
_logger.trace("expire key {} , {}" , key , seconds);
conn.expire(key, seconds);
}
public void delete(String key){
_logger.trace("del key {}" , key);
conn.del(key);
}
public void rPush(String key, Serializable object){
conn.rpush(key, ObjectTransformer.serialize(object));
}
public long lRem(String key,int count,String value){
return conn.lrem(key, count, value);
}
public List<String> lRange(String key,int start,int end){
return conn.lrange(key, start, end);
}
public void openPipeline(){
this.pipeline=conn.pipelined();
}
public List<Object> closePipeline(){
return pipeline.syncAndReturnAll();
}
/**
* 释放jedis资源
* @param jedis
*/
public void close() {
public void close() {
if (conn != null) {
connectionFactory.close(conn);
connectionFactory.close(conn);
}
}
public Jedis getConn() {
return conn;
}
public Jedis getConn() {
return conn;
}
public void setConn(Jedis conn) {
this.conn = conn;
}
public void setConn(Jedis conn) {
this.conn = conn;
}
public Pipeline getPipeline() {
return pipeline;
}
public Pipeline getPipeline() {
return pipeline;
}
}

View File

@ -25,7 +25,7 @@ import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class RedisConnectionFactory {
private static final Logger _logger = LoggerFactory.getLogger(RedisConnectionFactory.class);
private static final Logger _logger = LoggerFactory.getLogger(RedisConnectionFactory.class);
JedisPoolConfig poolConfig;
@ -42,7 +42,7 @@ public class RedisConnectionFactory {
public void initConnectionFactory() {
if (jedisPool == null) {
_logger.debug("init Jedis Pool .");
_logger.debug("init Jedis Pool .");
try {
if (this.hostName == null || hostName.equals("")) {
hostName = RedisDefaultConfig.DEFAULT_ADDRESS;
@ -75,16 +75,16 @@ public class RedisConnectionFactory {
}
public Jedis open() {
_logger.trace("get jedisPool Resource ...");
Jedis jedis = jedisPool.getResource();
_logger.trace("return jedisPool Resource .");
_logger.trace("get jedisPool Resource ...");
Jedis jedis = jedisPool.getResource();
_logger.trace("return jedisPool Resource .");
return jedis;
}
public void close(Jedis conn) {
// jedisPool.returnResource(conn);
_logger.trace("close conn .");
_logger.trace("close conn .");
conn.close();
_logger.trace("closed conn .");
}

View File

@ -1,7 +1,7 @@
package org.dromara.maxkey.persistence.redis;
public class RedisDefaultConfig {
/**
/**
* Redis默认服务器IP
*/
public static final String DEFAULT_ADDRESS = "127.0.0.1";

View File

@ -22,42 +22,42 @@ import java.util.concurrent.ConcurrentMap;
public final class ConstsAct {
public static final String CREATE = "create";
public static final String CREATE = "create";
public static final String DELETE = "delete";
public static final String DELETE = "delete";
public static final String UPDATE = "update";
public static final String UPDATE = "update";
public static final String CHANGE_PASSWORD = "change_password";
public static final String CHANGE_PASSWORD = "change_password";
public static final String FORGOT_PASSWORD = "forgot_password";
public static final String FORGOT_PASSWORD = "forgot_password";
public static final String ADD_MEMBER = "add_member";
public static final String ADD_MEMBER = "add_member";
public static final String DELETE_MEMBER = "delete_member";
public static final String DELETE_MEMBER = "delete_member";
public static final String ENABLE = "enable";
public static final String ENABLE = "enable";
public static final String DISABLE = "disable";
public static final String DISABLE = "disable";
public static final String INACTIVE = "inactive";
public static final String INACTIVE = "inactive";
public static final String LOCK = "lock";
public static final String LOCK = "lock";
public static final String UNLOCK = "unlock";
public static final String UNLOCK = "unlock";
public static final String VIEW = "view";
public static final String VIEW = "view";
public static final ConcurrentMap<Integer,String> statusActon ;
static {
statusActon = new ConcurrentHashMap<>();
statusActon.put(ConstsStatus.ACTIVE, ENABLE);
statusActon.put(ConstsStatus.INACTIVE, INACTIVE);
statusActon.put(ConstsStatus.DISABLED, DISABLE);
statusActon.put(ConstsStatus.LOCK, LOCK);
statusActon.put(ConstsStatus.UNLOCK, UNLOCK);
statusActon.put(ConstsStatus.DELETE, DELETE);
statusActon = new ConcurrentHashMap<>();
statusActon.put(ConstsStatus.ACTIVE, ENABLE);
statusActon.put(ConstsStatus.INACTIVE, INACTIVE);
statusActon.put(ConstsStatus.DISABLED, DISABLE);
statusActon.put(ConstsStatus.LOCK, LOCK);
statusActon.put(ConstsStatus.UNLOCK, UNLOCK);
statusActon.put(ConstsStatus.DELETE, DELETE);
}
}

View File

@ -18,8 +18,8 @@
package org.dromara.maxkey.constants;
public final class ConstsActResult {
public static final String SUCCESS = "success";
public static final String ERROR = "error";
public static final String FAIL = "fail";
public static final String SUCCESS = "success";
public static final String ERROR = "error";
public static final String FAIL = "fail";
}

View File

@ -25,11 +25,11 @@ package org.dromara.maxkey.constants;
*/
public class ConstsBoolean {
public static final int FALSE = 0;
public static final int FALSE = 0;
public static final int TRUE = 1;
public static final int TRUE = 1;
private int value = FALSE;
private int value = FALSE;
public ConstsBoolean() {

Some files were not shown because too many files have changed in this diff Show More