org.apache.shiro.authz.UnauthenticatedException Java Examples

The following examples show how to use org.apache.shiro.authz.UnauthenticatedException. 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: UserController.java    From spring-boot-study with MIT License 6 votes vote down vote up
@GetMapping("/show")
@ResponseBody
public String show(){

    Subject subject = SecurityUtils.getSubject();
    String str="";
    if(subject.hasRole("admin")){
        str=str+"您拥有 admin 权限";
    }else{
        str=str+"您没有 admin 权限";
    }
    if(subject.hasRole("sale")){
        str=str+"您拥有 sale 权限";
    }
    else{
        str=str+"您没有 sale 权限";
    }
    try{
        subject.checkPermission("app:setting:setting");
        str=str+"您拥有 app:setting:setting 权限";

    }catch (UnauthenticatedException ex){
        str=str+"您没有 app:setting:setting 权限";
    }
    return  str;
}
 
Example #2
Source File: IamSecurityHolder.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
/**
 * Gets current authenticate principal {@link IamPrincipalInfo}
 * 
 * @param assertion
 * @return
 * @see {@link com.wl4g.devops.iam.realm.AbstractIamAuthorizingRealm#doGetAuthenticationInfo(AuthenticationToken)}
 */
public static IamPrincipalInfo getPrincipalInfo(boolean assertion) {
	SimplePrincipalInfo info = (SimplePrincipalInfo) getSession()
			.getAttribute(new RelationAttrKey(KEY_AUTHC_ACCOUNT_INFO, SimplePrincipalInfo.class));
	if (assertion) {
		notNull(info, UnauthenticatedException.class,
				"Authentication subject empty. unauthenticated? or is @EnableIamServer/@EnableIamClient not enabled? Also note the call order!");
	}
	/**
	 * It is not recommended that external methods bind business attributes
	 * here. We recommend that external methods bind business attributes
	 * directly to the session, i.e: {@link #bind(Object, T)}
	 * 
	 * @see {@link com.wl4g.devops.iam.common.subject.SimplePrincipalInfo#setAttributes(Map)}#MARK1
	 */
	return info.setAttributes(unmodifiableMap(info.getAttributes())); // [MARK2]
}
 
Example #3
Source File: IamErrorConfiguring.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
@Override
public Integer getStatus(HttpServletRequest request, HttpServletResponse response, Map<String, Object> model, Exception ex) {
	// IAM Unauthenticated?
	if ((ex instanceof UnauthenticatedException)
			|| (ex instanceof com.wl4g.devops.common.exception.iam.UnauthenticatedException)) {
		return UNAUTHC.getErrcode();
	}
	// IAM Unauthorized?
	else if ((ex instanceof UnauthorizedException)
			|| (ex instanceof com.wl4g.devops.common.exception.iam.UnauthorizedException)) {
		return UNAUTHZ.getErrcode();
	}
	// see: IamSecurityHolder
	else if (ex instanceof UnknownSessionException) {
		return PARAM_ERR.getErrcode();
	}

	// Using next chain configuring.
	return null;
}
 
