Java Code Examples for org.springframework.http.HttpStatus#UNAUTHORIZED

The following examples show how to use org.springframework.http.HttpStatus#UNAUTHORIZED . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PageController.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@RestAccessControl(permission = Permission.SUPERUSER)
@RequestMapping(value = "/pages/{pageCode}/usage/details", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<PagedRestResponse<ComponentUsageEntity>> getComponentUsageDetails(@ModelAttribute("user") UserDetails user, @PathVariable String pageCode, PageSearchRequest searchRequest) {

    logger.trace("get {} usage details by code {}", COMPONENT_ID, pageCode);

    // clear filters
    searchRequest.setFilters(new Filter[0]);

    if (!this.getAuthorizationService().isAuth(user, pageCode)) {
        return new ResponseEntity<>(new PagedRestResponse<>(new PagedMetadata<>()), HttpStatus.UNAUTHORIZED);
    }

    PagedMetadata<ComponentUsageEntity> result = pageService.getComponentUsageDetails(pageCode, searchRequest);

    return new ResponseEntity<>(new PagedRestResponse<>(result), HttpStatus.OK);
}
 
Example 2
Source File: UserServiceImpl.java    From biliob_backend with MIT License 6 votes vote down vote up
@Override
public ResponseEntity<?> addFavoriteAuthor(@Valid Long mid) {
    User user = UserUtils.getFullInfo();
    if (user == null) {
        return new ResponseEntity<>(
                new Result<>(ResultEnum.HAS_NOT_LOGGED_IN), HttpStatus.UNAUTHORIZED);
    }
    ArrayList<Long> temp = new ArrayList<>();
    if (user.getFavoriteMid() != null) {
        temp = user.getFavoriteMid();
    }
    if (temp.contains(mid)) {
        UserServiceImpl.logger.warn("用户:{} 试图重复关注{}", user.getName(), mid);
        return new ResponseEntity<>(
                new Result<>(ResultEnum.ALREADY_FAVORITE_AUTHOR), HttpStatus.ACCEPTED);
    }
    temp.add(mid);
    user.setFavoriteMid(new ArrayList<>(temp));
    userRepository.save(user);
    UserServiceImpl.logger.info("用户:{} 关注了{}", user.getName(), mid);
    return new ResponseEntity<>(new Result(ResultEnum.ADD_FAVORITE_AUTHOR_SUCCEED), HttpStatus.OK);
}
 
Example 3
Source File: LoginController.java    From full-teaching with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/api-logIn")
public ResponseEntity<User> logIn() {
	
	System.out.println("Logging in...");

	if (!userComponent.isLoggedUser()) {
		
		System.out.println("Not user logged");
		
		log.info("Not user logged");
		return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
	} else {
		User loggedUser = userComponent.getLoggedUser();
		
		System.out.println("Logged as " + loggedUser.getName());
		
		log.info("Logged as " + loggedUser.getName());
		return new ResponseEntity<>(loggedUser, HttpStatus.OK);
	}
}
 
Example 4
Source File: UserServiceImpl.java    From biliob_backend with MIT License 6 votes vote down vote up
@Override
public ResponseEntity bindMail(String mail, String activationCode) {
    User user = UserUtils.getUser();
    if (user == null) {
        return new ResponseEntity<>(
                new Result(ResultEnum.HAS_NOT_LOGGED_IN), HttpStatus.UNAUTHORIZED);
    }
    if (!mailUtil.checkActivationCode(mail, activationCode)) {
        return new ResponseEntity<>(
                new Result(ResultEnum.ACTIVATION_CODE_UNMATCHED), HttpStatus.BAD_REQUEST);
    }
    if (mongoTemplate.exists(Query.query(Criteria.where("mail").is(mail)), User.class)) {
        return new ResponseEntity<>(
                new Result<>(ResultEnum.MAIL_HAD_BEEN_REGISTERED), HttpStatus.UNAUTHORIZED);
    }

    return creditHandle.modifyMail(UserUtils.getUser(), CreditConstant.MODIFY_MAIL, mail);
}
 
Example 5
Source File: AbstractRestExceptionHandler.java    From kaif with Apache License 2.0 5 votes vote down vote up
@ExceptionHandler(AccessDeniedException.class)
@ResponseBody
public ResponseEntity<E> handleAccessDeniedException(final AccessDeniedException ex,
    final WebRequest request) {
  final HttpStatus status = HttpStatus.UNAUTHORIZED;
  final E errorResponse = createErrorResponse(status,
      i18n(request, "rest-error.RestAccessDeniedException"));
  if (environment.acceptsProfiles(SpringProfile.DEV)) {
    //only dev server log detail access denied
    logException(ex, errorResponse, request);
  } else {
    logger.warn("{} {}", guessUri(request), ex.getClass().getSimpleName());
  }
  return new ResponseEntity<>(errorResponse, status);
}
 
Example 6
Source File: ExceptionControllerAdvice.java    From plumdo-work with Apache License 2.0 5 votes vote down vote up
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ExceptionHandler(AuthErrorException.class)
@ResponseBody
public ErrorInfo handleAuthError(AuthErrorException e) {
    log.error("授权验证异常", e);
    return new ErrorInfo(e.getRet(), e.getMessage());
}
 
Example 7
Source File: BrowserSecurityController.java    From SpringAll with MIT License 5 votes vote down vote up
@GetMapping("/authentication/require")
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public String requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
    SavedRequest savedRequest = requestCache.getRequest(request, response);
    if (savedRequest != null) {
        String targetUrl = savedRequest.getRedirectUrl();
        if (StringUtils.endsWithIgnoreCase(targetUrl, ".html"))
            redirectStrategy.sendRedirect(request, response, "/login.html");
    }
    return "访问的资源需要身份认证!";
}
 
