use of javax.servlet.ServletResponse in project spring-framework by spring-projects.
the class RequestContextFilterTests method testFilterInvocation.
private void testFilterInvocation(final ServletException sex) throws Exception {
final MockHttpServletRequest req = new MockHttpServletRequest();
req.setAttribute("myAttr", "myValue");
final MockHttpServletResponse resp = new MockHttpServletResponse();
// Expect one invocation by the filter being tested
class DummyFilterChain implements FilterChain {
public int invocations = 0;
@Override
public void doFilter(ServletRequest req, ServletResponse resp) throws IOException, ServletException {
++invocations;
if (invocations == 1) {
assertSame("myValue", RequestContextHolder.currentRequestAttributes().getAttribute("myAttr", RequestAttributes.SCOPE_REQUEST));
if (sex != null) {
throw sex;
}
} else {
throw new IllegalStateException("Too many invocations");
}
}
}
;
DummyFilterChain fc = new DummyFilterChain();
MockFilterConfig mfc = new MockFilterConfig(new MockServletContext(), "foo");
RequestContextFilter rbf = new RequestContextFilter();
rbf.init(mfc);
try {
rbf.doFilter(req, resp, fc);
if (sex != null) {
fail();
}
} catch (ServletException ex) {
assertNotNull(sex);
}
try {
RequestContextHolder.currentRequestAttributes();
fail();
} catch (IllegalStateException ex) {
// Ok
}
assertEquals(1, fc.invocations);
}
use of javax.servlet.ServletResponse in project spring-framework by spring-projects.
the class HiddenHttpMethodFilterTests method filterWithParameter.
@Test
public void filterWithParameter() throws IOException, ServletException {
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/hotels");
request.addParameter("_method", "delete");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = new FilterChain() {
@Override
public void doFilter(ServletRequest filterRequest, ServletResponse filterResponse) throws IOException, ServletException {
assertEquals("Invalid method", "DELETE", ((HttpServletRequest) filterRequest).getMethod());
}
};
filter.doFilter(request, response, filterChain);
}
use of javax.servlet.ServletResponse in project spring-framework by spring-projects.
the class HiddenHttpMethodFilterTests method filterWithNoParameter.
@Test
public void filterWithNoParameter() throws IOException, ServletException {
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/hotels");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = new FilterChain() {
@Override
public void doFilter(ServletRequest filterRequest, ServletResponse filterResponse) throws IOException, ServletException {
assertEquals("Invalid method", "POST", ((HttpServletRequest) filterRequest).getMethod());
}
};
filter.doFilter(request, response, filterChain);
}
use of javax.servlet.ServletResponse in project spring-security by spring-projects.
the class GrantedAuthorityDefaultsXmlTests method doFilterIsUserInRole.
// SEC-2926
@Test
public void doFilterIsUserInRole() throws Exception {
SecurityContext context = SecurityContextHolder.getContext();
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
chain = new MockFilterChain() {
@Override
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
assertThat(httpRequest.isUserInRole("USER")).isTrue();
assertThat(httpRequest.isUserInRole("INVALID")).isFalse();
super.doFilter(request, response);
}
};
springSecurityFilterChain.doFilter(request, response, chain);
assertThat(chain.getRequest()).isNotNull();
}
use of javax.servlet.ServletResponse in project blade by biezhi.
the class FormAuthenticator method validateRequest.
/* ------------------------------------------------------------ */
@Override
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
Request base_request = Request.getBaseRequest(request);
Response base_response = base_request.getResponse();
String uri = request.getRequestURI();
if (uri == null)
uri = URIUtil.SLASH;
mandatory |= isJSecurityCheck(uri);
if (!mandatory)
return new DeferredAuthentication(this);
if (isLoginOrErrorPage(URIUtil.addPaths(request.getServletPath(), request.getPathInfo())) && !DeferredAuthentication.isDeferred(response))
return new DeferredAuthentication(this);
HttpSession session = request.getSession(true);
try {
// Handle a request for authentication.
if (isJSecurityCheck(uri)) {
final String username = request.getParameter(__J_USERNAME);
final String password = request.getParameter(__J_PASSWORD);
UserIdentity user = login(username, password, request);
LOG.debug("jsecuritycheck {} {}", username, user);
session = request.getSession(true);
if (user != null) {
// Redirect to original request
String nuri;
FormAuthentication form_auth;
synchronized (session) {
nuri = (String) session.getAttribute(__J_URI);
if (nuri == null || nuri.length() == 0) {
nuri = request.getContextPath();
if (nuri.length() == 0)
nuri = URIUtil.SLASH;
}
form_auth = new FormAuthentication(getAuthMethod(), user);
}
LOG.debug("authenticated {}->{}", form_auth, nuri);
response.setContentLength(0);
int redirectCode = (base_request.getHttpVersion().getVersion() < HttpVersion.HTTP_1_1.getVersion() ? HttpServletResponse.SC_MOVED_TEMPORARILY : HttpServletResponse.SC_SEE_OTHER);
base_response.sendRedirect(redirectCode, response.encodeRedirectURL(nuri));
return form_auth;
}
// not authenticated
if (LOG.isDebugEnabled())
LOG.debug("Form authentication FAILED for " + StringUtil.printable(username));
if (_formErrorPage == null) {
LOG.debug("auth failed {}->403", username);
if (response != null)
response.sendError(HttpServletResponse.SC_FORBIDDEN);
} else if (_dispatch) {
LOG.debug("auth failed {}=={}", username, _formErrorPage);
RequestDispatcher dispatcher = request.getRequestDispatcher(_formErrorPage);
response.setHeader(HttpHeader.CACHE_CONTROL.asString(), HttpHeaderValue.NO_CACHE.asString());
response.setDateHeader(HttpHeader.EXPIRES.asString(), 1);
dispatcher.forward(new FormRequest(request), new FormResponse(response));
} else {
LOG.debug("auth failed {}->{}", username, _formErrorPage);
int redirectCode = (base_request.getHttpVersion().getVersion() < HttpVersion.HTTP_1_1.getVersion() ? HttpServletResponse.SC_MOVED_TEMPORARILY : HttpServletResponse.SC_SEE_OTHER);
base_response.sendRedirect(redirectCode, response.encodeRedirectURL(URIUtil.addPaths(request.getContextPath(), _formErrorPage)));
}
return Authentication.SEND_FAILURE;
}
// Look for cached authentication
Authentication authentication = (Authentication) session.getAttribute(SessionAuthentication.__J_AUTHENTICATED);
if (authentication != null) {
// Has authentication been revoked?
if (authentication instanceof User && _loginService != null && !_loginService.validate(((User) authentication).getUserIdentity())) {
LOG.debug("auth revoked {}", authentication);
session.removeAttribute(SessionAuthentication.__J_AUTHENTICATED);
} else {
synchronized (session) {
String j_uri = (String) session.getAttribute(__J_URI);
if (j_uri != null) {
//check if the request is for the same url as the original and restore
//params if it was a post
LOG.debug("auth retry {}->{}", authentication, j_uri);
StringBuffer buf = request.getRequestURL();
if (request.getQueryString() != null)
buf.append("?").append(request.getQueryString());
if (j_uri.equals(buf.toString())) {
MultiMap<String> j_post = (MultiMap<String>) session.getAttribute(__J_POST);
if (j_post != null) {
LOG.debug("auth rePOST {}->{}", authentication, j_uri);
base_request.setContentParameters(j_post);
}
session.removeAttribute(__J_URI);
session.removeAttribute(__J_METHOD);
session.removeAttribute(__J_POST);
}
}
}
LOG.debug("auth {}", authentication);
return authentication;
}
}
// if we can't send challenge
if (DeferredAuthentication.isDeferred(response)) {
LOG.debug("auth deferred {}", session.getId());
return Authentication.UNAUTHENTICATED;
}
// remember the current URI
synchronized (session) {
// But only if it is not set already, or we save every uri that leads to a login form redirect
if (session.getAttribute(__J_URI) == null || _alwaysSaveUri) {
StringBuffer buf = request.getRequestURL();
if (request.getQueryString() != null)
buf.append("?").append(request.getQueryString());
session.setAttribute(__J_URI, buf.toString());
session.setAttribute(__J_METHOD, request.getMethod());
if (MimeTypes.Type.FORM_ENCODED.is(req.getContentType()) && HttpMethod.POST.is(request.getMethod())) {
MultiMap<String> formParameters = new MultiMap<>();
base_request.extractFormParameters(formParameters);
session.setAttribute(__J_POST, formParameters);
}
}
}
// send the the challenge
if (_dispatch) {
LOG.debug("challenge {}=={}", session.getId(), _formLoginPage);
RequestDispatcher dispatcher = request.getRequestDispatcher(_formLoginPage);
response.setHeader(HttpHeader.CACHE_CONTROL.asString(), HttpHeaderValue.NO_CACHE.asString());
response.setDateHeader(HttpHeader.EXPIRES.asString(), 1);
dispatcher.forward(new FormRequest(request), new FormResponse(response));
} else {
LOG.debug("challenge {}->{}", session.getId(), _formLoginPage);
int redirectCode = (base_request.getHttpVersion().getVersion() < HttpVersion.HTTP_1_1.getVersion() ? HttpServletResponse.SC_MOVED_TEMPORARILY : HttpServletResponse.SC_SEE_OTHER);
base_response.sendRedirect(redirectCode, response.encodeRedirectURL(URIUtil.addPaths(request.getContextPath(), _formLoginPage)));
}
return Authentication.SEND_CONTINUE;
} catch (IOException | ServletException e) {
throw new ServerAuthException(e);
}
}
Aggregations