Example #4
Source File: ExceptionUtils.java    From onedev with MIT License 6 votes vote down vote up
public static void handle(HttpServletResponse response, Exception exception) {
	try {
		if (ExceptionUtils.find(exception, UnauthenticatedException.class) != null) {
			requireAuthentication(response);
		} else if (find(exception, UnauthorizedException.class) != null) {
			if (!SecurityUtils.getSubject().isAuthenticated()) 
				requireAuthentication(response);
			else 
				response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access denied.");
		} else if (find(exception, IncorrectCredentialsException.class) != null) {
			response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Incorrect credentials.");
		} else if (find(exception, UnknownAccountException.class) != null) {
			response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unknown user name.");
		} else {
			logger.warn("Error serving request", exception);
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, exception.getMessage());
		} 
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example #5
Source File: ShiroUtil.java    From Shiro-Action with MIT License 5 votes vote down vote up
/**
 * 获取当前登录用户.
 */
public static User getCurrentUser() {
    User user = (User) SecurityUtils.getSubject().getPrincipal();
    if (user == null) {
        throw new UnauthenticatedException("未登录被拦截");
    }
    return user;
}
 
Example #6
Source File: ShiroAuthenticatingThriftInterceptorTest.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Test(expected = UnauthenticatedException.class)
public void testInvokeNotAuthenticated() throws Throwable {
  expect(subject.isAuthenticated()).andReturn(false);

  replayAndInitialize();

  interceptor.invoke(methodInvocation);
}
 
Example #7
Source File: ShiroKerberosPermissiveAuthenticationFilterTest.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Test
public void testInterceptsUnauthenticatedException() throws ServletException, IOException {
  mockServlet.service(anyObject(HttpServletRequest.class), anyObject(HttpServletResponse.class));
  expectLastCall().andThrow(new UnauthenticatedException());

  replayAndStart();

  ClientResponse clientResponse = getRequestBuilder(PATH).get(ClientResponse.class);

  assertEquals(HttpServletResponse.SC_UNAUTHORIZED, clientResponse.getStatus());
  assertEquals(
      ShiroKerberosAuthenticationFilter.NEGOTIATE,
      clientResponse.getHeaders().getFirst(HttpHeaders.WWW_AUTHENTICATE));
}
 
Example #8
Source File: ShiroKerberosPermissiveAuthenticationFilter.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Override
protected void handleUnauthenticated(
    HttpServletRequest request,
    HttpServletResponse response,
    FilterChain chain) throws IOException, ServletException {

  // Incoming request is unauthenticated, but some RPCs might be okay with that.
  try {
    chain.doFilter(request, response);
  } catch (UnauthenticatedException e) {
    super.handleUnauthenticated(request, response, chain);
  }
}
 
Example #9
Source File: ShiroAuthenticatingThriftInterceptor.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
  checkState(initialized);
  Subject subject = subjectProvider.get();
  if (subject.isAuthenticated()) {
    return invocation.proceed();
  } else {
    // This is a special exception that will signal the BasicHttpAuthenticationFilter to send
    // a 401 with a challenge. This is necessary at this layer since we only apply this
    // interceptor to methods that require authentication.
    throw new UnauthenticatedException();
  }
}
 
Example #10
Source File: SecurityConcern.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
private void handleRequiresAuthentication( Subject subject )
{
    if ( requiresAuthentication != null ) {
        LOGGER.debug( "SecurityConcern::RequiresAuthentication" );
        if ( !subject.isAuthenticated() ) {
            throw new UnauthenticatedException( "The current Subject is not authenticated.  Access denied." );
        }
    } else {
        LOGGER.debug( "SecurityConcern::RequiresAuthentication: not concerned" );
    }
}
 
Example #11
Source File: SecurityConcern.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
private void handleRequiresUser( Subject subject )
{
    if ( requiresUser != null ) {
        LOGGER.debug( "SecurityConcern::RequiresUser" );
        if ( subject.getPrincipal() == null ) {
            throw new UnauthenticatedException(
                    "Attempting to perform a user-only operation. The current Subject is "
                    + "not a user (they haven't been authenticated or remembered from a previous login).  "
                    + "Access denied." );
        }
    } else {
        LOGGER.debug( "SecurityConcern::RequiresUser: not concerned" );
    }
}
 
Example #12
Source File: SecurityConcern.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
private void handleRequiresGuest( Subject subject )
{
    if ( requiresGuest != null ) {
        LOGGER.debug( "SecurityConcern::RequiresGuest" );
        if ( subject.getPrincipal() != null ) {
            throw new UnauthenticatedException(
                    "Attempting to perform a guest-only operation. The current Subject is "
                    + "not a guest (they have been authenticated or remembered from a previous login).  Access "
                    + "denied." );

        }
    } else {
        LOGGER.debug( "SecurityConcern::RequiresGuest: not concerned" );
    }
}
 
Example #13
Source File: ErrorResponse.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
public ErrorResponse(final Throwable cause) {
  this(checkNotNull(cause).getMessage() == null ? cause.getClass().getName() : cause.getMessage());
  authenticationRequired = cause instanceof UnauthenticatedException;
  if (authenticationRequired) {
    Subject subject = SecurityUtils.getSubject();
    if (subject == null || !(subject.isRemembered() || subject.isAuthenticated())) {
      message = "Access denied (authentication required)";
    }
  }
}
 
Example #14
Source File: AdminMyControllerAdvice.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
@ResponseBody
@ExceptionHandler({AuthenticationException.class,UnauthenticatedException.class})
public MessageResult handleAuthenticationError(AuthorizationException ex) {
    ex.printStackTrace();
    MessageResult result = MessageResult.error(4000, "please login");
    return result;
}
 
