Example usage for org.springframework.http HttpStatus UNAUTHORIZED

List of usage examples for org.springframework.http HttpStatus UNAUTHORIZED

Introduction

In this page you can find the example usage for org.springframework.http HttpStatus UNAUTHORIZED.

Prototype

HttpStatus UNAUTHORIZED

To view the source code for org.springframework.http HttpStatus UNAUTHORIZED.

Click Source Link

Document

401 Unauthorized .

Usage

From source file:com.wiiyaya.consumer.web.main.controller.ExceptionController.java

/**
 * ??//from w  ww  .  j av a  2  s  .c o m
 * @param request ?
 * @return ExceptionDto JSON
 */
@ExceptionHandler(value = AccessDeniedException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public ModelAndView accessDeniedException(HttpServletRequest request) {
    String errorMessage = messageSource.getMessage(MSG_ERROR_NO_PRIVILEGE, null,
            LocaleContextHolder.getLocale());
    return prepareExceptionInfo(request, HttpStatus.UNAUTHORIZED, MSG_ERROR_NO_PRIVILEGE, errorMessage);
}

From source file:gob.mx.salud.api.util.ResponseWrapper.java

/**
 * Genera una respuesta fallida del tipo <b>401-UNAUTHORIZED</b>
 * @param message// w  ww. j  ava 2s. c  o  m
 * @param data
 * @return {@code ResponseWrapper<T>}
 */
@SuppressWarnings("unchecked")
public ResponseWrapper<T> errorUnauthorized(String message, List<ErrorDetail> data) {
    error(ResponseWrapper.ERROR, HttpStatus.UNAUTHORIZED.value(), message, (T) data);
    return this;
}

From source file:io.pivotal.cla.config.SecurityConfig.java

private AuthenticationEntryPoint entryPoint() {
    LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> entryPoints = new LinkedHashMap<>();
    entryPoints.put(new AntPathRequestMatcher("/github/hooks/**"),
            new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED));
    entryPoints.put(new AntPathRequestMatcher("/admin/**"), new GitHubAuthenticationEntryPoint(
            oauthConfig.getMain(), "user:email,repo:status,admin:repo_hook,admin:org_hook,read:org"));
    BasicAuthenticationEntryPoint basicEntryPoint = new BasicAuthenticationEntryPoint();
    basicEntryPoint.setRealmName("Pivotal CLA");
    entryPoints.put(new AntPathRequestMatcher("/manage/**"), basicEntryPoint);
    DelegatingAuthenticationEntryPoint entryPoint = new DelegatingAuthenticationEntryPoint(entryPoints);
    entryPoint.setDefaultEntryPoint(new GitHubAuthenticationEntryPoint(oauthConfig.getMain(), "user:email"));
    return entryPoint;
}

From source file:org.echocat.marquardt.authority.spring.SpringAuthorityController.java

@ExceptionHandler(LoginFailedException.class)
@ResponseStatus(value = HttpStatus.UNAUTHORIZED, reason = "Login failed.")
public void handleAlreadyLoggedInException(final LoginFailedException ex) {
    LOGGER.info(ex.getMessage());/*from  w w w . j av  a 2  s .  c  o m*/
}

From source file:org.appverse.web.framework.backend.frontfacade.rest.authentication.simple.services.presentation.SimpleAuthenticationServiceImpl.java

/**
 * Authenticates an user. Requires basic authentication header.
 * @param httpServletRequest/*from www  . j a  v  a2s  .  c o  m*/
 * @param httpServletResponse
 * @return
 * @throws Exception
 */
