use of org.maxkey.authn.LoginCredential in project MaxKey by dromara.
the class SocialSignOnEndpoint method socialSignOn.
public boolean socialSignOn(SocialsAssociate socialsAssociate) {
socialsAssociate = this.socialsAssociateService.get(socialsAssociate);
_logger.debug("Loaded SocialSignOn Socials Associate : " + socialsAssociate);
if (null == socialsAssociate) {
WebContext.getRequest().getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, new BadCredentialsException(WebContext.getI18nValue("login.error.social")));
return false;
}
_logger.debug("Social Sign On from {} mapping to user {}", socialsAssociate.getProvider(), socialsAssociate.getUsername());
LoginCredential loginCredential = new LoginCredential(socialsAssociate.getUsername(), "", ConstsLoginType.SOCIALSIGNON);
loginCredential.setProvider(this.socialSignOnProvider.getProviderName());
authenticationProvider.authentication(loginCredential, true);
// socialsAssociate.setAccessToken(JsonUtils.object2Json(this.accessToken));
socialsAssociate.setSocialUserInfo(accountJsonString);
// socialsAssociate.setExAttribute(JsonUtils.object2Json(accessToken.getResponseObject()));
this.socialsAssociateService.update(socialsAssociate);
return true;
}
use of org.maxkey.authn.LoginCredential in project MaxKey by dromara.
the class HttpRemeberMeEntryPoint method preHandle.
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
boolean isAuthenticated = WebContext.isAuthenticated();
Cookie readRemeberMeCookie = WebContext.readCookieByName(request, WebConstants.REMEBER_ME_COOKIE);
if (!enable || isAuthenticated || readRemeberMeCookie == null || !applicationConfig.getLoginConfig().isRemeberMe()) {
return true;
}
_logger.trace("RemeberMe Login Start ...");
_logger.trace("Request url : " + request.getRequestURL());
_logger.trace("Request URI : " + request.getRequestURI());
_logger.trace("Request ContextPath : " + request.getContextPath());
_logger.trace("Request ServletPath : " + request.getServletPath());
_logger.trace("RequestSessionId : " + request.getRequestedSessionId());
_logger.trace("isRequestedSessionIdValid : " + request.isRequestedSessionIdValid());
_logger.trace("getSession : " + request.getSession(false));
// session not exists,session timeout,recreate new session
if (request.getSession(false) == null) {
_logger.info("recreate new session .");
request.getSession(true);
}
_logger.trace("getSession.getId : " + request.getSession().getId());
_logger.debug("Try RemeberMe login ");
String remeberMe = readRemeberMeCookie.getValue();
_logger.debug("RemeberMe : " + remeberMe);
remeberMe = new String(Base64Utils.base64UrlDecode(remeberMe));
remeberMe = PasswordReciprocal.getInstance().decoder(remeberMe);
_logger.debug("decoder RemeberMe : " + remeberMe);
RemeberMe remeberMeCookie = new RemeberMe();
remeberMeCookie = (RemeberMe) JsonUtils.json2Object(remeberMe, remeberMeCookie);
_logger.debug("Remeber Me Cookie : " + remeberMeCookie);
RemeberMe storeRemeberMe = remeberMeService.read(remeberMeCookie);
if (storeRemeberMe != null) {
DateTime loginDate = new DateTime(storeRemeberMe.getLastLogin());
DateTime expiryDate = loginDate.plusSeconds(remeberMeService.getRemeberMeValidity());
DateTime now = new DateTime();
if (now.isBefore(expiryDate)) {
LoginCredential loginCredential = new LoginCredential(storeRemeberMe.getUsername(), "", ConstsLoginType.REMEBER_ME);
authenticationProvider.authentication(loginCredential, true);
remeberMeService.updateRemeberMe(remeberMeCookie, response);
_logger.debug("RemeberMe Logined in , username " + storeRemeberMe.getUsername());
}
}
return true;
}
use of org.maxkey.authn.LoginCredential in project MaxKey by dromara.
the class HttpWsFederationEntryPoint method preHandle.
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
boolean isAuthenticated = WebContext.isAuthenticated();
String wsFederationWA = request.getParameter(WsFederationConstants.WA);
String wsFederationWResult = request.getParameter(WsFederationConstants.WRESULT);
if (!enable || isAuthenticated || !applicationConfig.getLoginConfig().isWsFederation() || wsFederationWA == null) {
return true;
}
_logger.trace("WsFederation Login Start ...");
_logger.trace("Request url : " + request.getRequestURL());
_logger.trace("Request URI : " + request.getRequestURI());
_logger.trace("Request ContextPath : " + request.getContextPath());
_logger.trace("Request ServletPath : " + request.getServletPath());
_logger.trace("RequestSessionId : " + request.getRequestedSessionId());
_logger.trace("isRequestedSessionIdValid : " + request.isRequestedSessionIdValid());
_logger.trace("getSession : " + request.getSession(false));
// session not exists,session timeout,recreate new session
if (request.getSession(false) == null) {
_logger.trace("recreate new session .");
request.getSession(true);
}
_logger.trace("getSession.getId : " + request.getSession().getId());
// for WsFederation Login
_logger.debug("WsFederation : " + wsFederationWA + " , wsFederationWResult : " + wsFederationWResult);
if (applicationConfig.getLoginConfig().isWsFederation() && StringUtils.isNotEmpty(wsFederationWA) && wsFederationWA.equalsIgnoreCase(WsFederationConstants.WSIGNIN)) {
_logger.debug("wresult : {}" + wsFederationWResult);
final String wctx = request.getParameter(WsFederationConstants.WCTX);
_logger.debug("wctx : {}" + wctx);
// create credentials
final AssertionImpl assertion = WsFederationUtils.parseTokenFromString(wsFederationWResult);
// Validate the signature
if (assertion != null && WsFederationUtils.validateSignature(assertion, wsFederationService.getWsFederationConfiguration().getSigningCertificates())) {
final WsFederationCredential wsFederationCredential = WsFederationUtils.createCredentialFromToken(assertion);
if (wsFederationCredential != null && wsFederationCredential.isValid(wsFederationService.getWsFederationConfiguration().getRelyingParty(), wsFederationService.getWsFederationConfiguration().getIdentifier(), wsFederationService.getWsFederationConfiguration().getTolerance())) {
// Give the library user a chance to change the attributes as necessary
if (wsFederationService.getWsFederationConfiguration().getAttributeMutator() != null) {
wsFederationService.getWsFederationConfiguration().getAttributeMutator().modifyAttributes(wsFederationCredential.getAttributes(), wsFederationService.getWsFederationConfiguration().getUpnSuffix());
}
LoginCredential loginCredential = new LoginCredential(wsFederationCredential.getAttributes().get("").toString(), "", ConstsLoginType.WSFEDERATION);
authenticationProvider.authentication(loginCredential, true);
return true;
} else {
_logger.warn("SAML assertions are blank or no longer valid.");
}
} else {
_logger.error("WS Requested Security Token is blank or the signature is not valid.");
}
}
return true;
}
use of org.maxkey.authn.LoginCredential in project MaxKey by dromara.
the class ConsumerEndpoint method consumer.
@RequestMapping(value = "/consumer/saml/v20/{spId}")
public ModelAndView consumer(HttpServletRequest request, HttpServletResponse response, @PathVariable("spId") String spId) throws Exception {
logger.debug("Attempting authentication.");
// 初始化SP 证书
initCredential(spId);
SAMLMessageContext messageContext = null;
/*
try {
messageContext = bindingAdapter.extractSAMLMessageContext(request);
} catch (MessageDecodingException me) {
logger.error("Could not decode SAML Response", me);
throw new Exception(me);
} catch (SecurityException se) {
logger.error("Could not decode SAML Response", se);
throw new Exception(se);
}*/
logger.debug("Message received from issuer: " + messageContext.getInboundMessageIssuer());
if (!(messageContext.getInboundSAMLMessage() instanceof Response)) {
logger.error("SAML Message was not a Response");
throw new Exception();
}
List<Assertion> assertionList = ((Response) messageContext.getInboundSAMLMessage()).getAssertions();
String credentials = extractBindingAdapter.extractSAMLMessage(request);
// 未认证token
Response samlResponse = (Response) messageContext.getInboundSAMLMessage();
AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = new WebAuthenticationDetailsSource();
try {
validatorSuite.validate(samlResponse);
} catch (ValidationException ve) {
logger.warn("Response Message failed Validation", ve);
throw new ServiceProviderAuthenticationException("Invalid SAML REsponse Message", ve);
}
checkResponseStatus(samlResponse);
Assertion assertion = samlResponse.getAssertions().get(0);
logger.debug("authenticationResponseIssuingEntityName {}", samlResponse.getIssuer().getValue());
String username = assertion.getSubject().getNameID().getValue();
logger.debug("assertion.getID() ", assertion.getID());
logger.debug("assertion.getSubject().getNameID().getValue() ", username);
logger.debug("assertion.getID() ", assertion.getAuthnStatements());
LoginCredential loginCredential = new LoginCredential(username, "", ConstsLoginType.SAMLTRUST);
authenticationProvider.authentication(loginCredential, true);
ModelAndView mav = new ModelAndView();
mav.addObject("username", username);
mav.setViewName("redirect:/appList");
return mav;
}
use of org.maxkey.authn.LoginCredential in project MaxKey by dromara.
the class CasRestV1Endpoint method casLoginRestUsers.
@Operation(summary = "CAS REST认证接口", description = "用户名密码登录接口", method = "POST")
@RequestMapping(value = CasConstants.ENDPOINT.ENDPOINT_REST_USERS_V1, method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity<String> casLoginRestUsers(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = CasConstants.PARAMETER.SERVICE, required = false) String casService, @RequestParam(value = CasConstants.PARAMETER.REST_USERNAME, required = true) String username, @RequestParam(value = CasConstants.PARAMETER.REST_PASSWORD, required = true) String password) {
try {
if (password == null || password.isEmpty()) {
throw new BadCredentialsException("No credentials are provided or extracted to authenticate the REST request");
}
LoginCredential loginCredential = new LoginCredential(username, password, "CASREST");
authenticationProvider.authentication(loginCredential, false);
UserInfo userInfo = WebContext.getUserInfo();
TicketGrantingTicketImpl ticketGrantingTicket = new TicketGrantingTicketImpl("Random", WebContext.getAuthentication(), null);
String ticket = casTicketGrantingTicketServices.createTicket(ticketGrantingTicket);
String location = applicationConfig.getServerPrefix() + CasConstants.ENDPOINT.ENDPOINT_REST_TICKET_V1 + ticket;
HttpHeaders headers = new HttpHeaders();
headers.add("location", location);
ServiceResponseBuilder serviceResponseBuilder = new ServiceResponseBuilder();
serviceResponseBuilder.setFormat(HttpResponseConstants.FORMAT_TYPE.JSON);
// for user
serviceResponseBuilder.setAttribute("userId", userInfo.getId());
serviceResponseBuilder.setAttribute("displayName", userInfo.getDisplayName());
serviceResponseBuilder.setAttribute("firstName", userInfo.getGivenName());
serviceResponseBuilder.setAttribute("lastname", userInfo.getFamilyName());
serviceResponseBuilder.setAttribute("mobile", userInfo.getMobile());
serviceResponseBuilder.setAttribute("birthday", userInfo.getBirthDate());
serviceResponseBuilder.setAttribute("gender", userInfo.getGender() + "");
// for work
serviceResponseBuilder.setAttribute("employeeNumber", userInfo.getEmployeeNumber());
serviceResponseBuilder.setAttribute("title", userInfo.getJobTitle());
serviceResponseBuilder.setAttribute("email", userInfo.getWorkEmail());
serviceResponseBuilder.setAttribute("department", userInfo.getDepartment());
serviceResponseBuilder.setAttribute("departmentId", userInfo.getDepartmentId());
serviceResponseBuilder.setAttribute("workRegion", userInfo.getWorkRegion());
serviceResponseBuilder.success().setUser(userInfo.getUsername());
return new ResponseEntity<>(serviceResponseBuilder.serviceResponseBuilder(), headers, HttpStatus.OK);
} catch (final AuthenticationException e) {
_logger.error("BadCredentialsException ", e);
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
} catch (final Exception e) {
_logger.error("Exception ", e);
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Aggregations