Example 8
Source File: ApiSessionController.java    From youkefu with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/session", method = RequestMethod.POST)
@Menu(type = "apps" , subtype = "session" , access = true)
@ApiOperation("登录服务,传入登录账号和密码")
public ResponseEntity<Object> session(HttpServletRequest request , HttpServletResponse response , @Valid String userid ) {
	ResponseEntity<Object> entity = null ;
    if(!StringUtils.isBlank(userid)){
    	String auth = UKTools.getUUID();
    	CacheHelper.getApiUserCacheBean().put(auth, super.getIMUser(request, userid, null), UKDataContext.SYSTEM_ORGI);
    	entity = new ResponseEntity<Object>(auth, HttpStatus.OK) ;
    	response.addCookie(new Cookie("authorization",auth));
    }else{
    	entity = new ResponseEntity<>(HttpStatus.UNAUTHORIZED) ;
    }
    return entity;
}
 
Example 9
Source File: BrowserSecurityController.java    From SpringAll with MIT License 5 votes vote down vote up
@GetMapping("/authentication/require")
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public String requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
    SavedRequest savedRequest = requestCache.getRequest(request, response);
    if (savedRequest != null) {
        String targetUrl = savedRequest.getRedirectUrl();
        if (StringUtils.endsWithIgnoreCase(targetUrl, ".html"))
            redirectStrategy.sendRedirect(request, response, "/login.html");
    }
    return "访问的资源需要身份认证!";
}
 
Example 10
Source File: FoodManagementApiImpl.java    From springboot-rest-h2-swagger with GNU General Public License v3.0 5 votes vote down vote up
@Override
public ResponseEntity addFood(@RequestHeader(name="Consumer-Key", required=false) String key, @RequestBody Food food) {
	if (this.esAuthService.isAdmin(key)) {
		Boolean result = this.foodManagementService.addFood(food);
		return new ResponseEntity(result, HttpStatus.CREATED);
	}
	else {
		return new ResponseEntity(new Response("Invalid Consmer Key"), HttpStatus.UNAUTHORIZED);
	}
}
 
Example 11
Source File: ExceptionResolver.java    From spring-boot-vue-admin with Apache License 2.0 5 votes vote down vote up
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ExceptionHandler({BadCredentialsException.class, AuthenticationException.class})
public Result authException(final Throwable e) {
  log.error("==> 身份验证异常: {}", e.getMessage());
  e.printStackTrace();
  return ResultGenerator.genFailedResult(ResultCode.UNAUTHORIZED_EXCEPTION);
}
 
