當前位置: 首頁>>代碼示例>>Java>>正文


Java Subject類代碼示例

本文整理匯總了Java中org.apache.shiro.subject.Subject的典型用法代碼示例。如果您正苦於以下問題:Java Subject類的具體用法?Java Subject怎麽用?Java Subject使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Subject類屬於org.apache.shiro.subject包,在下文中一共展示了Subject類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: getSession

import org.apache.shiro.subject.Subject; //導入依賴的package包/類
public static Session getSession(){
		try{
			Subject subject = SecurityUtils.getSubject();
			Session session = subject.getSession(false);
			if (session == null){
				session = subject.getSession();
			}
			if (session != null){
				return session;
			}
//			subject.logout();
		}catch (InvalidSessionException e){

		}
		return null;
	}
 
開發者ID:egojit8,項目名稱:easyweb,代碼行數:17,代碼來源:UserUtils.java

示例2: authorize

import org.apache.shiro.subject.Subject; //導入依賴的package包/類
public void authorize(ResourcePermission context) {
  Subject currentUser = getSubject();
  if (currentUser == null) {
    return;
  }

  if (context == null) {
    return;
  }

  if (context.getResource() == Resource.NULL && context.getOperation() == Operation.NULL) {
    return;
  }

  try {
    currentUser.checkPermission(context);
  } catch (ShiroException e) {
    String msg = currentUser.getPrincipal() + " not authorized for " + context;
    logger.info(msg);
    throw new NotAuthorizedException(msg, e);
  }
}
 
開發者ID:ampool,項目名稱:monarch,代碼行數:23,代碼來源:IntegratedSecurityService.java

示例3: login

import org.apache.shiro.subject.Subject; //導入依賴的package包/類
@ModelAttribute("login")
private MsgTO login(@RequestBody MsgTO msgTo) {
	Long userId = msgTo.getUserId();
	String password = msgTo.getPassword();
	SysUserEntity user = ((SysUserService) SpringContextUtils.getBean("sysUserService")).queryObject(userId);
	if(user==null){
		throw new RRException("用戶id不存在");
	}
	try {
		Subject subject = ShiroUtils.getSubject();
		// sha256加密
		password = new Sha256Hash(password).toHex();
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), password);
		subject.login(token);
	} catch (Exception e) {
		throw new RRException("登錄失敗");
	}
	msgTo.setUser(user);
	return msgTo;
}
 
開發者ID:gyp220203,項目名稱:renren-msg,代碼行數:21,代碼來源:MsgSendController.java

示例4: testIniAuthorization

import org.apache.shiro.subject.Subject; //導入依賴的package包/類
/**
 * testIniAuthorization
 * @Description: 使用inirealm完成授權
 * @return: void
 * @Author: BeautifulSoup
 * @Date: 2017年12月16日 下午3:05:34
 */
@Test
@Ignore
public void testIniAuthorization(){
	Factory<SecurityManager> factory=new IniSecurityManagerFactory("classpath:permission-shiro.ini");
	SecurityManager securityManager = factory.getInstance();
	SecurityUtils.setSecurityManager(securityManager);
	Subject subject = SecurityUtils.getSubject();
	//首先認證,認證通過之後才能授權
	UsernamePasswordToken token=new UsernamePasswordToken("beautifulsoup", "password");
	try{
		subject.login(token);
	}catch(AuthenticationException e){
		e.printStackTrace();
	}
	System.out.println("用戶的認證狀態:"+subject.isAuthenticated());
	boolean isPermitted=subject.isPermittedAll("user:create:01","user:query");
	subject.checkPermissions("user:create:01","user:query");
	System.out.println(isPermitted);
}
 
開發者ID:fuyunwang,項目名稱:ShiroDemo,代碼行數:27,代碼來源:AuthorizationTest.java

示例5: onLoginSuccess

import org.apache.shiro.subject.Subject; //導入依賴的package包/類
/**
 * 覆蓋默認實現,用sendRedirect直接跳出框架,以免造成js框架重複加載js出錯。
 * 
 * @param token
 * @param subject
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@Override
protected boolean onLoginSuccess(AuthenticationToken token,
		Subject subject, ServletRequest request, ServletResponse response)
		throws Exception {
	HttpServletRequest httpRequest = (HttpServletRequest) request;
	HttpServletResponse httpResponse = (HttpServletResponse) response;

	if (!"XMLHttpRequest".equalsIgnoreCase(httpRequest
			.getHeader("X-Requested-With"))) {
		httpResponse.sendRedirect(httpRequest.getContextPath()
				+ this.getSuccessUrl());
	} else {
		httpRequest.getRequestDispatcher("/CN").forward(httpRequest,
				httpResponse);
	}
	return false;
}
 
開發者ID:jiangzongyao,項目名稱:kettle_support_kettle8.0,代碼行數:28,代碼來源:FormAuthentication2Filter.java

示例6: checkSubjectRolesAndPermissions

import org.apache.shiro.subject.Subject; //導入依賴的package包/類
/**
 * Check subject roles and permissions.
 *
 * @param currentUser the current user
 * @throws FailedLoginException the failed login exception in case roles or permissions are absent
 */
