Search in sources :

Example 1 with LoginCredential

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;
}
Also used : BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) LoginCredential(org.maxkey.authn.LoginCredential)

Example 2 with LoginCredential

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;
}
Also used : Cookie(javax.servlet.http.Cookie) LoginCredential(org.maxkey.authn.LoginCredential) DateTime(org.joda.time.DateTime)

Example 3 with LoginCredential

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;
}
Also used : AssertionImpl(org.opensaml.saml1.core.impl.AssertionImpl) LoginCredential(org.maxkey.authn.LoginCredential)

Example 4 with LoginCredential

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;
}
Also used : ValidationException(org.opensaml.xml.validation.ValidationException) Assertion(org.opensaml.saml2.core.Assertion) ModelAndView(org.springframework.web.servlet.ModelAndView) MessageDecodingException(org.opensaml.ws.message.decoder.MessageDecodingException) IdentityProviderAuthenticationException(org.maxkey.authz.saml20.consumer.spring.IdentityProviderAuthenticationException) ValidationException(org.opensaml.xml.validation.ValidationException) SecurityException(org.opensaml.xml.security.SecurityException) ServiceProviderAuthenticationException(org.maxkey.authz.saml20.consumer.spring.ServiceProviderAuthenticationException) Response(org.opensaml.saml2.core.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) HttpServletRequest(javax.servlet.http.HttpServletRequest) SAMLMessageContext(org.opensaml.common.binding.SAMLMessageContext) ServiceProviderAuthenticationException(org.maxkey.authz.saml20.consumer.spring.ServiceProviderAuthenticationException) LoginCredential(org.maxkey.authn.LoginCredential) WebAuthenticationDetailsSource(org.springframework.security.web.authentication.WebAuthenticationDetailsSource) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 5 with LoginCredential

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);
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) ResponseEntity(org.springframework.http.ResponseEntity) AuthenticationException(org.springframework.security.core.AuthenticationException) UserInfo(org.maxkey.entity.UserInfo) TicketGrantingTicketImpl(org.maxkey.authz.cas.endpoint.ticket.TicketGrantingTicketImpl) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) LoginCredential(org.maxkey.authn.LoginCredential) ServiceResponseBuilder(org.maxkey.authz.cas.endpoint.response.ServiceResponseBuilder) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationException(org.springframework.security.core.AuthenticationException) Operation(io.swagger.v3.oas.annotations.Operation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

LoginCredential (org.maxkey.authn.LoginCredential)10 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)3 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)3 Operation (io.swagger.v3.oas.annotations.Operation)2 DateTime (org.joda.time.DateTime)2 TicketGrantingTicketImpl (org.maxkey.authz.cas.endpoint.ticket.TicketGrantingTicketImpl)2 HttpHeaders (org.springframework.http.HttpHeaders)2 ResponseEntity (org.springframework.http.ResponseEntity)2 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)2 AuthenticationException (org.springframework.security.core.AuthenticationException)2 SignedJWT (com.nimbusds.jwt.SignedJWT)1 Cookie (javax.servlet.http.Cookie)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 ServiceResponseBuilder (org.maxkey.authz.cas.endpoint.response.ServiceResponseBuilder)1 IdentityProviderAuthenticationException (org.maxkey.authz.saml20.consumer.spring.IdentityProviderAuthenticationException)1 ServiceProviderAuthenticationException (org.maxkey.authz.saml20.consumer.spring.ServiceProviderAuthenticationException)1 UserInfo (org.maxkey.entity.UserInfo)1 AuthorizationHeaderCredential (org.maxkey.util.AuthorizationHeaderCredential)1 SAMLMessageContext (org.opensaml.common.binding.SAMLMessageContext)1