@RequestMapping(value = "${appverse.frontfacade.rest.simpleAuthenticationEndpoint.path:/sec/simplelogin}", method = RequestMethod.POST)
public ResponseEntity<AuthorizationData> login(@RequestBody CredentialsVO credentials,
        HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
    try {
        if (credentials == null || credentials.getUsername() == null) {
            throw new BadCredentialsException("Invalid parameters");
        }
        // Authenticate principal and return authorization data
        AuthorizationData authData = userAndPasswordAuthenticationManager
                .authenticatePrincipal(credentials.getUsername(), credentials.getPassword());

        if (securityEnableCsrf) {
            // Obtain XSRFToken and add it as a response header
            // The token comes in the request (CsrFilter adds it) and we need to set it in the response so the clients 
            // have it to use it in the next requests
            CsrfToken csrfToken = (CsrfToken) httpServletRequest.getAttribute(CSRF_TOKEN_SESSION_ATTRIBUTE);
            httpServletResponse.addHeader(csrfToken.getHeaderName(), csrfToken.getToken());
        }

        // AuthorizationDataVO
        return new ResponseEntity<AuthorizationData>(authData, HttpStatus.OK);
    } catch (AuthenticationException e) {
        return new ResponseEntity<AuthorizationData>(HttpStatus.UNAUTHORIZED);
    }
}

From source file:aiai.ai.station.LaunchpadRequester.java

/**
 * this scheduler is being run at the station side
 *
 * long fixedDelay()//from w w w.ja v  a 2s.  c  o  m
 * Execute the annotated method with a fixed period in milliseconds between the end of the last invocation and the start of the next.
 */
public void fixedDelay() {
    if (globals.isUnitTesting) {
        return;
    }
    if (!globals.isStationEnabled) {
        return;
    }

    ExchangeData data = new ExchangeData();
    String stationId = stationService.getStationId();
    if (stationId == null) {
        data.setCommand(new Protocol.RequestStationId());
    }
    data.setStationId(stationId);

    if (stationId != null) {
        // always report about current active sequences, if we have actual stationId
        data.setCommand(stationTaskService.produceStationSequenceStatus());
        data.setCommand(stationService.produceReportStationStatus());
        final boolean b = stationTaskService.isNeedNewExperimentSequence(stationId);
        if (b) {
            data.setCommand(new Protocol.RequestTask(globals.isAcceptOnlySignedSnippets));
        }
        if (System.currentTimeMillis() - lastRequestForMissingResources > 15_000) {
            data.setCommand(new Protocol.CheckForMissingOutputResources());
            lastRequestForMissingResources = System.currentTimeMillis();
        }
    }

    reportSequenceProcessingResult(data);

    List<Command> cmds;
    synchronized (commands) {
        cmds = new ArrayList<>(commands);
        commands.clear();
    }
    data.setCommands(cmds);

    // !!! always use data.setCommand() for correct initializing stationId !!!

    // we have to pull new tasks from server constantly
    try {
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        headers.setContentType(MediaType.APPLICATION_JSON);
        if (globals.isSecureRestUrl) {
            String auth = globals.restUsername + '=' + globals.restToken + ':' + globals.stationRestPassword;
            byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.US_ASCII));
            String authHeader = "Basic " + new String(encodedAuth);
            headers.set("Authorization", authHeader);
        }

        HttpEntity<ExchangeData> request = new HttpEntity<>(data, headers);

        ResponseEntity<ExchangeData> response = restTemplate.exchange(globals.serverRestUrl, HttpMethod.POST,
                request, ExchangeData.class);
        ExchangeData result = response.getBody();

        addCommands(commandProcessor.processExchangeData(result).getCommands());
        log.debug("fixedDelay(), {}", result);
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode() == HttpStatus.UNAUTHORIZED) {
            log.error("Error 401 accessing url {}, globals.isSecureRestUrl: {}", globals.serverRestUrl,
                    globals.isSecureRestUrl);
        } else {
            throw e;
        }
    } catch (RestClientException e) {
        log.error("Error accessing url: {}", globals.serverRestUrl);
        log.error("Stacktrace", e);
    }
}

From source file:org.mifos.module.sms.controller.MifosSmsController.java

@ExceptionHandler
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public void handleInvalidApiKeyException(final InvalidApiKeyException ex) {

}