protected void checkSubjectRolesAndPermissions(final Subject currentUser) throws FailedLoginException {
    if (this.requiredRoles != null) {
        for (final String role : this.requiredRoles) {
            if (!currentUser.hasRole(role)) {
                throw new FailedLoginException("Required role " + role + " does not exist");
            }
        }
    }

    if (this.requiredPermissions != null) {
        for (final String perm : this.requiredPermissions) {
            if (!currentUser.isPermitted(perm)) {
                throw new FailedLoginException("Required permission " + perm + " does not exist");
            }
        }
    }
}
 
開發者ID:hsj-xiaokang,項目名稱:springboot-shiro-cas-mybatis,代碼行數:24,代碼來源:ShiroAuthenticationHandler.java

示例7: showTagBody

import org.apache.shiro.subject.Subject; //導入依賴的package包/類
@Override
protected boolean showTagBody(String permissionNames) {
	boolean hasAnyPermission = false;

	Subject subject = getSubject();

	if (subject != null) {
		// Iterate through permissions and check to see if the user has one of the permissions
		for (String permission : permissionNames.split(PERMISSION_NAMES_DELIMETER)) {

			if (subject.isPermitted(permission.trim())) {
				hasAnyPermission = true;
				break;
			}

		}
	}

	return hasAnyPermission;
}
 
開發者ID:funtl,項目名稱:framework,代碼行數:21,代碼來源:HasAnyPermissionsTag.java

示例8: login

import org.apache.shiro.subject.Subject; //導入依賴的package包/類
@RequestMapping(value="/login",method=RequestMethod.POST)
public ModelAndView login(User user, String captcha, HttpSession session,HttpServletRequest request) throws Exception{
	ModelAndView mv = new ModelAndView();
	
	String kaptchaExpected = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
	System.out.println(kaptchaExpected);
	Subject subject = SecurityUtils.getSubject();
	UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
	try{
		subject.login(token);
		mv.setViewName("redirect:/index.jsp");
	} catch (AuthenticationException e){
		mv.addObject("message", "login errors");
		mv.setViewName("redirect:/backend/login");
	} 
	return mv;
}
 
開發者ID:ranji1221,項目名稱:clemon,代碼行數:18,代碼來源:LoginController.java

示例9: getGroups

import org.apache.shiro.subject.Subject; //導入依賴的package包/類
@ApiOperation("獲取小組列表")
@GetMapping
public ResponseEntity getGroups(@RequestParam("page") int page,
                                @RequestParam("page_size") int pageSize,
                                @RequestParam(name = "owner", required = false, defaultValue = "0") int owner) {
    if (owner > 0) {
        // 鑒權
        Subject subject = SecurityUtils.getSubject();
        if (! subject.isAuthenticated()) {
            throw new UnauthorizedException();
        }
        int uid = SessionHelper.get().getUid();
        if (uid != owner) {
            throw new UnauthorizedException();
        }

        PageRowBounds pager = new PageRowBounds(page, pageSize);
        List<GroupEntity> groups = groupService.getGroups(uid, pager);
        Map<String, Object> data = new HashMap<>(2);
        data.put("data", groups);
        data.put("total", pager.getTotal());
        return new ResponseEntity(data);
    } else {
        return new ResponseEntity(new ArrayList<>());
    }
}
 
開發者ID:Eagle-OJ,項目名稱:eagle-oj-api,代碼行數:27,代碼來源:GroupsController.java

示例10: deleteTag

import org.apache.shiro.subject.Subject; //導入依賴的package包/類
public void deleteTag(String tag) {
  	String refName = GitUtils.tag2ref(tag);
  	ObjectId commitId = getRevCommit(refName).getId();
  	try {
	git().tagDelete().setTags(tag).call();
} catch (GitAPIException e) {
	throw new RuntimeException(e);
}
  	Subject subject = SecurityUtils.getSubject();
  	GitPlex.getInstance(UnitOfWork.class).doAsync(new Runnable() {

	@Override
	public void run() {
		ThreadContext.bind(subject);
		try {
			Project project = GitPlex.getInstance(ProjectManager.class).load(getId());
			GitPlex.getInstance(ListenerRegistry.class).post(
					new RefUpdated(project, refName, commitId, ObjectId.zeroId()));
		} finally {
			ThreadContext.unbindSubject();
		}
	}
  		
  	});
  }
 
開發者ID:jmfgdev,項目名稱:gitplex-mit,代碼行數:26,代碼來源:Project.java

示例11: logout

