当前位置: 首页>>代码示例>>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;未经允许,请勿转载。