Example #15
Source File: GlobalExceptionHandler.java    From spring-boot-plus with Apache License 2.0 5 votes vote down vote up
/**
 * 未认证异常处理
 *
 * @param exception
 * @return
 */
@ExceptionHandler(value = UnauthenticatedException.class)
@ResponseStatus(HttpStatus.OK)
public ApiResult<Boolean> unauthenticatedExceptionHandler(UnauthenticatedException exception) {
    printRequestDetail();
    printApiCodeException(ApiCode.UNAUTHENTICATED_EXCEPTION, exception);
    return ApiResult.fail(ApiCode.UNAUTHENTICATED_EXCEPTION);
}
 
Example #16
Source File: WebExceptionHandler.java    From ueboot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@ExceptionHandler(UnauthenticatedException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ResponseBody
public Response<Void> handleException(UnauthenticatedException e) {
    log.debug("{} was thrown", e.getClass(), e);
    return new Response<>(HttpStatus.UNAUTHORIZED.value() + "", "当前用户未登录", null);
}
 
Example #17
Source File: ShiroExceptionHandler.java    From ueboot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@ExceptionHandler(UnauthenticatedException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ResponseBody
public Response<Void> handleException(UnauthenticatedException e) {
    log.debug("{} was thrown", e.getClass(), e);
    ShiroExceptionHandler.remove();
    shiroEventListener.afterLogin(currentUserName.get(),false,e.getMessage());
    return new Response<>(HttpStatus.UNAUTHORIZED.value() + "", "当前用户未登录", null);
}
 
Example #18
Source File: RegisterPage.java    From onedev with MIT License 5 votes vote down vote up
public RegisterPage(PageParameters params) {
	super(params);
	
	if (!OneDev.getInstance(SettingManager.class).getSecuritySetting().isEnableSelfRegister())
		throw new UnauthenticatedException("User self-register is disabled");
	if (getLoginUser() != null)
		throw new IllegalStateException("Can not sign up a user while signed in");
}
 
Example #19
Source File: UnauthenticatedExceptionMapper.java    From onedev with MIT License 5 votes vote down vote up
@Override
  public Response toResponse(UnauthenticatedException exception) {
ResponseBuilder builder = Response.status(Response.Status.UNAUTHORIZED);
builder.header("WWW-Authenticate", HttpServletRequest.BASIC_AUTH + " realm=\"" + appName + "\"");
  	if (exception.getMessage() != null)
  		builder = builder.entity(exception.getMessage()).type("text/plain");
  	
  	return builder.build();
  }
 
Example #20
Source File: AdminMyControllerAdvice.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
@ResponseBody
@ExceptionHandler({AuthenticationException.class,UnauthenticatedException.class})
public MessageResult handleAuthenticationError(AuthorizationException ex) {
    ex.printStackTrace();
    MessageResult result = MessageResult.error(4000, "please login");
    return result;
}
 
Example #21
Source File: IamErrorConfiguring.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Override
public String getRootCause(HttpServletRequest request, HttpServletResponse response, Map<String, Object> model,
		Exception ex) {
	// IAM Unauthenticated or Unauthorized?
	if ((ex instanceof UnauthenticatedException) || (ex instanceof UnauthorizedException)
			|| (ex instanceof com.wl4g.devops.common.exception.iam.UnauthenticatedException)
			|| (ex instanceof com.wl4g.devops.common.exception.iam.UnauthorizedException)) {
		// return getRootCausesString(ex);
		return getMessage(ex);
	}

	// Using next chain configuring.
	return null;
}
 
Example #22
Source File: BaseController.java    From hunt-admin with Apache License 2.0 4 votes vote down vote up
@ExceptionHandler(Exception.class)
public void exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception exception) throws IOException, ServletException {
    log.error("exception occur : \n {}", StringUtil.exceptionDetail(exception));
    if (request.getHeader("Accept").contains("application/json")) {
        log.debug("qingqiu");
        Result result = Result.error();
        if (exception instanceof IncorrectCredentialsException) {
            result = Result.instance(ResponseCode.password_incorrect.getCode(), ResponseCode.password_incorrect.getMsg());
            //账号不存在
        } else if (exception instanceof UnknownAccountException) {
            result = Result.instance(ResponseCode.unknown_account.getCode(), ResponseCode.unknown_account.getMsg());
            //未授权
        } else if (exception instanceof UnauthorizedException) {
            result = Result.instance(ResponseCode.unauthorized.getCode(), ResponseCode.unauthorized.getMsg());
            //未登录
        } else if (exception instanceof UnauthenticatedException) {
            result = Result.instance(ResponseCode.unauthenticated.getCode(), ResponseCode.unauthenticated.getMsg());
            //缺少参数
        } else if (exception instanceof MissingServletRequestParameterException) {
            result = Result.instance(ResponseCode.missing_parameter.getCode(), ResponseCode.missing_parameter.getMsg());
            //参数格式错误
        } else if ((exception instanceof MethodArgumentTypeMismatchException)) {
            result = Result.instance(ResponseCode.param_format_error.getCode(), ResponseCode.param_format_error.getMsg());
            //ip限制
        } else if (exception.getCause().getMessage().contains("system.exception.ForbiddenIpException")) {
            result = Result.instance(ResponseCode.forbidden_ip.getCode(), ResponseCode.forbidden_ip.getMsg());
            //其他错误
        }
        //调试时输出异常日志
        if (systemService.selectDataItemByKey("error_detail", 2L).equals("true")) {
            result.setData(StringUtil.exceptionDetail(exception));
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().append(new Gson().toJson(result));
        response.getWriter().flush();
        response.getWriter().close();
    } else {
        String basePath = systemService.selectDataItemByKey("basePath", 4L);
        String url = "/error/internalError";

        if (exception instanceof UnauthorizedException) {
            url = "/error/unAuthorization";
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        response.sendRedirect(basePath + url);
    }
}
 
Example #23
Source File: GlobalExceptionHandler.java    From SpringBoot-Shiro-Vue with MIT License 4 votes vote down vote up
/**
 * 未登录报错拦截
 * 在请求需要权限的接口,而连登录都还没登录的时候,会报此错
 */
@ExceptionHandler(UnauthenticatedException.class)
public JSONObject unauthenticatedException() {
	return CommonUtil.errorJson(ErrorEnum.E_20011);
}
 
Example #24
Source File: GlobalExceptionResolver.java    From mySpringBoot with Apache License 2.0 4 votes vote down vote up
@ExceptionHandler(UnauthenticatedException.class)
public void page401(HttpServletResponse response, UnauthenticatedException e) {
    RetResult<Object> result = new RetResult<>();
        result.setCode(RetCode.UNAUTHEN).setMsg("用户未登录").setData(null);
    responseResult(response, result);
}
 
Example #25
Source File: ApplicationExceptionHandler.java    From spring-boot-shiro-orientdb with Apache License 2.0 4 votes vote down vote up
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ExceptionHandler(
        {AuthenticationException.class, UnknownAccountException.class,
                UnauthenticatedException.class, IncorrectCredentialsException.class, UnauthorizedException.class})
public void unauthorized() {
}
 
Example #26
Source File: SubjectAuthResource.java    From shiro-jersey with Apache License 2.0 4 votes vote down vote up
@GET
public String get(@Auth Subject subject) {
    if (!subject.isAuthenticated()) throw new UnauthenticatedException();

    return Double.toString(Math.random());
}
 
Example #27
Source File: SubjectAuthResource.java    From shiro-jersey with Apache License 2.0 4 votes vote down vote up
@GET
public String get(@Auth Subject subject) {
    if (!subject.isAuthenticated()) throw new UnauthenticatedException();

    return Double.toString(Math.random());
}
 
Example #28
Source File: ShiroUtilsController.java    From mySpringBoot with Apache License 2.0 4 votes vote down vote up
@GetMapping("/noLogin")
public void noLogin() {
    throw new UnauthenticatedException();
}
 
Example #29
Source File: WebExceptionHandler.java    From Shiro-Action with MIT License 4 votes vote down vote up
@ExceptionHandler
public String unauthenticatedException(UnauthenticatedException e) {
    return "redirect:" + shiroFilterFactoryBean.getLoginUrl();
}
 
Example #30
Source File: GlobalExceptionHandler.java    From SpringBoot-Shiro-Vue-master-20180625 with Apache License 2.0 2 votes vote down vote up
/**
 * 未登录报错拦截
 * 在请求需要权限的接口,而连登录都还没登录的时候,会报此错
 *
 * @return
 * @throws Exception
 */
@ExceptionHandler(UnauthenticatedException.class)
public JSONObject unauthenticatedException() throws Exception {
    return CommonUtil.errorJson(ErrorEnum.E_20011);
}