import org.apache.shiro.subject.Subject; //導入依賴的package包/類
public void logout() {
  Subject currentUser = getSubject();
  if (currentUser == null) {
    return;
  }

  try {
    logger.info("Logging out " + currentUser.getPrincipal());
    currentUser.logout();
  } catch (ShiroException e) {
    logger.info(e.getMessage(), e);
    throw new GemFireSecurityException(e.getMessage(), e);
  }
  // clean out Shiro's thread local content
  ThreadContext.remove();
}
 
開發者ID:ampool,項目名稱:monarch,代碼行數:17,代碼來源:IntegratedSecurityService.java

示例12: responseApprovalDeny

import org.apache.shiro.subject.Subject; //導入依賴的package包/類
protected void responseApprovalDeny() throws IOException, OAuthSystemException {

        final OAuthResponse oAuthResponse = OAuthASResponse.errorResponse(HttpServletResponse.SC_FOUND)
                .setError(OAuthError.CodeResponse.ACCESS_DENIED)
                .setErrorDescription("User denied access")
                .location(clientDetails().getRedirectUri())
                .setState(oauthRequest.getState())
                .buildQueryMessage();
        LOG.debug("'ACCESS_DENIED' response: {}", oAuthResponse);

        WebUtils.writeOAuthQueryResponse(response, oAuthResponse);

        //user logout when deny
        final Subject subject = SecurityUtils.getSubject();
        subject.logout();
        LOG.debug("After 'ACCESS_DENIED' call logout. user: {}", subject.getPrincipal());
    }
 
開發者ID:monkeyk,項目名稱:oauth2-shiro,代碼行數:18,代碼來源:AbstractAuthorizeHandler.java

示例13: onPreHandle

import org.apache.shiro.subject.Subject; //導入依賴的package包/類
@Override
protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
   	Subject subject = SecurityUtils.getSubject();
	if (!subject.isAuthenticated()) {
        HttpServletRequest httpRequest = WebUtils.toHttp(request);
        String authzHeader = httpRequest.getHeader(AUTHORIZATION_HEADER);
        if (authzHeader != null) {
            if (authzHeader.toLowerCase(Locale.ENGLISH).startsWith("basic") 
            		|| authzHeader.toLowerCase(Locale.ENGLISH).startsWith("token")) {
            	String authToken = StringUtils.substringAfter(authzHeader, " ");
                String decoded = Base64.decodeToString(authToken);
                String userName = StringUtils.substringBefore(decoded, ":").trim();
                String password = StringUtils.substringAfter(decoded, ":").trim();
                if (userName.length() != 0 && password.length() != 0) {
	                UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
                    subject.login(token);
                }
            }
        } 
	} 
	
	return true;
}
 
開發者ID:jmfgdev,項目名稱:gitplex-mit,代碼行數:24,代碼來源:BasicAuthenticationFilter.java

示例14: onAccessDenied

import org.apache.shiro.subject.Subject; //導入依賴的package包/類
@Override
protected boolean onAccessDenied(ServletRequest request,
		ServletResponse response) throws Exception {
	
		Subject subject = getSubject(request, response);  
        if (null == subject.getPrincipal()) {//表示沒有登錄,重定向到登錄頁麵  
            saveRequest(request);
            WebUtils.issueRedirect(request, response, ShiroUtils.LOGIN_URL);  
        } else {
    		if(ShiroUtils.isAjax(request)){
    			Map<String, Object> result = new HashMap<String, Object>();
    			result.put("status", "401");
    			result.put("message", "sorry,您沒有權限");
    			result.put("url", ShiroUtils.UNAUTHORIZED);
    			ShiroUtils.writeJson(response, result);
    		}else
    		{
    			if (StringUtils.hasText(ShiroUtils.UNAUTHORIZED)) {//如果有未授權頁麵跳轉過去  
	                WebUtils.issueRedirect(request, response, ShiroUtils.UNAUTHORIZED);  
	            } else {//否則返回401未授權狀態碼  
	                WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);  
	            } 
    		}
        }  
	return Boolean.FALSE;
}
 
開發者ID:wjggwm,項目名稱:webside,代碼行數:27,代碼來源:PermissionFilter.java

示例15: signin

import org.apache.shiro.subject.Subject; //導入依賴的package包/類
@RequestMapping(value = "/signin", method = {
        RequestMethod.POST})
public String signin(ModelMap map, User user, HttpServletRequest request) {

    String error;
    UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPasswd());
    token.setRememberMe(null != request.getParameter("rememberme") ? true : false);
    try {
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
        subject.getSession().setAttribute("curUser", userService.findByUsername((String) subject.getPrincipal()));
        return "redirect:/dashboard/console";
    } catch (UnknownAccountException uae) {
        error = "用戶名錯誤!";
    } catch (IncorrectCredentialsException ice) {
        error = "密碼錯誤!";
    } catch (LockedAccountException lae) {
        error = "用戶被鎖定!";
    }
    map.addAttribute("error", error);
    return "signin";
}
 
開發者ID:melonlee,項目名稱:PowerApi,代碼行數:23,代碼來源:AuthController.java


注:本文中的org.apache.shiro.subject.Subject類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。