本文整理汇总了Java中org.apache.shiro.SecurityUtils类的典型用法代码示例。如果您正苦于以下问题:Java SecurityUtils类的具体用法?Java SecurityUtils怎么用?Java SecurityUtils使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
SecurityUtils类属于org.apache.shiro包,在下文中一共展示了SecurityUtils类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getRealm
import org.apache.shiro.SecurityUtils; //导入依赖的package包/类
@SuppressWarnings("unchecked")
public static <T> T getRealm(Class<? extends Realm> realmType){
RealmSecurityManager securityManager = (RealmSecurityManager) SecurityUtils.getSecurityManager();
if(!CollectionUtils.isEmpty(securityManager.getRealms())){
for(Iterator<Realm> it = securityManager.getRealms().iterator(); it.hasNext();){
Realm realm = it.next();
if(realm.getClass().equals(realmType)){
return (T) realm;
}
}
}
return null;
}
示例2: afterReturn
import org.apache.shiro.SecurityUtils; //导入依赖的package包/类
/**
* @param joinPoint
*/
@AfterReturning("logAnnoAspect()")
public void afterReturn(JoinPoint joinPoint) {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Method method = methodSignature.getMethod();
LogModify logModifyAnno = method.getAnnotation(LogModify.class);
if (null != logModifyAnno) {
BaseEntity entity = (BaseEntity) joinPoint.getArgs()[0];
Log log = new Log();
log.setUserId(((User) SecurityUtils.getSubject().getSession().getAttribute("curUser")).getId());
log.setAction(ACTION + logModifyAnno.resource());
log.setResource(entity.getLogResource());
log.setResourceId(entity.getId());
logService.insert(log);
}
}
示例3: articleVote
import org.apache.shiro.SecurityUtils; //导入依赖的package包/类
/**
* 用户对文章进行点赞
*
* @param articleId 文章id
* @return
*/
@ResponseBody
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity articleVote(int articleId) {
MMSnsArticleEntity articleInfo = articleService.getArticleSimpleInfo(String.valueOf(articleId));
if (articleInfo == null) {
return new ResponseEntity(404, "parameter error", "文章不存在");
}
MMSnsCommonUserEntity sessionCommonUser = (MMSnsCommonUserEntity) SecurityUtils.getSubject().getSession().getAttribute(MMSnsCommonUserEntity.MMSNS_COMMON_USER);
Integer sessionCommonUserUserId = sessionCommonUser.getUserId();
if (articleInfo.getUserId() == sessionCommonUserUserId.intValue()) {
return new ResponseEntity(404, "parameter error", "不能点赞自己的文章");
}
List<MMSnsArticleVoteEntity> articleVotes = articleVoteService.getArticleVoteByCondition(articleId, sessionCommonUserUserId);
if (articleVotes != null && articleVotes.size() > 0) {
return new ResponseEntity(200, "success", "已点赞");
}
MMSnsArticleVoteEntity articleVoteEntity = new MMSnsArticleVoteEntity();
articleVoteEntity.setArticleId(articleId);
articleVoteEntity.setVoteUserId(sessionCommonUserUserId);
articleVoteEntity.setVoteStatus(PublicEnum.NORMAL.value());
articleVoteEntity.setVoteDate(new Date());
articleVoteEntity.setArticleUserId(articleInfo.getUserId());
articleVoteEntity = articleVoteService.voteArticle(articleVoteEntity);
return new ResponseEntity(200, "success", "点赞成功");
}
示例4: saveSession
import org.apache.shiro.SecurityUtils; //导入依赖的package包/类
/** 保存session */
private void saveSession(String account) {
// 踢出用户
SysSession record = new SysSession();
record.setAccount(account);
List<?> sessionIds = sysSessionService.querySessionIdByAccount(record);
if (sessionIds != null) {
for (Object sessionId : sessionIds) {
record.setSessionId((String) sessionId);
sysSessionService.deleteBySessionId(record);
sessionRepository.delete((String) sessionId);
sessionRepository.cleanupExpiredSessions();
}
}
Subject currentUser = SecurityUtils.getSubject();
Session session = currentUser.getSession();
record.setSessionId(session.getId().toString());
String host = (String) session.getAttribute("HOST");
record.setIp(StringUtils.isBlank(host) ? session.getHost() : host);
record.setStartTime(session.getStartTimestamp());
sysSessionService.update(record);
}
示例5: updateMember
import org.apache.shiro.SecurityUtils; //导入依赖的package包/类
/**
* 更新组成员信息
* @param userGroupId 用户组和用户关系主键id
* @param privilage 权限
* @param remark 描述
* @param request
* @return
*/
@ResponseBody
@RequiresPermissions("system:group:memberEdit")
@MumuLog(name = "用户群组更新成员信息",operater = "PUT")
@RequestMapping(value = {"/memberEdit"}, method = RequestMethod.PUT)
public ResponseEntity updateMember(int userGroupId, String privilage, String remark, HttpServletRequest request) {
try {
SysUserGroup userGroup = new SysUserGroup();
userGroup.setUserGroupId(userGroupId);
userGroup.setEditor(SecurityUtils.getSubject().getPrincipal().toString());
userGroup.setPrivilage(privilage);
userGroup.setRemark(remark);
userGroupService.updateSysUserGroupById(userGroup);
return new ResponseEntity(200, "成功更新组成员信息", null);
} catch (Exception e) {
log.error(e);
return new ResponseEntity(500, "编辑组成员信息出现异常", null);
}
}
示例6: userGet
import org.apache.shiro.SecurityUtils; //导入依赖的package包/类
@RequestMapping("/userGet")
@ResponseBody
public String userGet(HttpServletRequest req,HttpServletResponse respon)throws Exception{
Subject currentUser = SecurityUtils.getSubject();
LOGGER.info("userinfo------->{}",JSON.toJSONString(currentUser.getPrincipal()));
/* String userNameString = req.getRemoteUser();
System.out.println("username---->"+userNameString);
AttributePrincipal principal = (AttributePrincipal) req.getUserPrincipal();
if (null != principal) {
Map<String, Object> attMap = principal.getAttributes();
for (Entry<String, Object> entry : attMap.entrySet()) {
System.out.println("===> | " + entry.getKey() + "=:" + entry.getValue() + "<br>");
}
String username = null;
if (null != principal) {
username = principal.getName();
System.out.println("<span style='color:red;'>" + username + "</span><br>");
}
} */
return (String) currentUser.getPrincipal();
}
示例7: loadShiroConfiguration
import org.apache.shiro.SecurityUtils; //导入依赖的package包/类
/**
* Sets shiro configuration to the path of the resource
* that points to the {@code shiro.ini} file.
*
* @param resource the resource
*/
public void loadShiroConfiguration(final Resource resource) {
try {
final Resource shiroResource = ResourceUtils.prepareClasspathResourceIfNeeded(resource);
if (shiroResource != null && shiroResource.exists()) {
final String location = shiroResource.getURI().toString();
LOGGER.debug("Loading Shiro configuration from [{}]", location);
final Factory<SecurityManager> factory = new IniSecurityManagerFactory(location);
final SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
} else {
LOGGER.debug("Shiro configuration is not defined");
}
} catch (final Exception e) {
throw Throwables.propagate(e);
}
}
示例8: index
import org.apache.shiro.SecurityUtils; //导入依赖的package包/类
/**
*
* @return
*/
@RequestMapping(value = "index.html", method = RequestMethod.GET)
public String index(Model model) {
try
{
// 获取登录的bean
UserEntity userEntity = (UserEntity)SecurityUtils.getSubject().getPrincipal();
List<ResourceEntity> list = resourceService.findResourcesMenuByUserId(userEntity.getId().intValue());
List<ResourceEntity> treeList = TreeUtil.getChildResourceEntitys(list, null);
model.addAttribute("list", treeList);
model.addAttribute("menu", JSON.toJSONString(treeList));
// 登陆的信息回传页面
model.addAttribute("userEntity", userEntity);
return "/index";
}catch(Exception e)
{
throw new SystemException(e);
}
}
示例9: testIniRealm
import org.apache.shiro.SecurityUtils; //导入依赖的package包/类
/**
* testIniRealm
* @Description: iniRealm的测试
* @return: void
* @Author: BeautifulSoup
* @Date: 2017年12月16日 上午11:41:43
*/
@Test
@Ignore
public void testIniRealm(){
Factory<SecurityManager> factory=new IniSecurityManagerFactory("classpath:inirealm-shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token=new UsernamePasswordToken("james_shu", "1997admin");
try{
subject.login(token);
}catch(AuthenticationException e){
e.printStackTrace();
}
System.out.println("用户认证状态:"+subject.isAuthenticated());
subject.logout();
System.out.println("用户当前认证状态:"+subject.isAuthenticated());
}
示例10: hasAnyPermissions
import org.apache.shiro.SecurityUtils; //导入依赖的package包/类
/**
* 验证用户是否具有以下任意一个权限。
* @param permissions 以 delimeter 为分隔符的权限列表
* @param delimeter 权限列表分隔符
* @return 用户是否具有以下任意一个权限
*/
public boolean hasAnyPermissions(String permissions, String delimeter) {
Subject subject = SecurityUtils.getSubject();
if (subject != null) {
if (delimeter == null || delimeter.length() == 0) {
delimeter = PERMISSION_NAMES_DELIMETER;
}
for (String permission : permissions.split(delimeter)) {
if (permission != null && subject.isPermitted(permission.trim()) == true) {
return true;
}
}
}
return false;
}
示例11: doGet
import org.apache.shiro.SecurityUtils; //导入依赖的package包/类
/**
* lists the users in the system and their roles and renders the output as html file
* @param job
* <code>MCRServletJob</code>
* @exception IOException exception while rendering output
* @exception TransformerException exception while rendering output
* @exception SAXException exception while rendering output
*/
protected void doGet(MCRServletJob job) throws IOException, TransformerException, SAXException {
org.apache.shiro.subject.Subject currentUser = SecurityUtils.getSubject();
Element output;
if (currentUser.hasRole("userAdmin")) {
output = prepareOutput(job,"userAdmin","admin","userManagement");
List<String> users = UserDAO.listUsers();
for (String user : users) {
Element userElement = new Element("user");
userElement.addContent(new Element("username").addContent(user));
List<UserRole> userRoles = UserRoleDAO.getUserRolesByEmail(user);
LOGGER.info("found " + userRoles.size() + " roles.");
for (UserRole userRole : userRoles) {
Element roleElement = new Element("role");
roleElement.addContent(userRole.getRoleName());
userElement.addContent(roleElement);
}
output.addContent(userElement);
}
} else
output = new Element("error").addContent(new Element("message").addContent("error.noPermission"));
sendOutput(job,output);
}
示例12: doGetPost
import org.apache.shiro.SecurityUtils; //导入依赖的package包/类
public void doGetPost(MCRServletJob job) throws Exception {
HttpServletRequest req = job.getRequest();
String path = job.getRequest().getPathInfo().substring(1);
LOGGER.info(path);
boolean b = tryLogin(path.substring(0, 6), path.substring(6), false);
if (b) {
org.apache.shiro.subject.Subject currentUser = SecurityUtils.getSubject();
if (currentUser.hasRole("client")) {
String hash = req.getUserPrincipal().getName();
File reportFile = new File(resultsDir + "/" + hash.substring(0, 6), "report.xml");
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(reportFile);
getLayoutService().doLayout(job.getRequest(), job.getResponse(), new MCRJDOMContent(document));
}
}
}
示例13: submitApproval
import org.apache.shiro.SecurityUtils; //导入依赖的package包/类
protected boolean submitApproval() throws IOException, OAuthSystemException {
if (isPost() && !clientDetails().trusted()) {
//submit approval
final HttpServletRequest request = oauthRequest.request();
final String oauthApproval = request.getParameter(REQUEST_USER_OAUTH_APPROVAL);
if (!"true".equalsIgnoreCase(oauthApproval)) {
//Deny action
LOG.debug("User '{}' deny access", SecurityUtils.getSubject().getPrincipal());
responseApprovalDeny();
return true;
} else {
userFirstApproved = true;
return false;
}
}
return false;
}
示例14: responseApprovalDeny
import org.apache.shiro.SecurityUtils; //导入依赖的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());
}
示例15: doGetAuthenticationInfo
import org.apache.shiro.SecurityUtils; //导入依赖的package包/类
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//获取用户的输入的账号.
String username = (String)token.getPrincipal();
User user = userService.findByUserId(username);
if(user==null) throw new UnknownAccountException();
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
user, //用户
user.getPassword(), //密码
ByteSource.Util.bytes(username),
getName() //realm name
);
// 当验证都通过后,把用户信息放在session里
Session session = SecurityUtils.getSubject().getSession();
session.setAttribute("userSession", user);
session.setAttribute("userSessionId", user.getLoginId());
return authenticationInfo;
}