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

View File

@ -24,32 +24,32 @@ public class AuthMaxKeyJeeGitRequest extends AuthDefaultRequest {
* @param config * @param config
*/ */
public AuthMaxKeyJeeGitRequest(AuthConfig config) { public AuthMaxKeyJeeGitRequest(AuthConfig config) {
super(config, AuthCustomSource.MAXKEY); super(config, AuthCustomSource.MAXKEY);
} }
public AuthMaxKeyJeeGitRequest(AuthConfig config, AuthSource source) { public AuthMaxKeyJeeGitRequest(AuthConfig config, AuthSource source) {
super(config, source); super(config, source);
} }
public AuthMaxKeyJeeGitRequest(AuthConfig config, AuthStateCache authStateCache) { public AuthMaxKeyJeeGitRequest(AuthConfig config, AuthStateCache authStateCache) {
super(config, AuthCustomSource.MAXKEY, authStateCache); super(config, AuthCustomSource.MAXKEY, authStateCache);
} }
@Override @Override
protected AuthToken getAccessToken(AuthCallback authCallback) { protected AuthToken getAccessToken(AuthCallback authCallback) {
String body = doPostAuthorizationCode(authCallback.getCode()); String body = doPostAuthorizationCode(authCallback.getCode());
JSONObject object = JSONObject.parseObject(body); JSONObject object = JSONObject.parseObject(body);
System.out.println("getAccessToken:"+JsonMapper.toJson(object)); System.out.println("getAccessToken:"+JsonMapper.toJson(object));
AuthCustomExceptionUtils.checkResponse(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(); 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 @Override
protected AuthUser getUserInfo(AuthToken authToken) { protected AuthUser getUserInfo(AuthToken authToken) {
String body = doGetUserInfo(authToken); String body = doGetUserInfo(authToken);
JSONObject object = JSONObject.parseObject(body); JSONObject object = JSONObject.parseObject(body);
AuthCustomExceptionUtils.checkResponse(object); 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(); 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"; private static final String DEFAULT_USER_CODE="system";
public static String getAuthUserToSysUserCode(String oauthUserId) { public static String getAuthUserToSysUserCode(String oauthUserId) {
//自行实现第三方用户到jeesite用户之间逻辑转换关系 //自行实现第三方用户到jeesite用户之间逻辑转换关系
if(DEMO_MODE) { if(DEMO_MODE) {
return DEFAULT_USER_CODE; return DEFAULT_USER_CODE;
} }
return oauthUserId; return oauthUserId;
} }
public static void loginByOauthUserId(String oauthUserId) { public static void loginByOauthUserId(String oauthUserId) {
HttpServletRequest request = ServletUtils.getRequest(); HttpServletRequest request = ServletUtils.getRequest();
HttpServletResponse response = ServletUtils.getResponse(); HttpServletResponse response = ServletUtils.getResponse();
try { try {
// FormToken 构造方法的三个参数登录名是否内部登录无条件请求对象 // FormToken 构造方法的三个参数登录名是否内部登录无条件请求对象
UserUtils.getSubject().login(new FormToken(getAuthUserToSysUserCode(oauthUserId), true, request)); UserUtils.getSubject().login(new FormToken(getAuthUserToSysUserCode(oauthUserId), true, request));
System.out.println("登录成功__sid=" + UserUtils.getSession().getId()); System.out.println("登录成功__sid=" + UserUtils.getSession().getId());
FormFilter.onLoginSuccess(request, response); FormFilter.onLoginSuccess(request, response);
} catch (AuthenticationException e) { } catch (AuthenticationException e) {
FormFilter.onLoginFailure(e, request, response); FormFilter.onLoginFailure(e, request, response);
} }
} }
@ -71,11 +71,11 @@ public class Oauth2UserLoginUtils{
// jeegit: // jeegit:
// clientId: 823874316692094976 // clientId: 823874316692094976
// clientSecret: t74BMTcwMjIwMjMwODIzNTA4NDQFLu // clientSecret: t74BMTcwMjIwMjMwODIzNTA4NDQFLu
// serverUrl: http://sso.maxkey.top // serverUrl: http://sso.maxkey.top
// redirectUri: http://localhost:8980/js/oauth2/callback/jeegit // redirectUri: http://localhost:8980/js/oauth2/callback/jeegit
// className: com.jeesite.modules.oauth2.request.AuthMaxKeyRequest // className: com.jeesite.modules.oauth2.request.AuthMaxKeyRequest
authRequest = new AuthMaxKeyJeeGitRequest(AuthConfig.builder() authRequest = new AuthMaxKeyJeeGitRequest(AuthConfig.builder()
.clientId(Global.getProperty("oauth2." + source + ".clientId")) .clientId(Global.getProperty("oauth2." + source + ".clientId"))
.clientSecret(Global.getProperty("oauth2." + source + ".clientSecret")) .clientSecret(Global.getProperty("oauth2." + source + ".clientSecret"))

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -8,14 +8,14 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur
@Configuration @Configuration
@EnableOAuth2Sso @EnableOAuth2Sso
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.authorizeRequests() .authorizeRequests()
.antMatchers("/", "/error**").permitAll() .antMatchers("/", "/error**").permitAll()
.anyRequest().authenticated() .anyRequest().authenticated()
.and().logout().logoutUrl("/logout") .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 @Controller
public class AppController { public class AppController {
@GetMapping("hello") @GetMapping("hello")
public ModelAndView welcome() { public ModelAndView welcome() {
ModelAndView mav = new ModelAndView(); ModelAndView mav = new ModelAndView();
mav.setViewName("welcome"); mav.setViewName("welcome");
return mav; return mav;
} }
@GetMapping("error") @GetMapping("error")
public ModelAndView error() { public ModelAndView error() {
Map<String, String> model = new HashMap<>(); Map<String, String> model = new HashMap<>();
ModelAndView mav = new ModelAndView(); ModelAndView mav = new ModelAndView();
mav.setViewName("error"); mav.setViewName("error");
return mav; return mav;
} }
} }

View File

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

View File

@ -8,14 +8,14 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur
@Configuration @Configuration
@EnableOAuth2Sso @EnableOAuth2Sso
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.authorizeRequests() .authorizeRequests()
.antMatchers("/", "/error**").permitAll() .antMatchers("/", "/error**").permitAll()
.anyRequest().authenticated() .anyRequest().authenticated()
.and().logout().logoutUrl("/logout") .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; String sessionId;
int twoFactor; int twoFactor;
List<GrantedAuthority> grantedAuthority; List<GrantedAuthority> grantedAuthority;
@ -47,13 +47,13 @@ public class SignPrincipal implements UserDetails {
boolean roleAdministrators; 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. * SigninPrincipal.
@ -160,22 +160,22 @@ public class SignPrincipal implements UserDetails {
public String getSessionId() { public String getSessionId() {
return sessionId; return sessionId;
} }
public void setSessionId(String sessionId) { public void setSessionId(String sessionId) {
this.sessionId = sessionId; this.sessionId = sessionId;
} }
public String getInstId() { public String getInstId() {
return instId; return instId;
} }
public String getUserId() { public String getUserId() {
return userId; return userId;
} }
@Override @Override
public boolean isEnabled() { public boolean isEnabled() {
return this.enabled; return this.enabled;
} }
@ -207,45 +207,45 @@ public class SignPrincipal implements UserDetails {
} }
public int getTwoFactor() { public int getTwoFactor() {
return twoFactor; return twoFactor;
} }
public void setTwoFactor(int twoFactor) { public void setTwoFactor(int twoFactor) {
this.twoFactor = twoFactor; this.twoFactor = twoFactor;
} }
public void clearTwoFactor() { public void clearTwoFactor() {
this.twoFactor = 0; this.twoFactor = 0;
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
builder.append("Principal [username="); builder.append("Principal [username=");
builder.append(getUsername()); builder.append(getUsername());
builder.append(", userInfo="); builder.append(", userInfo=");
builder.append(userInfo); builder.append(userInfo);
builder.append(", userDetails="); builder.append(", userDetails=");
builder.append(userDetails); builder.append(userDetails);
builder.append(", grantedAuthority="); builder.append(", grantedAuthority=");
builder.append(grantedAuthority); builder.append(grantedAuthority);
builder.append(", grantedAuthorityApps="); builder.append(", grantedAuthorityApps=");
builder.append(grantedAuthorityApps); builder.append(grantedAuthorityApps);
builder.append(", authenticated="); builder.append(", authenticated=");
builder.append(authenticated); builder.append(authenticated);
builder.append(", roleAdministrators="); builder.append(", roleAdministrators=");
builder.append(roleAdministrators); builder.append(roleAdministrators);
builder.append(", accountNonExpired="); builder.append(", accountNonExpired=");
builder.append(accountNonExpired); builder.append(accountNonExpired);
builder.append(", accountNonLocked="); builder.append(", accountNonLocked=");
builder.append(accountNonLocked); builder.append(accountNonLocked);
builder.append(", credentialsNonExpired="); builder.append(", credentialsNonExpired=");
builder.append(credentialsNonExpired); builder.append(credentialsNonExpired);
builder.append(", enabled="); builder.append(", enabled=");
builder.append(enabled); builder.append(enabled);
builder.append("]"); builder.append("]");
return builder.toString(); return builder.toString();
} }

View File

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

View File

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

View File

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

View File

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

View File

@ -19,9 +19,9 @@ package org.dromara.maxkey.authn.jwt;
public interface CongressService { 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 remove(String congress);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -33,11 +33,11 @@ public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentR
@Override @Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
Authentication authentication = Authentication authentication =
(Authentication ) webRequest.getAttribute( (Authentication ) webRequest.getAttribute(
WebConstants.AUTHENTICATION, RequestAttributes.SCOPE_SESSION); WebConstants.AUTHENTICATION, RequestAttributes.SCOPE_SESSION);
UserInfo userInfo = AuthorizationUtils.getUserInfo(authentication); UserInfo userInfo = AuthorizationUtils.getUserInfo(authentication);
if (userInfo != null) { if (userInfo != null) {
return userInfo; return userInfo;
} }
throw new MissingServletRequestPartException("currentUser"); throw new MissingServletRequestPartException("currentUser");

View File

@ -38,36 +38,36 @@ import jakarta.servlet.http.HttpServletResponse;
@Controller @Controller
public class FileUploadEndpoint { public class FileUploadEndpoint {
private static Logger _logger = LoggerFactory.getLogger(FileUploadEndpoint.class); private static Logger _logger = LoggerFactory.getLogger(FileUploadEndpoint.class);
@Autowired @Autowired
FileUploadService fileUploadService; FileUploadService fileUploadService;
@PostMapping({"/file/upload/"}) @PostMapping({"/file/upload/"})
@ResponseBody @ResponseBody
public Message<Object> upload( HttpServletRequest request, public Message<Object> upload( HttpServletRequest request,
HttpServletResponse response, HttpServletResponse response,
@ModelAttribute FileUpload fileUpload, @ModelAttribute FileUpload fileUpload,
@CurrentUser UserInfo currentUser){ @CurrentUser UserInfo currentUser){
_logger.debug("FileUpload"); _logger.debug("FileUpload");
fileUpload.setId(fileUpload.generateId()); fileUpload.setId(fileUpload.generateId());
fileUpload.setContentType(fileUpload.getUploadFile().getContentType()); fileUpload.setContentType(fileUpload.getUploadFile().getContentType());
fileUpload.setFileName(fileUpload.getUploadFile().getOriginalFilename()); fileUpload.setFileName(fileUpload.getUploadFile().getOriginalFilename());
fileUpload.setContentSize(fileUpload.getUploadFile().getSize()); fileUpload.setContentSize(fileUpload.getUploadFile().getSize());
fileUpload.setCreatedBy(currentUser.getUsername()); fileUpload.setCreatedBy(currentUser.getUsername());
/* /*
* upload UploadFile MultipartFile to Uploaded Bytes * upload UploadFile MultipartFile to Uploaded Bytes
*/ */
if(null!=fileUpload.getUploadFile()&&!fileUpload.getUploadFile().isEmpty()){ if(null!=fileUpload.getUploadFile()&&!fileUpload.getUploadFile().isEmpty()){
try { try {
fileUpload.setUploaded(fileUpload.getUploadFile().getBytes()); fileUpload.setUploaded(fileUpload.getUploadFile().getBytes());
fileUploadService.insert(fileUpload); fileUploadService.insert(fileUpload);
_logger.trace("FileUpload SUCCESS"); _logger.trace("FileUpload SUCCESS");
} catch (IOException e) { } catch (IOException e) {
_logger.error("FileUpload IOException",e); _logger.error("FileUpload IOException",e);
} }
} }
return new Message<Object>(Message.SUCCESS,(Object)fileUpload.getId()); 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(); Object principal = authentication == null ? null : authentication.getPrincipal();
_logger.trace("principal {}",principal); _logger.trace("principal {}",principal);
if(principal != null ) { if(principal != null ) {
if(principal instanceof SignPrincipal && ((SignPrincipal)principal).getUserInfo()!=null) { if(principal instanceof SignPrincipal && ((SignPrincipal)principal).getUserInfo()!=null) {
SignPrincipal signPrincipal = (SignPrincipal)principal; SignPrincipal signPrincipal = (SignPrincipal)principal;
_logger.trace("{} HttpSession Id {} for userId {} , username {} @Ticket {} Destroyed" , _logger.trace("{} HttpSession Id {} for userId {} , username {} @Ticket {} Destroyed" ,
DateUtils.formatDateTime(new Date()), DateUtils.formatDateTime(new Date()),
session.getId(), session.getId(),
signPrincipal.getUserInfo().getId(), signPrincipal.getUserInfo().getId(),
signPrincipal.getUserInfo().getUsername(), signPrincipal.getUserInfo().getUsername(),
signPrincipal.getSessionId()); signPrincipal.getSessionId());
}else if(principal instanceof User) { }else if(principal instanceof User) {
User user = (User)principal; User user = (User)principal;
_logger.trace("{} HttpSession Id {} for username {} password {} Destroyed" , _logger.trace("{} HttpSession Id {} for username {} password {} Destroyed" ,
DateUtils.formatDateTime(new Date()), DateUtils.formatDateTime(new Date()),
session.getId(), session.getId(),
user.getUsername(), user.getUsername(),
user.getPassword()); user.getPassword());
}else{ }else{
_logger.trace("{} HttpSession Id {} for principal {} Destroyed" , _logger.trace("{} HttpSession Id {} for principal {} Destroyed" ,
DateUtils.formatDateTime(new Date()), DateUtils.formatDateTime(new Date()),
session.getId(), session.getId(),
principal); principal);
} }
}else { }else {
_logger.trace("{} HttpSession Id {} Destroyed" , _logger.trace("{} HttpSession Id {} Destroyed" ,
DateUtils.formatDateTime(new Date()), DateUtils.formatDateTime(new Date()),
session.getId()); session.getId());
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -41,30 +41,30 @@ public class TokenAutoConfiguration{
@Bean @Bean
AuthTokenService authTokenService( AuthTokenService authTokenService(
AuthJwkConfig authJwkConfig, AuthJwkConfig authJwkConfig,
RedisConnectionFactory redisConnFactory, RedisConnectionFactory redisConnFactory,
MomentaryService momentaryService, MomentaryService momentaryService,
AuthRefreshTokenService refreshTokenService, AuthRefreshTokenService refreshTokenService,
@Value("${maxkey.server.persistence}") int persistence) throws JOSEException { @Value("${maxkey.server.persistence}") int persistence) throws JOSEException {
CongressService congressService; CongressService congressService;
_logger.debug("cache persistence {}" , persistence); _logger.debug("cache persistence {}" , persistence);
if (persistence == ConstsPersistence.REDIS) { if (persistence == ConstsPersistence.REDIS) {
congressService = new RedisCongressService(redisConnFactory); congressService = new RedisCongressService(redisConnFactory);
}else { }else {
congressService = new InMemoryCongressService(); congressService = new InMemoryCongressService();
} }
return new AuthTokenService( return new AuthTokenService(
authJwkConfig, authJwkConfig,
congressService, congressService,
momentaryService, momentaryService,
refreshTokenService refreshTokenService
); );
} }
@Bean @Bean
AuthRefreshTokenService refreshTokenService(AuthJwkConfig authJwkConfig) throws JOSEException { 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 static String PROVIDER_SUFFIX = "AuthenticationProvider";
public class AuthType{ public class AuthType{
public static final String NORMAL = "normal"; public static final String NORMAL = "normal";
public static final String TFA = "tfa"; public static final String TFA = "tfa";
public static final String MOBILE = "mobile"; public static final String MOBILE = "mobile";
public static final String TRUSTED = "trusted"; public static final String TRUSTED = "trusted";
/** /**
* 扫描认证 * 扫描认证
*/ */
public static final String SCAN_CODE = "scancode"; public static final String SCAN_CODE = "scancode";
/** /**
* 手机端APP * 手机端APP
*/ */
public static final String APP = "app"; public static final String APP = "app";
} }
protected ApplicationConfig applicationConfig; protected ApplicationConfig applicationConfig;
@ -99,11 +99,11 @@ public abstract class AbstractAuthenticationProvider {
} }
public Authentication authenticate(LoginCredential authentication){ public Authentication authenticate(LoginCredential authentication){
return null; return null;
} }
public Authentication authenticate(LoginCredential authentication,boolean trusted) { public Authentication authenticate(LoginCredential authentication,boolean trusted) {
return null; return null;
} }
/** /**
@ -124,7 +124,7 @@ public abstract class AbstractAuthenticationProvider {
for(GrantedAuthority administratorsAuthority : grantedAdministratorsAuthoritys) { for(GrantedAuthority administratorsAuthority : grantedAdministratorsAuthoritys) {
if(grantedAuthoritys.contains(administratorsAuthority)) { if(grantedAuthoritys.contains(administratorsAuthority)) {
principal.setRoleAdministrators(true); principal.setRoleAdministrators(true);
_logger.trace("ROLE ADMINISTRATORS Authentication ."); _logger.trace("ROLE ADMINISTRATORS Authentication .");
} }
} }
@ -134,7 +134,7 @@ public abstract class AbstractAuthenticationProvider {
UsernamePasswordAuthenticationToken authenticationToken = UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken( new UsernamePasswordAuthenticationToken(
principal, principal,
"PASSWORD", "PASSWORD",
grantedAuthoritys grantedAuthoritys
); );
@ -228,34 +228,34 @@ public abstract class AbstractAuthenticationProvider {
loginUser.setDisplayName("not exist"); loginUser.setDisplayName("not exist");
loginUser.setLoginCount(0); loginUser.setLoginCount(0);
authenticationRealm.insertLoginHistory( authenticationRealm.insertLoginHistory(
loginUser, loginUser,
ConstsLoginType.LOCAL, ConstsLoginType.LOCAL,
"", "",
i18nMessage, i18nMessage,
WebConstants.LOGIN_RESULT.USER_NOT_EXIST); WebConstants.LOGIN_RESULT.USER_NOT_EXIST);
throw new BadCredentialsException(i18nMessage); throw new BadCredentialsException(i18nMessage);
} }
return true; return true;
} }
protected boolean statusValid(LoginCredential loginCredential , UserInfo userInfo) { protected boolean statusValid(LoginCredential loginCredential , UserInfo userInfo) {
if(userInfo.getIsLocked()==ConstsStatus.LOCK) { if(userInfo.getIsLocked()==ConstsStatus.LOCK) {
authenticationRealm.insertLoginHistory( authenticationRealm.insertLoginHistory(
userInfo, userInfo,
loginCredential.getAuthType(), loginCredential.getAuthType(),
loginCredential.getProvider(), loginCredential.getProvider(),
loginCredential.getCode(), loginCredential.getCode(),
WebConstants.LOGIN_RESULT.USER_LOCKED WebConstants.LOGIN_RESULT.USER_LOCKED
); );
}else if(userInfo.getStatus()!=ConstsStatus.ACTIVE) { }else if(userInfo.getStatus()!=ConstsStatus.ACTIVE) {
authenticationRealm.insertLoginHistory( authenticationRealm.insertLoginHistory(
userInfo, userInfo,
loginCredential.getAuthType(), loginCredential.getAuthType(),
loginCredential.getProvider(), loginCredential.getProvider(),
loginCredential.getCode(), loginCredential.getCode(),
WebConstants.LOGIN_RESULT.USER_INACTIVE WebConstants.LOGIN_RESULT.USER_INACTIVE
); );
} }
return true; return true;
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -21,8 +21,8 @@ import java.util.List;
public interface KerberosService { public interface KerberosService {
public List<KerberosProxy> getKerberosProxys(); public List<KerberosProxy> getKerberosProxys();
public String buildKerberosProxys( ); public String buildKerberosProxys( );
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -26,40 +26,40 @@ import org.slf4j.LoggerFactory;
public class RedisMomentaryService implements MomentaryService { public class RedisMomentaryService implements MomentaryService {
private static final Logger _logger = LoggerFactory.getLogger(RedisMomentaryService.class); private static final Logger _logger = LoggerFactory.getLogger(RedisMomentaryService.class);
protected int validitySeconds = 60 * 5; //default 5 minutes. protected int validitySeconds = 60 * 5; //default 5 minutes.
RedisConnectionFactory connectionFactory; RedisConnectionFactory connectionFactory;
public static final String PREFIX = "mxk:momentary:"; public static final String PREFIX = "mxk:momentary:";
/** /**
* @param connectionFactory * @param connectionFactory
*/ */
public RedisMomentaryService( public RedisMomentaryService(
RedisConnectionFactory connectionFactory) { RedisConnectionFactory connectionFactory) {
super(); super();
this.connectionFactory = connectionFactory; this.connectionFactory = connectionFactory;
} }
/** /**
* *
*/ */
public RedisMomentaryService() { public RedisMomentaryService() {
} }
public void setConnectionFactory(RedisConnectionFactory connectionFactory) { public void setConnectionFactory(RedisConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory; this.connectionFactory = connectionFactory;
} }
@Override @Override
public void put(String sessionId , String name, Object value){ public void put(String sessionId , String name, Object value){
RedisConnection conn = connectionFactory.getConnection(); RedisConnection conn = connectionFactory.getConnection();
String sessionKey = getSessionKey(sessionId , name); String sessionKey = getSessionKey(sessionId , name);
conn.setexObject(sessionKey, validitySeconds, value); conn.setexObject(sessionKey, validitySeconds, value);
_logger.trace("key {}, validitySeconds {}, value {}",sessionKey,validitySeconds,value); _logger.trace("key {}, validitySeconds {}, value {}",sessionKey,validitySeconds,value);
conn.close(); conn.close();
} }
@Override @Override
public Object get(String sessionId , String name) { public Object get(String sessionId , String name) {
@ -71,19 +71,19 @@ public class RedisMomentaryService implements MomentaryService {
return value; return value;
} }
@Override @Override
public Object remove(String sessionId, String name) { public Object remove(String sessionId, String name) {
RedisConnection conn = connectionFactory.getConnection(); RedisConnection conn = connectionFactory.getConnection();
String sessionKey = getSessionKey(sessionId , name); String sessionKey = getSessionKey(sessionId , name);
Object value = conn.getObject(sessionKey); Object value = conn.getObject(sessionKey);
conn.delete(getSessionKey(sessionId , name)); conn.delete(getSessionKey(sessionId , name));
conn.close(); conn.close();
_logger.trace("key {}, value {}",sessionKey,value); _logger.trace("key {}, value {}",sessionKey,value);
return value; return value;
} }
private String getSessionKey(String sessionId , String name) { 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; import redis.clients.jedis.Pipeline;
public class RedisConnection { public class RedisConnection {
private static final Logger _logger = LoggerFactory.getLogger(RedisConnection.class); private static final Logger _logger = LoggerFactory.getLogger(RedisConnection.class);
Jedis conn ; Jedis conn ;
RedisConnectionFactory connectionFactory; RedisConnectionFactory connectionFactory;
Pipeline pipeline ; Pipeline pipeline ;
public RedisConnection() { public RedisConnection() {
} }
public RedisConnection(RedisConnectionFactory connectionFactory) { public RedisConnection(RedisConnectionFactory connectionFactory) {
this.conn=connectionFactory.open(); this.conn=connectionFactory.open();
this.connectionFactory=connectionFactory; this.connectionFactory=connectionFactory;
} }
/** /**
* @param key * @param key
* @param value * @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();
}
/**
* 释放jedis资源
* @param jedis
*/ */
public void close() { public void set(String key, String value){
if (conn != null) { conn.set(key, value);
connectionFactory.close(conn); }
/**
* @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 Jedis getConn() { public void setexObject(String key,int seconds, Object value){
return conn; if(value instanceof Serializable) {
} setex(key, seconds, ObjectTransformer.serialize((Serializable)value));
}else {
_logger.error("value must implements of Serializable .");
}
}
public void setConn(Jedis conn) { /**
this.conn = conn; * @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 .");
}
public Pipeline getPipeline() {
return pipeline; /**
} * @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() {
if (conn != null) {
connectionFactory.close(conn);
}
}
public Jedis getConn() {
return conn;
}
public void setConn(Jedis conn) {
this.conn = conn;
}
public Pipeline getPipeline() {
return pipeline;
}
} }

View File

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

View File

@ -1,7 +1,7 @@
package org.dromara.maxkey.persistence.redis; package org.dromara.maxkey.persistence.redis;
public class RedisDefaultConfig { public class RedisDefaultConfig {
/** /**
* Redis默认服务器IP * Redis默认服务器IP
*/ */
public static final String DEFAULT_ADDRESS = "127.0.0.1"; 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 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 ; public static final ConcurrentMap<Integer,String> statusActon ;
static { static {
statusActon = new ConcurrentHashMap<>(); statusActon = new ConcurrentHashMap<>();
statusActon.put(ConstsStatus.ACTIVE, ENABLE); statusActon.put(ConstsStatus.ACTIVE, ENABLE);
statusActon.put(ConstsStatus.INACTIVE, INACTIVE); statusActon.put(ConstsStatus.INACTIVE, INACTIVE);
statusActon.put(ConstsStatus.DISABLED, DISABLE); statusActon.put(ConstsStatus.DISABLED, DISABLE);
statusActon.put(ConstsStatus.LOCK, LOCK); statusActon.put(ConstsStatus.LOCK, LOCK);
statusActon.put(ConstsStatus.UNLOCK, UNLOCK); statusActon.put(ConstsStatus.UNLOCK, UNLOCK);
statusActon.put(ConstsStatus.DELETE, DELETE); statusActon.put(ConstsStatus.DELETE, DELETE);
} }
} }

View File

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

View File

@ -25,11 +25,11 @@ package org.dromara.maxkey.constants;
*/ */
public class ConstsBoolean { 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() { public ConstsBoolean() {

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