Construct local login Service Url

@param request
@param response
@param service
@param serverName
@param artifactParameterName
@param encode
490300
public String constructLocalLoginServiceUrl(final HttpServletRequest request,
      final HttpServletResponse response, final String service, final String serverName,
      final String artifactParameterName, final boolean encode) {
    if (Strings.isNotBlank(service)) return encode ? response.encodeURL(service) : service;
    final StringBuilder buffer = new StringBuilder();

    if (!serverName.startsWith("https://") && !serverName.startsWith("http://")) {
      buffer.append(request.isSecure() ? "https://" : "http://");
    }
    buffer.append(serverName);
    buffer.append(request.getContextPath());
    buffer.append(localLogin);
    final String returnValue = encode ? response.encodeURL(buffer.toString()) : buffer.toString();
    return returnValue;
  }
275999
@GetMapping(produces = MediaType.APPLICATION_XML_VALUE)
    @ResponseBody
    public ResponseEntity<Object> produce(final HttpServletRequest request, final HttpServletResponse response) {
        val username = request.getParameter("username");
        val password = request.getParameter("password");
        val entityId = request.getParameter(SamlProtocolConstants.PARAMETER_ENTITY_ID);

        try {
            val selectedService = this.serviceFactory.createService(entityId);
            val registeredService = this.servicesManager.findServiceBy(selectedService, SamlRegisteredService.class);
            RegisteredServiceAccessStrategyUtils.ensureServiceAccessIsAllowed(registeredService);

            val assertion = getAssertion(username, password, entityId);
            val authnRequest = new AuthnRequestBuilder().buildObject();
            authnRequest.setIssuer(saml20ObjectBuilder.newIssuer(entityId));

            val adaptorResult = SamlRegisteredServiceServiceProviderMetadataFacade.get(defaultSamlRegisteredServiceCachingMetadataResolver,
                registeredService, entityId);
            if (adaptorResult.isPresent()) {
                val adaptor = adaptorResult.get();
                val messageContext = new MessageContext<>();
                val scratch = messageContext.getSubcontext(ScratchContext.class, true);
                scratch.getMap().put(SamlProtocolConstants.PARAMETER_ENCODE_RESPONSE, Boolean.FALSE);

                val object = this.responseBuilder.build(authnRequest, request, response, assertion,
                    registeredService, adaptor, SAMLConstants.SAML2_POST_BINDING_URI, messageContext);
                val encoded = SamlUtils.transformSamlObject(saml20ObjectBuilder.getOpenSamlConfigBean(), object).toString();
                return new ResponseEntity<>(encoded, HttpStatus.OK);
            }
        } catch (final Exception e) {
            LOGGER.error(e.getMessage(), e);
            return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
588636
public void bindServer(HttpServletRequest request, HttpServletResponse response){
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(StrUtil.isBlank(getToken()) || StrUtil.isBlank(getAESKey()) || StrUtil.isBlank(getCropId())){
            pw.write("");
            pw.flush();
            pw.close();
        }
        try {
            WXBizMsgCrypt pc = new WXBizMsgCrypt(getToken(), getAESKey(), getCropId());
            String echoStr = pc.verifyUrl(request.getParameter("msg_signature"), request.getParameter("timestamp"), request.getParameter("nonce"), request.getParameter("echostr"));
            pw.write(echoStr);
            pw.flush();
            pw.close();
        } catch (AesException e) {
            e.printStackTrace();
            pw.write("");
            pw.flush();
            pw.close();
        }
    }
1045154
def _login_url(service, ticket='ST', gateway=False):
    

    LOGINS = {'ST': 'login',
              'PT': 'proxyValidate'}
    if gateway:
        params = {'service': service, 'gateway': 'true'}
    else:
        params = {'service': service}

    if settings.CAS_EXTRA_LOGIN_PARAMS:
        params.update(settings.CAS_EXTRA_LOGIN_PARAMS)

    if not ticket:
        ticket = 'ST'

    login_type = LOGINS.get(ticket[:2], 'login')

    return urlparse.urljoin(settings.CAS_SERVER_URL, login_type) + '?' + urlencode(params)
1338197
@Override
    protected int authenticated(final Request request, final Response response)
    {
        try
        {
            final CookieSetting credentialsCookie = this.getCredentialsCookie(request, response);
            credentialsCookie.setValue(this.formatCredentials(request.getChallengeResponse()));
            credentialsCookie.setMaxAge(this.getMaxCookieAge());
        }
        catch(final GeneralSecurityException e)
        {
            this.log.error("Could not format credentials cookie", e);
        }
        
        // log.info("calling super.authenticated");
        // return super.authenticated(request, response);
        
        // Modified copy of Authenticator.authenticated
        if(this.log.isDebugEnabled())
        {
            this.log.debug("The authentication succeeded for the identifer \"{}\" using the {} scheme.", request
                    .getChallengeResponse().getIdentifier(), request.getChallengeResponse().getScheme());
        }
        
        // Update the client info accordingly
        if(request.getClientInfo() != null)
        {
            request.getClientInfo().setAuthenticated(true);
        }
        
        // Clear previous challenge requests
        response.getChallengeRequests().clear();
        
        // Add the roles for the authenticated subject
        if(this.getEnroler() != null)
        {
            this.getEnroler().enrole(request.getClientInfo());
        }
        
        // Return STOP here works for login but not for subsequent requests that expect a response
        // return STOP;
        return Filter.CONTINUE;
    }
242071
private String buildOAuth1Url(OAuth1ConnectionFactory<?> connectionFactory, NativeWebRequest request, MultiValueMap<String, String> additionalParameters) {
		OAuth1Operations oauthOperations = connectionFactory.getOAuthOperations();
		MultiValueMap<String, String> requestParameters = getRequestParameters(request);
		OAuth1Parameters parameters = getOAuth1Parameters(request, additionalParameters);
		parameters.putAll(requestParameters);
		if (oauthOperations.getVersion() == OAuth1Version.CORE_10) {
			parameters.setCallbackUrl(callbackUrl(request));
		}
		OAuthToken requestToken = fetchRequestToken(request, requestParameters, oauthOperations);
		sessionStrategy.setAttribute(request, OAUTH_TOKEN_ATTRIBUTE, requestToken);
		return buildOAuth1Url(oauthOperations, requestToken.getValue(), parameters);
	}
498958
@Override
    public final CacheKey getCacheKey(HttpServletRequest request, HttpServletResponse response) {
        final Resource stylesheetResource = this.getStylesheetResource(request);
        final Serializable stylesheetCacheKey;
        try {
            stylesheetCacheKey = this.xmlUtilities.getStylesheetCacheKey(stylesheetResource);
        } catch (TransformerConfigurationException e) {
            throw new RuntimeException(
                    "Failed to get Transformer for stylesheet: " + stylesheetResource, e);
        } catch (IOException e) {
            throw new RuntimeException("Failed to load stylesheet: " + stylesheetResource, e);
        }

        return CacheKey.build(stylesheetResource.getDescription(), stylesheetCacheKey);
    }
245860
protected String constructLoginURL(HttpServletRequest request, boolean isXMLRequest) {
        String delimiter = "?";
        if (authenticationProviderUrl.contains("?")) {
            delimiter = "&";
        }
        StringBuilder loginURL = new StringBuilder();
        if (isXMLRequest) {
            String atlasApplicationURL = "";
            String referalURL = request.getHeader("referer");

            if (referalURL == null) {
                atlasApplicationURL = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
            } else {
                atlasApplicationURL = referalURL;
            }

            loginURL.append(authenticationProviderUrl).append(delimiter).append(originalUrlQueryParam).append("=").append(atlasApplicationURL);
        } else {
            loginURL.append(authenticationProviderUrl).append(delimiter).append(originalUrlQueryParam).append("=").append(request.getRequestURL().append(getOriginalQueryString(request)));
        }
        return loginURL.toString();
    }
1075171
private ApiResponse buildResponseFromContext(Context c) {
		Map<String, String> fields = new HashMap<>();
		fields.put("name", c.getName());
		fields.put("id", Integer.toString(c.getIndex()));
		fields.put("description", c.getDescription());
		fields.put("inScope", Boolean.toString(c.isInScope()));
		fields.put("excludeRegexs", jsonEncodeList(c.getExcludeFromContextRegexs()));
		fields.put("includeRegexs", jsonEncodeList(c.getIncludeInContextRegexs()));
		
		AuthenticationMethod authenticationMethod = c.getAuthenticationMethod();
		if(authenticationMethod != null){
			Pattern pattern = authenticationMethod.getLoggedInIndicatorPattern();
			fields.put("loggedInPattern",  pattern == null ? "" : pattern.toString());
			pattern = authenticationMethod.getLoggedOutIndicatorPattern();
			fields.put("loggedOutPattern", pattern == null ? "" : pattern.toString());
			AuthenticationMethodType type = authenticationMethod.getType();
			fields.put("authType", type == null ? "" : type.getName());
		}
		
		AuthorizationDetectionMethod authorizationDetectionMethod = c.getAuthorizationDetectionMethod();
		if(authorizationDetectionMethod != null){
			fields.put("authenticationDetectionMethodId",String.valueOf(authorizationDetectionMethod.getMethodUniqueIdentifier()));
		}
		
		fields.put("urlParameterParserClass", c.getUrlParamParser().getClass().getCanonicalName());
		fields.put("urlParameterParserConfig", c.getUrlParamParser().getConfig());
		fields.put("postParameterParserClass", c.getPostParamParser().getClass().getCanonicalName());
		fields.put("postParameterParserConfig", c.getPostParamParser().getConfig());
		
		return new ApiResponseSet<String>("context", fields);
	}
256482
@POST
    @Produces(MediaType.TEXT_PLAIN)
    @ApiOperation(
            value = "Assert login credentials",
            notes = "Upon a successful login, a JWT will be returned in the response. This functionality requires authentication to be enabled.",
            response = String.class
    )
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Success"),
            @ApiResponse(code = 401, message = "Unauthorized")
    })
    @AuthenticationNotRequired
    public Response validateCredentials(@FormParam("username") String username, @FormParam("password") String password) {
        final Authenticator auth = new Authenticator(username, password);
        try {
            final Principal principal = auth.authenticate();
            if (principal != null) {
                LOGGER.info(SecurityMarkers.SECURITY_AUDIT, "Login succeeded (username: " + username
                        + " / ip address: " + super.getRemoteAddress()
                        + " / agent: " + super.getUserAgent() + ")");

                final JsonWebToken jwt = new JsonWebToken();
                final String token = jwt.createToken(principal);
                return Response.ok(token).build();
            }
        } catch (AuthenticationException e) {
            LOGGER.warn(SecurityMarkers.SECURITY_AUDIT, "Unauthorized login attempt (username: "
                    + username + " / ip address: " + super.getRemoteAddress()
                    + " / agent: " + super.getUserAgent() + ")");
        }
        return Response.status(Response.Status.UNAUTHORIZED).build();
    }
