List of usage examples for javax.servlet.http HttpServletResponse SC_UNAUTHORIZED
int SC_UNAUTHORIZED
To view the source code for javax.servlet.http HttpServletResponse SC_UNAUTHORIZED.
Click Source Link
From source file:org.openmrs.module.hl7query.web.controller.BaseHL7QueryController.java
@ExceptionHandler(APIAuthenticationException.class) @ResponseBody//from w w w. ja v a2s.c o m public AuthenticationErrorObject apiAuthenticationExceptionHandler(Exception ex, HttpServletResponse response) throws Exception { if (Context.isAuthenticated()) { // user is logged in but doesn't have the relevant privilege -> 403 FORBIDDEN errorCode = HttpServletResponse.SC_FORBIDDEN; errorDetail = "User is logged in but doesn't have the relevant privilege"; } else { // user is not logged in -> 401 UNAUTHORIZED errorCode = HttpServletResponse.SC_UNAUTHORIZED; errorDetail = "User is not logged in"; response.addHeader("WWW-Authenticate", "Basic realm=\"OpenMRS at " + HL7QueryConstants.URI_PREFIX); } response.setStatus(errorCode); return ExceptionUtil.wrapErrorResponse(ex, errorDetail); }
From source file:de.mpg.escidoc.services.aa.web.client.BasicAaClient.java
private boolean testLogin(HttpServletRequest request, HttpServletResponse response) throws Exception { String auth = request.getHeader("authorization"); if (auth == null) { response.addHeader("WWW-Authenticate", "Basic realm=\"Validation Service\""); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } else {//w w w .j a va2 s . c o m auth = auth.substring(6); String cred = new String(Base64.decodeBase64(auth.getBytes())); if (cred.contains(":")) { String[] userPass = cred.split(":"); String userName = "admin"; String password = "nimda"; if (!userPass[0].equals(userName) || !userPass[1].equals(password)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return false; } else { return true; } } else { response.sendError(HttpServletResponse.SC_FORBIDDEN); return false; } } }
From source file:org.craftercms.security.authentication.impl.LoginFailureHandlerImplTest.java
@Test public void testSendError() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); RequestContext context = new RequestContext(request, response); handler.handle(context, new AuthenticationException()); assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus()); assertTrue(response.isCommitted());//from w w w. ja v a2s .com }
From source file:ch.wisv.areafiftylan.security.TokenAuthenticationFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String xAuth = ((HttpServletRequest) request).getHeader("X-Auth-Token"); if (!Strings.isNullOrEmpty(xAuth)) { AuthenticationToken authenticationToken = extractOptional( authenticationTokenRepository.findByToken(xAuth), response); if (authenticationToken.isValid()) { User user = authenticationToken.getUser(); SecurityContextHolder.getContext().setAuthentication( new PreAuthenticatedAuthenticationToken(user, "N/A", user.getAuthorities())); } else {/*from w ww .j av a 2 s .c o m*/ ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token Expired"); } } chain.doFilter(request, response); }
From source file:com.thoughtworks.go.server.security.GoExceptionTranslationFilter.java
protected void sendStartAuthentication(ServletRequest request, ServletResponse response, FilterChain chain, AuthenticationException reason) throws ServletException, IOException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; //TODO: This is a hack for bug #3175, we should revisit this code in V2.0 if (isJson(httpRequest) || isJsonFormat(httpRequest)) { httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return;//from ww w . jav a 2s. c o m } final Log logger = LogFactory.getLog(GoExceptionTranslationFilter.class); SavedRequest savedRequest = new SavedRequest(httpRequest, getPortResolver()); if (logger.isDebugEnabled()) { logger.debug("Authentication entry point being called; SavedRequest added to Session: " + savedRequest); } if (isCreateSessionAllowed() && shouldRedirect(savedRequest.getRequestUrl())) { // Store the HTTP request itself. Used by AbstractProcessingFilter // for redirection after successful authentication (SEC-29) httpRequest.getSession().setAttribute(AbstractProcessingFilter.SPRING_SECURITY_SAVED_REQUEST_KEY, savedRequest); } // SEC-112: Clear the SecurityContextHolder's Authentication, as the // existing Authentication is no longer considered valid SecurityContextHolder.getContext().setAuthentication(null); determineAuthenticationPoint(httpRequest).commence(httpRequest, response, reason); }
From source file:com.jl.crm.web.OAuthTest.java
@Test public void oauthLoginForJson() throws Exception { request.addHeader("Accept", MediaType.APPLICATION_JSON_VALUE); springSecurityFilterChain.doFilter(request, response, chain); assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus()); assertEquals(/*w w w . ja v a 2 s .co m*/ "Bearer realm=\"oauth\", error=\"unauthorized\", error_description=\"Full authentication is required to access this resource\"", response.getHeader("WWW-Authenticate")); }
From source file:com.gst.infrastructure.security.service.CustomAuthenticationFailureHandler.java
/** * Performs the redirect or forward to the {@code defaultFailureUrl} if set, * otherwise returns a 401 error code.//from www . ja v a 2 s. co m * <p> * If redirecting or forwarding, {@code saveException} will be called to * cache the exception for use in the target view. */ @Override public void onAuthenticationFailure(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException exception) throws IOException, ServletException { if (this.defaultFailureUrl == null) { this.logger.debug("No failure URL set, sending 401 Unauthorized error"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication Failed: " + exception.getMessage()); } else { saveException(request, exception); if (this.forwardToDestination) { this.logger.debug("Forwarding to " + this.defaultFailureUrl); request.getRequestDispatcher(this.defaultFailureUrl).forward(request, response); } else { this.logger.debug("Redirecting to " + this.defaultFailureUrl); final String oauthToken = request.getParameter("oauth_token"); request.setAttribute("oauth_token", oauthToken); final String url = this.defaultFailureUrl + "?oauth_token=" + oauthToken; this.redirectStrategy.sendRedirect(request, response, url); } } }
From source file:com.todo.backend.security.JWTFilter.java
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { try {/*w w w .jav a 2s . c o m*/ final HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; final Optional<String> jwtToken = extractToken(httpServletRequest); if (jwtToken.isPresent()) { final Authentication authentication = JWTUtils.getAuthentication(jwtToken.get(), secretKey); SecurityContextHolder.getContext().setAuthentication(authentication); } filterChain.doFilter(servletRequest, servletResponse); } catch (ExpiredJwtException e) { log.debug("Security exception for user {} - {}. Expired token.", e.getClaims().getSubject(), e.getMessage()); ((HttpServletResponse) servletResponse).sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication token expired!"); } catch (JwtException e) { log.debug("Authentication token is invalid. {}", e.getMessage()); ((HttpServletResponse) servletResponse).sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication token is invalid!"); } }
From source file:com.liferay.sync.engine.documentlibrary.handler.BaseHandler.java
@Override public void handleException(Exception e) { _logger.error(e.getMessage(), e);/*from w w w . jav a 2 s .c om*/ SyncAccount syncAccount = SyncAccountService.fetchSyncAccount(getSyncAccountId()); if (e instanceof FileNotFoundException) { SyncFile syncFile = (SyncFile) getParameterValue("syncFile"); if (syncFile.getVersion() == null) { SyncFileService.deleteSyncFile(syncFile); } } else if (e instanceof HttpHostConnectException) { syncAccount.setState(SyncAccount.STATE_DISCONNECTED); syncAccount.setUiEvent(SyncAccount.UI_EVENT_CONNECTION_EXCEPTION); SyncAccountService.update(syncAccount); retryServerConnection(); } else if (e instanceof HttpResponseException) { syncAccount.setState(SyncAccount.STATE_DISCONNECTED); HttpResponseException hre = (HttpResponseException) e; int statusCode = hre.getStatusCode(); if (statusCode == HttpServletResponse.SC_UNAUTHORIZED) { syncAccount.setUiEvent(SyncAccount.UI_EVENT_AUTHENTICATION_EXCEPTION); } else { syncAccount.setUiEvent(SyncAccount.UI_EVENT_CONNECTION_EXCEPTION); } SyncAccountService.update(syncAccount); } }
From source file:org.cloudfoundry.identity.uaa.error.JsonAwareAuthenticationEntryPointTests.java
@Test public void testCommenceWithHtmlAccept() throws Exception { request.addHeader("Accept", MediaType.TEXT_HTML_VALUE); entryPoint.commence(request, response, new BadCredentialsException("Bad")); assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus()); assertEquals("Bad", response.getErrorMessage()); }