From source file:com.github.ibole.infrastructure.web.security.spring.shiro.filter.StatelessAuthFilter.java

@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {

    JwtObject jwtObject = JwtObject.getEmpty();
    boolean loggedIn = false;
    try {/*w  ww.  jav a2 s. c  o m*/

        if (isLoginRequest(request, response)) {
            loggedIn = executeLogin(request, response);
        }

        if (reequestWithToken(request, response)) {
            String jwtToken = WsWebUtil.getTokenFromHeader(WebUtils.toHttp(request));
            if (Strings.isNullOrEmpty(jwtToken)) {
                loggedIn = false;
            } else {
                jwtObject = JoseUtils.claimsOfTokenWithoutValidation(jwtToken);
                StatelessToken token = new StatelessToken(jwtToken, jwtObject.getLoginId(),
                        jwtObject.getClientId());
                // Delegate to Realm {@link StatelessRealm} to authenticate the request
                Subject subject = getSubject(request, response);
                subject.login(token);
                loggedIn = true;
                logger.debug("Authenticated successfully for '{}' from '{}'!", jwtObject.getLoginId(),
                        jwtObject.getClientId());
            }
        }

    } catch (AuthenticationServiceException ex) {
        loggedIn = false;
        logger.error("Authenticated failed for '{}' from '{}' - ", jwtObject.getLoginId(),
                jwtObject.getClientId(), ex.getMessage());
        onLoginFail(response, HttpStatus.UNAUTHORIZED, ex.getErrorStatus());
    } catch (Exception ex) {
        loggedIn = false;
        logger.error("Authenticated failed for '{}' from '{}' - ", jwtObject.getLoginId(),
                jwtObject.getClientId(), ex.getMessage());
    }

    if (!loggedIn) {
        onLoginFail(response, HttpStatus.UNAUTHORIZED, HttpErrorStatus.ACCOUNT_INVALID);
    }

    return loggedIn;
}

From source file:edu.kit.scc.RestServiceController.java

/**
 * Unlinking endpoint./*from w ww . j  a v a  2 s  . c om*/
 * 
 * @param basicAuthorization authorization header value
 * @param scimUsers a JSON serialized list of SCIM users for unlinking
 * @param response the HttpServletResponse
 * @return A JSON serialized list of SCIM users containing the local user information.
 */
@RequestMapping(path = "/unlink", method = RequestMethod.POST, consumes = "application/scim+json", produces = "application/scim+json")
public ResponseEntity<?> unlinkUsers(@RequestHeader("Authorization") String basicAuthorization,
        @RequestBody List<ScimUser> scimUsers, HttpServletResponse response) {

    if (!verifyAuthorization(basicAuthorization)) {
        return new ResponseEntity<String>("REST Service Unauthorized", HttpStatus.UNAUTHORIZED);
    }

    log.debug("Request body {}", scimUsers);

    List<ScimUser> modifiedUsers = identityHarmonizer.unlinkUsers(scimUsers);
    if (!modifiedUsers.isEmpty()) {
        return new ResponseEntity<List<ScimUser>>(modifiedUsers, HttpStatus.OK);
    }

    return new ResponseEntity<String>("Conflicting information", HttpStatus.CONFLICT);
}

From source file:com.xyxy.platform.examples.showcase.functional.rest.UserRestFT.java

/**
 * ?ShiroHttpBasic?/*from  w  w w.ja  va  2  s  .  c  o  m*/
 */
@Test
public void authWithHttpBasic() {
    // Http Basic?
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.set(com.google.common.net.HttpHeaders.AUTHORIZATION,
            Servlets.encodeHttpBasic("admin", "wrongpassword"));
    HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);

    try {
        jdkTemplate.exchange(resourceUrl + "/{id}.xml", HttpMethod.GET, requestEntity, UserDTO.class, 1L);
        fail("Get should fail with error username/password");
    } catch (HttpStatusCodeException e) {
        assertThat(e.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
    }
}