1146988
public void saveRequestUrlAndParameters(HttpServletRequest request, HttpServletResponse response) {
        String cookieName = ReferrerURLCookieHandler.REFERRER_URL_COOKIENAME;
        ReferrerURLCookieHandler referrerURLCookieHandler = getCookieHandler();
        Cookie c = referrerURLCookieHandler.createCookie(cookieName, getRequestUrlWithEncodedQueryString(request), request);
        response.addCookie(c);

        savePostParameters(request, response);
    }
542751
@SneakyThrows
    protected String constructServiceUrl(final HttpServletRequest request,
                                         final HttpServletResponse response,
                                         final Pair<? extends SignableSAMLObject, MessageContext> pair) throws SamlException {
        val authnRequest = (AuthnRequest) pair.getLeft();
        val messageContext = pair.getRight();

        try (val writer = SamlUtils.transformSamlObject(samlProfileHandlerConfigurationContext.getOpenSamlConfigBean(), authnRequest)) {
            val builder = new URLBuilder(samlProfileHandlerConfigurationContext.getCallbackService().getId());
            builder.getQueryParams().add(
                new net.shibboleth.utilities.java.support.collection.Pair<>(SamlProtocolConstants.PARAMETER_ENTITY_ID,
                    SamlIdPUtils.getIssuerFromSamlObject(authnRequest)));

            val samlRequest = EncodingUtils.encodeBase64(writer.toString().getBytes(StandardCharsets.UTF_8));
            builder.getQueryParams().add(
                new net.shibboleth.utilities.java.support.collection.Pair<>(SamlProtocolConstants.PARAMETER_SAML_REQUEST,
                    samlRequest));
            builder.getQueryParams().add(
                new net.shibboleth.utilities.java.support.collection.Pair<>(SamlProtocolConstants.PARAMETER_SAML_RELAY_STATE,
                    SAMLBindingSupport.getRelayState(messageContext)));
            val url = builder.buildURL();

            LOGGER.trace("Built service callback url [{}]", url);
            return CommonUtils.constructServiceUrl(request, response,
                url, samlProfileHandlerConfigurationContext.getCasProperties().getServer().getName(),
                CasProtocolConstants.PARAMETER_SERVICE,
                CasProtocolConstants.PARAMETER_TICKET, false);
        }
    }