Example 12
Source File: JwtOperator.java    From light-security with Apache License 2.0 5 votes vote down vote up
/**
 * 从token中获取claim
 *
 * @param token token
 * @return claim
 */
public Claims getClaimsFromToken(String token) {
    try {
        return Jwts.parser()
                .setSigningKey(this.reactiveLightSecurityProperties.getJwt().getSecret().getBytes())
                .parseClaimsJws(token)
                .getBody();

    } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException e) {
        log.error("token解析错误", e);
        throw new LightSecurityException(HttpStatus.UNAUTHORIZED, "Token invalided.", e);
    }
}
 
Example 13
Source File: VideoSessionController.java    From full-teaching with Apache License 2.0 5 votes vote down vote up
private ResponseEntity<Object> checkAuthorizationUsers(Object o, Collection<User> users){
	if(o == null){
		//The object does not exist
		return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
	}
	if(!users.contains(this.user.getLoggedUser())){
		//The user is not authorized to edit if it is not an attender of the Course
		return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); 
	}
	return null;
}
 
Example 14
Source File: HttpClientErrorException.java    From spring-analysis-note with MIT License 4 votes vote down vote up
Unauthorized(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) {
	super(HttpStatus.UNAUTHORIZED, statusText, headers, body, charset);
}
 
Example 15
Source File: LightSecurityException.java    From light-security with Apache License 2.0 4 votes vote down vote up
public LightSecurityException(String reason) {
    this(HttpStatus.UNAUTHORIZED, reason);
}
 
Example 16
Source File: GateWayExceptionHandlerAdvice.java    From SpringCloud with Apache License 2.0 4 votes vote down vote up
@ExceptionHandler(value = {MalformedJwtException.class})
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public Result handle(MalformedJwtException ex) {
    log.error("MalformedJwtException:{}", ex.getMessage());
    return Result.fail(SystemErrorType.INVALID_TOKEN);
}
 
Example 17
Source File: ApiUtil.java    From springdoc-openapi with Apache License 2.0 4 votes vote down vote up
public static void checkApiKey(NativeWebRequest req) {
	if (!"1".equals(System.getenv("DISABLE_API_KEY")) && !"special-key".equals(req.getHeader("api_key"))) {
		throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Missing API key!");
	}
}
 
Example 18
Source File: GlobalControllerExceptionHandler.java    From onboard with Apache License 2.0 4 votes vote down vote up
@ExceptionHandler(NoLoginException.class)
public ResponseEntity<ErrorInfo> handleNoLoginException(HttpServletRequest request, Exception ex) {
    ErrorInfo e = new ErrorInfo(HttpStatus.UNAUTHORIZED.value(), request.getRequestURI(), ex);
    return new ResponseEntity<ErrorInfo>(e, HttpStatus.UNAUTHORIZED);
}
 
Example 19
Source File: LightSecurityExceptionHandler.java    From light-security with Apache License 2.0 2 votes vote down vote up
/**
 * Light Security相关异常
 *
 * @param exception 异常
 * @return 发生异常时的返回
 */
@ExceptionHandler(value = {LightSecurityException.class})
@ResponseBody
public ResponseEntity<String> error(LightSecurityException exception) {
    return new ResponseEntity<>(exception.getMessage(), HttpStatus.UNAUTHORIZED);
}
 
Example 20
Source File: UnauthorizedException.java    From sinavi-jfw with Apache License 2.0 2 votes vote down vote up
/**
 * コンストラクタです。
 * @param responseHeaders レスポンスヘッダー情報
 * @param responseBody レスポンスボディ情報
 * @param responseCharset レスポンスキャラセット
 */
public UnauthorizedException(HttpHeaders responseHeaders, byte[] responseBody, Charset responseCharset) {
    super(HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED.name(), responseHeaders, responseBody, responseCharset);
}