本文整理汇总了Java中org.springframework.http.HttpStatus.UNAUTHORIZED属性的典型用法代码示例。如果您正苦于以下问题:Java HttpStatus.UNAUTHORIZED属性的具体用法?Java HttpStatus.UNAUTHORIZED怎么用?Java HttpStatus.UNAUTHORIZED使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类org.springframework.http.HttpStatus
的用法示例。
在下文中一共展示了HttpStatus.UNAUTHORIZED属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: authorize
@PostMapping("/authenticate")
@Timed
public ResponseEntity authorize(@Valid @RequestBody LoginVM loginVM, HttpServletResponse response) {
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(loginVM.getUsername(), loginVM.getPassword());
try {
Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
boolean rememberMe = (loginVM.isRememberMe() == null) ? false : loginVM.isRememberMe();
String jwt = tokenProvider.createToken(authentication, rememberMe);
response.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt);
return ResponseEntity.ok(new JWTToken(jwt));
} catch (AuthenticationException ae) {
log.trace("Authentication exception trace: {}", ae);
return new ResponseEntity<>(Collections.singletonMap("AuthenticationException",
ae.getLocalizedMessage()), HttpStatus.UNAUTHORIZED);
}
}
示例2: authorize
@PostMapping("/authenticate")
@Timed
public ResponseEntity<?> authorize(@Valid @RequestBody LoginVM loginVM, HttpServletResponse response) {
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(loginVM.getUsername(), loginVM.getPassword());
try {
Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
boolean rememberMe = (loginVM.isRememberMe() == null) ? false : loginVM.isRememberMe();
String jwt = tokenProvider.createToken(authentication, rememberMe);
response.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt);
return ResponseEntity.ok(new JWTToken(jwt));
} catch (AuthenticationException exception) {
return new ResponseEntity<>(Collections.singletonMap("AuthenticationException",exception.getLocalizedMessage()), HttpStatus.UNAUTHORIZED);
}
}
示例3: authorize
@RequestMapping(value = "/authenticate", method = RequestMethod.POST)
@Timed
public ResponseEntity<?> authorize(@Valid @RequestBody LoginDTO loginDTO, HttpServletResponse response) {
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(loginDTO.getUsername(), loginDTO.getPassword());
try {
Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
boolean rememberMe = (loginDTO.isRememberMe() == null) ? false : loginDTO.isRememberMe();
String jwt = tokenProvider.createToken(authentication, rememberMe);
response.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt);
return ResponseEntity.ok(new JWTToken(jwt));
} catch (AuthenticationException exception) {
return new ResponseEntity<>(Collections.singletonMap("AuthenticationException",exception.getLocalizedMessage()), HttpStatus.UNAUTHORIZED);
}
}
示例4: handleUncaughtException
@ResponseBody
@Order(Ordered.HIGHEST_PRECEDENCE)
@ExceptionHandler(Throwable.class)
public final ResponseEntity<Result<String>> handleUncaughtException(final Throwable exception, final WebRequest
request) {
// adds information about encountered error to application log
LOG.error(MessageHelper.getMessage("logger.error", request.getDescription(true)), exception);
HttpStatus code = HttpStatus.OK;
String message;
if (exception instanceof FileNotFoundException) {
// any details about real path of a resource should be normally prevented to send to the client
message = MessageHelper.getMessage("error.io.not.found");
} else if (exception instanceof DataAccessException) {
// any details about data access error should be normally prevented to send to the client,
// as its message can contain information about failed SQL query or/and database schema
if (exception instanceof BadSqlGrammarException) {
// for convenience we need to provide detailed information about occurred BadSqlGrammarException,
// but it can be retrieved
SQLException root = ((BadSqlGrammarException) exception).getSQLException();
if (root.getNextException() != null) {
LOG.error(MessageHelper.getMessage("logger.error.root.cause", request.getDescription(true)),
root.getNextException());
}
message = MessageHelper.getMessage("error.sql.bad.grammar");
} else {
message = MessageHelper.getMessage("error.sql");
}
} else if (exception instanceof UnauthorizedClientException) {
message = exception.getMessage();
code = HttpStatus.UNAUTHORIZED;
} else {
message = exception.getMessage();
}
return new ResponseEntity<>(Result.error(StringUtils.defaultString(StringUtils.trimToNull(message),
MessageHelper.getMessage("error" + ".default"))), code);
}
示例5: buildUnauthorizedResponseEntity
/**
* Build unauthorized response entity.
*
* @param code the code
* @return the response entity
*/
private static ResponseEntity buildUnauthorizedResponseEntity(final String code) {
final LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<>(1);
map.add(OAuth20Constants.ERROR, code);
final String value = OAuth20Utils.jsonify(map);
return new ResponseEntity<>(value, HttpStatus.UNAUTHORIZED);
}
示例6: checkUsernameAndPassword
@Override
public Account checkUsernameAndPassword(String username,String password) {
Account acc = queryByUsername(username);
if (acc == null || acc.getUid() == null){
logger.debug("username {} is not existing",username);
throw new AppException(HttpStatus.UNAUTHORIZED, ErrorMap.of("401001", "用户名不存在"));
}
if (!checkPassword(password, acc.getPassword())){
throw new AppException(HttpStatus.UNAUTHORIZED, ErrorMap.of("401001", "密码错误"));
}
return acc;
}
示例7: containerCustomizer
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return (container -> {
ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/401.html");
ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html");
ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.html");
container.addErrorPages(error401Page, error404Page, error500Page);
});
}
示例8: handleMessageException
/**
* Handles MessageException exception.
*
* @param exception the MessageException instance
* @param request the WebRequest caused exception
* @return the ResponseEntity object instance
*/
@ExceptionHandler(MessageException.class)
protected ResponseEntity<Object> handleMessageException(MessageException exception, WebRequest request) {
HttpStatus status;
switch (exception.getErrorType()) {
case NOT_FOUND:
status = HttpStatus.NOT_FOUND;
break;
case DATA_INVALID:
case PARAMETERS_INVALID:
status = HttpStatus.BAD_REQUEST;
break;
case ALREADY_EXISTS:
status = HttpStatus.CONFLICT;
break;
case AUTH_FAILED:
status = HttpStatus.UNAUTHORIZED;
break;
case OPERATION_TIMED_OUT:
case INTERNAL_ERROR:
default:
status = HttpStatus.INTERNAL_SERVER_ERROR;
break;
}
MessageError error = new MessageError(request.getHeader(CORRELATION_ID), exception.getTimestamp(),
status.value(), status.getReasonPhrase(),
exception.getMessage(), exception.getClass().getSimpleName());
return super.handleExceptionInternal(exception, error, new HttpHeaders(), status, request);
}
示例9: handleAccessDeniedException
@ExceptionHandler({ AccessDeniedException.class })
public ResponseEntity<Object> handleAccessDeniedException(final Exception ex, final HttpHeaders headers, final WebRequest request) {
logger.info(ex.getClass().getName());
logger.error("error", ex);
//
final AitException AitException = new AitException(HttpStatus.UNAUTHORIZED, "Acceso no permitido", "Su perfil no cuenta con los permisos necesarios para acceder al servicio solicitado");
return handleExceptionInternal(ex, AitException, headers, AitException.getStatus(), request);
}
示例10: handleClientErrors
private static void handleClientErrors(ClientHttpResponse response) throws IOException {
HttpStatus statusCode = response.getStatusCode();
Map<String, Object> errorMap = extractErrorDetailsFromResponse(response);
String errorText = "";
if (errorMap.containsKey("error")) {
errorText = (String) errorMap.get("error");
} else if (errorMap.containsKey("errors")) {
Object errors = errorMap.get("errors");
if (errors instanceof List) {
@SuppressWarnings("unchecked")
List<Map<String, String>> errorsList = (List<Map<String, String>>) errors;
errorText = errorsList.get(0).get("message");
} else if (errors instanceof String) {
errorText = (String) errors;
}
}
if (statusCode == HttpStatus.BAD_REQUEST) {
if (errorText.contains("Rate limit exceeded.")) {
throw new RateLimitExceededException(TWITTER);
}
} else if (statusCode == HttpStatus.UNAUTHORIZED) {
if (errorText == null) {
throw new NotAuthorizedException(TWITTER, response.getStatusText());
} else if ("Could not authenticate you.".equals(errorText)) {
throw new MissingAuthorizationException(TWITTER);
} else if ("Could not authenticate with OAuth.".equals(errorText)) { // revoked token
throw new RevokedAuthorizationException(TWITTER);
} else if ("Invalid / expired Token".equals(errorText)) {
// Note that Twitter doesn't actually expire tokens
throw new InvalidAuthorizationException(TWITTER, errorText);
} else {
throw new NotAuthorizedException(TWITTER, errorText);
}
} else if (statusCode == HttpStatus.FORBIDDEN) {
if (errorText.equals(DUPLICATE_STATUS_TEXT) || errorText.contains("You already said that")) {
throw new DuplicateStatusException(TWITTER, errorText);
} else if (errorText.equals(STATUS_TOO_LONG_TEXT) || errorText.contains(MESSAGE_TOO_LONG_TEXT)) {
throw new MessageTooLongException(errorText);
} else if (errorText.equals(INVALID_MESSAGE_RECIPIENT_TEXT)) {
throw new InvalidMessageRecipientException(errorText);
} else if (errorText.equals(DAILY_RATE_LIMIT_TEXT)) {
throw new RateLimitExceededException(TWITTER);
} else {
throw new OperationNotPermittedException(TWITTER, errorText);
}
} else if (statusCode == HttpStatus.NOT_FOUND) {
throw new ResourceNotFoundException(TWITTER, errorText);
} else if (statusCode == HttpStatus.valueOf(ENHANCE_YOUR_CALM) || statusCode == HttpStatus
.valueOf(TOO_MANY_REQUESTS)) {
throw new RateLimitExceededException(TWITTER);
}
}
示例11: unauthorizedAction
@ExceptionHandler(UnauthorizedActionException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ResponseBody
public ErrorInfo unauthorizedAction(HttpServletRequest req, Exception ex) {
return new ErrorInfo(req.getRequestURL().toString(), ex, HttpStatus.UNAUTHORIZED.value());
}
示例12: buildUnauthorizedResponseEntity
private static ResponseEntity buildUnauthorizedResponseEntity(String code) {
LinkedMultiValueMap map = new LinkedMultiValueMap(1);
map.add("error", code);
String value = OAuth20Utils.jsonify(map);
return new ResponseEntity(value, HttpStatus.UNAUTHORIZED);
}
示例13: unanthorized
@ExceptionHandler(UnauthorizedException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ResponseBody
public String unanthorized(UnauthorizedException e) {
return e.toString();
}
示例14: handleUnauthorized
@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
@ExceptionHandler(NoHomeserverTokenException.class)
@ResponseBody
MatrixErrorInfo handleUnauthorized(MatrixException e) {
return new MatrixErrorInfo(e.getErrorCode());
}
示例15: unauthorized
@RequestMapping("/401")
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public ResponseEntity unauthorized() {
return new ResponseEntity(401, "请求未授权", null);
}