205546
@Override
    public List<Object> loginRequest() {
        if (loginParams == null)
            return null;
        return Arrays.asList("POST", loginPath, loginParams);
    }
1001739
@PostMapping(value = "/v1/users", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public ResponseEntity<String> createTicketGrantingTicket(@RequestBody final MultiValueMap<String, String> requestBody,
                                                             final HttpServletRequest request) {
        try {
            val credential = this.credentialFactory.fromRequest(request, requestBody);
            if (credential == null || credential.isEmpty()) {
                throw new BadRestRequestException("No credentials are provided or extracted to authenticate the REST request");
            }
            val service = this.serviceFactory.createService(request);
            val authenticationResult =
                authenticationSystemSupport.handleAndFinalizeSingleAuthenticationTransaction(service, credential);
            if (authenticationResult == null) {
                throw new FailedLoginException("Authentication failed");
            }
            return this.userAuthenticationResourceEntityResponseFactory.build(authenticationResult, request);
        } catch (final AuthenticationException e) {
            return RestResourceUtils.createResponseEntityForAuthnFailure(e, request, applicationContext);
        } catch (final BadRestRequestException e) {
            LOGGER.error(e.getMessage(), e);
            return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
        } catch (final Exception e) {
            LOGGER.error(e.getMessage(), e);
            return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
341785
@Override
    public HttpResponse loginFailed(ServiceRequestContext ctx, AggregatedHttpMessage req,
                                    @Nullable MessageContext<Response> message, Throwable cause) {
        return HttpResponse.of(HttpStatus.UNAUTHORIZED, MediaType.HTML_UTF_8,
                               "<html><body>Login failed.</body></html>");
    }
616834
@NoAuth
    @RequestMapping(value = "/signin", method = RequestMethod.POST)
    @ResponseBody
    public JsonObjectBase signin(@Valid SigninForm signin, HttpServletRequest request) {

        LOG.info(signin.toString());

        // 验证
        authValidator.validateLogin(signin);

        // 数据库登录
        User user = signMgr.signin(signin.getName());

        // 过期时间
        int expireTime = LoginConstant.SESSION_EXPIRE_TIME;
        if (signin.getRemember().equals(1)) {
            expireTime = LoginConstant.SESSION_EXPIRE_TIME2;
        }

        // redis login
        redisLogin.login(request, user, expireTime);

        VisitorVo visitorVo = userMgr.getCurVisitor();

        return buildSuccess("visitor", visitorVo);
    }
141391
private void doClientSideRedirect(HttpServletResponse response, String loginURL, String state, String domain) throws IOException {

        response.setStatus(HttpServletResponse.SC_OK);
        PrintWriter pw = response.getWriter();
        pw.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
        pw.println("<head>");

        pw.println(createJavaScriptForRedirect(loginURL, state, domain));

        pw.println("<title>Redirect To OP</title> ");
        pw.println("</head>");
        pw.println("<body></body>");
        pw.println("</html>");

        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, private, max-age=0");
        // HTTP 1.0.
        response.setHeader("Pragma", "no-cache");
        // Proxies.
        response.setDateHeader("Expires", 0);
        response.setContentType("text/html; charset=UTF-8");

        pw.close();

    }