org.apache.shiro.SecurityUtils Java Examples
The following examples show how to use
org.apache.shiro.SecurityUtils.
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: MainController.java From easyweb-shiro with MIT License | 6 votes |
/** * 登录 */ @ResponseBody @PostMapping("/login") public JsonResult doLogin(String username, String password, String code, HttpServletRequest request) { if (StringUtil.isBlank(username, password)) { return JsonResult.error("账号密码不能为空"); } if (!CaptchaUtil.ver(code, request)) { CaptchaUtil.clear(request); return JsonResult.error("验证码不正确"); } try { UsernamePasswordToken token = new UsernamePasswordToken(username, password); SecurityUtils.getSubject().login(token); addLoginRecord(getLoginUserId(), request); return JsonResult.ok("登录成功"); } catch (IncorrectCredentialsException ice) { return JsonResult.error("密码错误"); } catch (UnknownAccountException uae) { return JsonResult.error("账号不存在"); } catch (LockedAccountException e) { return JsonResult.error("账号被锁定"); } catch (ExcessiveAttemptsException eae) { return JsonResult.error("操作频繁,请稍后再试"); } }
Example #2
Source File: ValidateUserFilter.java From civism-sso with Apache License 2.0 | 6 votes |
@Override protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) { boolean existSession = SecurityUtils.getSubject().isAuthenticated(); if (!existSession) { return false; } else { Session session = SecurityUtils.getSubject().getSession(false); if (session != null) { Serializable id = session.getId(); if (id != null) { if (redisClient.get((String) id) != null) { return true; } } } return false; } }
Example #3
Source File: SysDepartController.java From jeecg-boot-with-activiti with MIT License | 6 votes |
/** * 导出excel * * @param request * @param response */ @RequestMapping(value = "/exportXls") public ModelAndView exportXls(SysDepart sysDepart,HttpServletRequest request) { // Step.1 组装查询条件 QueryWrapper<SysDepart> queryWrapper = QueryGenerator.initQueryWrapper(sysDepart, request.getParameterMap()); //Step.2 AutoPoi 导出Excel ModelAndView mv = new ModelAndView(new JeecgEntityExcelView()); List<SysDepart> pageList = sysDepartService.list(queryWrapper); //按字典排序 Collections.sort(pageList, new Comparator<SysDepart>() { @Override public int compare(SysDepart arg0, SysDepart arg1) { return arg0.getOrgCode().compareTo(arg1.getOrgCode()); } }); //导出文件名称 mv.addObject(NormalExcelConstants.FILE_NAME, "部门列表"); mv.addObject(NormalExcelConstants.CLASS, SysDepart.class); LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal(); mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("部门列表数据", "导出人:"+user.getRealname(), "导出信息")); mv.addObject(NormalExcelConstants.DATA_LIST, pageList); return mv; }
Example #4
Source File: SysUserAgentController.java From jeecg-boot-with-activiti with MIT License | 6 votes |
/** * 导出excel * * @param request * @param response */ @RequestMapping(value = "/exportXls") public ModelAndView exportXls(SysUserAgent sysUserAgent,HttpServletRequest request) { // Step.1 组装查询条件 QueryWrapper<SysUserAgent> queryWrapper = QueryGenerator.initQueryWrapper(sysUserAgent, request.getParameterMap()); //Step.2 AutoPoi 导出Excel ModelAndView mv = new ModelAndView(new JeecgEntityExcelView()); List<SysUserAgent> pageList = sysUserAgentService.list(queryWrapper); //导出文件名称 mv.addObject(NormalExcelConstants.FILE_NAME, "用户代理人设置列表"); mv.addObject(NormalExcelConstants.CLASS, SysUserAgent.class); LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal(); mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("用户代理人设置列表数据", "导出人:"+user.getRealname(), "导出信息")); mv.addObject(NormalExcelConstants.DATA_LIST, pageList); return mv; }
Example #5
Source File: RegisterController.java From PhrackCTF-Platform-Personal with Apache License 2.0 | 6 votes |
@RequestMapping(value = "/register",method = RequestMethod.GET) public ModelAndView doGetRegister() throws Exception { ModelAndView mv = new ModelAndView("register"); Subject currentUser = SecurityUtils.getSubject(); CommonUtils.setUserInfo(currentUser, userServices, submissionServices,mv); CommonUtils.setControllerName(request, mv); if (currentUser.isAuthenticated()||currentUser.isRemembered()) { return new ModelAndView("redirect:/home"); } List<Countries> cts = countryServices.SelectAllCountry(); mv.addObject("country",cts); mv.setViewName("register"); return mv; }
Example #6
Source File: MySysUser.java From erp-framework with MIT License | 6 votes |
public static MyShiroRealm.ShiroUser ShiroUser() { MyShiroRealm.ShiroUser user= (MyShiroRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal(); return user; /** * 这个方式解决了拦截时候,从SecurityUtils.getSubject().getPrincipal()获取的对象为null,而强行转换而报错,但是返回的数据导致拦截器return false,而不能继续执行 * 目前验证码显示不出来,从而问题依旧没有解决 */ // Object obj = SecurityUtils.getSubject().getPrincipal(); // MyShiroRealm.ShiroUser user = new MyShiroRealm.ShiroUser(); // if(obj==null){ // return new MyShiroRealm.ShiroUser(); // } // // if(obj instanceof MyShiroRealm.ShiroUser) { // user = (MyShiroRealm.ShiroUser) obj; // } else { // System.out.print(obj.getClass()+"1111"); // user = JsonUtil.json2Bean(JsonUtil.bean2Json(obj), MyShiroRealm.ShiroUser.class); // } // return user; }
Example #7
Source File: ServiceITSetupImpl.java From usergrid with Apache License 2.0 | 6 votes |
public ServiceITSetupImpl() { super(); managementService = springResource.getBean( ManagementService.class ); applicationCreator = springResource.getBean( ApplicationCreator.class ); tokenService = springResource.getBean( TokenService.class ); providerFactory = springResource.getBean( SignInProviderFactory.class ); properties = springResource.getBean( "properties", Properties.class ); smf = springResource.getBean( ServiceManagerFactory.class ); exportService = springResource.getBean( ExportService.class ); importService = springResource.getBean( ImportService.class ); jobSchedulerService = springResource.getBean(JobSchedulerService.class); try { appInfoMigrationPlugin = springResource.getBean(GuiceFactory.class) .getObject().getInstance(AppInfoMigrationPlugin.class); } catch ( Exception e ) { logger.error("Unable to instantiate AppInfoMigrationPlugin", e); } //set our security manager for shiro SecurityUtils.setSecurityManager(springResource.getBean( org.apache.shiro.mgt.SecurityManager.class )); }
Example #8
Source File: RealmTest.java From cjs_ssms with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) { //此处从ini文件来实现用用户角色权限配置,实际多从数据库表来实现 Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini.bak"); //SercurityManager 对象 SecurityManager instance = factory.getInstance(); SecurityUtils.setSecurityManager(instance); //测试用户 Subject currentUser = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken("admin", "admin"); boolean result = false; try { currentUser.login(token); result = true; LOG.debug("认证成功"); } catch (Exception e) { result = false; LOG.debug("认证失败"); } }
Example #9
Source File: UserController.java From MyBlog with Apache License 2.0 | 6 votes |
@PostMapping("login") @ResponseBody public MyResponse login(@NotBlank String username, @NotBlank String password, boolean rememberMe) { try { //shiro通过SecurityUtils.getSubject()获得主体,主体可以理解为客户端实例,原理在后面讲 Subject subject = SecurityUtils.getSubject(); //已经认证过,也就是该客户端已经登陆过 if (subject.isAuthenticated()) { return MyResponse.createResponse(ResponseEnum.ALREADY_LOGIN); } //一般都使用UsernamePasswordToken,shiro的token中有Principal和Credentials的概念 //Principal代表当前客户端要登录的用户,Credentials代表证明该用户身份的凭证 //UsernamePasswordToken将username作为Principal,password作为Credentials UsernamePasswordToken token = new UsernamePasswordToken(username, password); //rememberMe功能后面讲 token.setRememberMe(rememberMe); subject.login(token); return MyResponse.createResponse(ResponseEnum.SUCC); } catch (AuthenticationException e) { // 用户名或密码错误,不应该明确返回到底是用户不存在还是密码错误 return MyResponse.createResponse(ResponseEnum.ILLEGAL_PARAM); } }
Example #10
Source File: Realm.java From usergrid with Apache License 2.0 | 6 votes |
@Override protected AuthorizationInfo getAuthorizationInfo(PrincipalCollection principals) { UsergridAuthorizationInfo info = (UsergridAuthorizationInfo)super.getAuthorizationInfo(principals); Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); session.setAttribute( "applications", info.getApplicationSet()); session.setAttribute("organizations", info.getOrganizationSet()); if ( info.getOrganization() != null ) { session.setAttribute( "organization", info.getOrganization() ); } if ( info.getApplication() != null ) { session.setAttribute( "application", info.getApplication() ); } return info; }
Example #11
Source File: UserUtils.java From easyweb with Apache License 2.0 | 6 votes |
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; }
Example #12
Source File: ControllerAOP.java From layui-admin with MIT License | 6 votes |
/** * 应用日志存储 * */ @After("operLogCut() && @annotation(operLog)") public void logAdvisor(BizOperLog operLog){ log.info("进入操作日志切面"); // 添加记录日志 HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); UserTest user = (UserTest)SecurityUtils.getSubject().getPrincipal(); String userid = user.getId();// 操作员ID String loginName = user.getLoginName(); String ipAddr = IPUtil.getIpAddr(request);// 访问段ip //从注解中获取操作类型和备注 String opertype = operLog.operType().getValue(); String memo = operLog.memo(); sysOperLogServiceImpl.insertOperLog(userid,loginName,ipAddr,opertype,memo); log.info("记录操作日志成功"); }
Example #13
Source File: ManageController.java From PhrackCTF-Platform-Team with Apache License 2.0 | 6 votes |
/** * 添加新闻的控制器 * * @return * @throws Exception */ @RequestMapping(value = "/admin/addnews",method={RequestMethod.GET}) public ModelAndView AddNews() throws Exception { ModelAndView mv = new ModelAndView("admin/addnews"); Subject currentUser = SecurityUtils.getSubject(); CommonUtils.setControllerName(request, mv); CommonUtils.setUserInfo(currentUser, userServices, teamServices,submissionServices,mv); if (CommonUtils.CheckIpBanned(request, bannedIpServices)) { currentUser.logout(); return new ModelAndView("redirect:/showinfo?err=-99"); } mv.setViewName("admin/addnews"); return mv; }
Example #14
Source File: ShiroDialectTest.java From thymeleaf-extras-shiro with Apache License 2.0 | 6 votes |
@Test public void testPrincipalWithType() { Subject subjectUnderTest = new Subject.Builder(getSecurityManager()).buildSubject(); setSubject(subjectUnderTest); Context context = new Context(); String result; // Guest user result = templateEngine.process(TEST_TEMPLATE_PATH, context); assertFalse(result.contains("shiro:")); assertFalse(result.contains("TYPEPRINCIPAL1")); assertFalse(result.contains("TYPEPRINCIPAL2")); // Logged in user subjectUnderTest.login(new UsernamePasswordToken(USER1, PASS1)); assertEquals(Integer.valueOf(0), SecurityUtils.getSubject().getPrincipals().oneByType(Integer.class)); // sanity result = templateEngine.process(TEST_TEMPLATE_PATH, context); assertFalse(result.contains("shiro:")); assertTrue(result.contains("TYPEPRINCIPAL1<span>0</span>TYPEPRINCIPAL1")); assertTrue(result.contains("TYPEPRINCIPAL20TYPEPRINCIPAL2")); subjectUnderTest.logout(); }
Example #15
Source File: ShiroPermissingTag.java From mumu with Apache License 2.0 | 6 votes |
/** * 验证用户是否具有以下任意一个角色。 * @param roleNames 以 delimeter 为分隔符的角色列表 * @param delimeter 角色列表分隔符 * @return 用户是否具有以下任意一个角色 */ public boolean hasAnyRoles(String roleNames, String delimeter) { Subject subject = SecurityUtils.getSubject(); if (subject != null) { if (delimeter == null || delimeter.length() == 0) { delimeter = ROLE_NAMES_DELIMETER; } for (String role : roleNames.split(delimeter)) { if (subject.hasRole(role.trim()) == true) { return true; } } } return false; }
Example #16
Source File: SysUserServiceImpl.java From watchdog-framework with MIT License | 6 votes |
public SysUserVO getCurrentUser(){ Tools.executeLogin(); Subject subject = SecurityUtils.getSubject(); if(!subject.isAuthenticated()){ throw new RequestException(ResponseCode.NOT_SING_IN); } JwtToken jwtToken = new JwtToken(); Object principal = subject.getPrincipal(); if(principal==null){ throw RequestException.fail("用户信息获取失败"); } BeanUtils.copyProperties(principal,jwtToken); SysUser user = this.findUserByName(jwtToken.getUsername(),false); if(user==null){ throw RequestException.fail("用户不存在"); } //获取菜单/权限信息 List<SysResource> allPer = userRolesRegexResource(roleService.findAllRoleByUserId(user.getId(),true)); SysUserVO vo = new SysUserVO(); BeanUtils.copyProperties(user,vo); vo.setResources(allPer); return vo; }
Example #17
Source File: FileAction.java From Student-Homework-Management-System with MIT License | 6 votes |
/** * 文件上传主页入口方法 * * @param model {@link Model} * @return JSP页面 */ @RequestMapping("fileupload") public String index(Model model) { User user = (User) SecurityUtils.getSubject().getPrincipal(); if (user.getPercode().equals(ADMIN)) { return ADMIN; } boolean firstLogin = userService.isFirstLogin(user.getUid()); if (firstLogin) { return "jsp/firstpd.jsp"; } //用户上传历史实体 List<History> userHistoryList = fileService.getUserHistoryByUserId(user.getUid()); //Student浏览区数据 // orderInfoList already filtered with state model.addAttribute("orderInfoStudentFullList", fileService.getOrderInfoFullEntity()); //下拉框数据 model.addAttribute("orderInfoList", fileService.getOrderInfoEntity()); model.addAttribute("user", user); model.addAttribute("userHistoryList", userHistoryList); return "jsp/fileupload.jsp"; }
Example #18
Source File: ManageController.java From PhrackCTF-Platform-Personal with Apache License 2.0 | 6 votes |
/** * 添加提示的控制器 * * @return * @throws Exception */ @RequestMapping(value = "/admin/addhint",method={RequestMethod.GET}) public ModelAndView AddHint() throws Exception { ModelAndView mv = new ModelAndView("admin/addhint"); Subject currentUser = SecurityUtils.getSubject(); CommonUtils.setControllerName(request, mv); CommonUtils.setUserInfo(currentUser, userServices, submissionServices,mv); if (CommonUtils.CheckIpBanned(request, bannedIpServices)) { currentUser.logout(); return new ModelAndView("redirect:/showinfo?err=-99"); } List<Challenges> challs = challengeServices.getAllChallenges(); mv.addObject("allchalls", challs); mv.setViewName("admin/addhint"); return mv; }
Example #19
Source File: ClusterController.java From chronus with Apache License 2.0 | 6 votes |
/** * 新增环境集群配置 * * @param clusterEntity * @param bindingResult * @return * @throws Exception */ @RequestMapping(value = "/", method = RequestMethod.POST) public Response insert(@RequestBody @Valid ClusterEntity clusterEntity, BindingResult bindingResult) throws Exception { Response response = new Response().success(); try { if (ControllerUtil.checkResponse(response, bindingResult).failed()) { return response; } if (StringUtils.isBlank(clusterEntity.getCluster())) { clusterEntity.setCluster(ChronusConstants.DEF_CLUSTER); } String userName = (String) SecurityUtils.getSubject().getPrincipal(); clusterEntity.setCreatedBy(userName); clusterEntity.setUpdatedBy(userName); clusterService.insert(clusterEntity); } catch (Exception e) { log.error("新增环境配置异常! envEntity:{}", clusterEntity, e); response.hinderFail("新增环境配置异常" + e.getMessage()); } return response; }
Example #20
Source File: MailController.java From PhrackCTF-Platform-Team with Apache License 2.0 | 6 votes |
@RequestMapping(value="admin/mails",method = {RequestMethod.GET}) public ModelAndView Mails() throws Exception { ModelAndView mv = new ModelAndView("admin/mails"); Subject currentUser = SecurityUtils.getSubject(); CommonUtils.setControllerName(request, mv); CommonUtils.setUserInfo(currentUser, userServices, teamServices,submissionServices,mv); if (CommonUtils.CheckIpBanned(request, bannedIpServices)) { currentUser.logout(); return new ModelAndView("redirect:/showinfo?err=-99"); } String uid = request.getParameter("target"); Users touser= null; if (uid!=null && uid.length()>0 && StringUtils.isNumeric(uid) && (touser = userServices.getUserById(Long.valueOf(uid)))!=null) { mv.addObject("target", touser.getEmail()); } else if (uid!=null) { return new ModelAndView("redirect:/showinfo?err=404"); } mv.setViewName("admin/mails"); return mv; }
Example #21
Source File: LoginController.java From springboot-learn with MIT License | 6 votes |
/** * 登录 * * @param username * @param password * @return */ @PostMapping("/login") @ResponseBody public Object submitLogin(String username, String password, boolean rememberMe, String kaptcha) { UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe); //获取当前的Subject Subject currentUser = SecurityUtils.getSubject(); try { // 在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查 // 每个Realm都能在必要时对提交的AuthenticationTokens作出反应 // 所以这一步在调用login(token)方法时,它会走到xxRealm.doGetAuthenticationInfo()方法中,具体验证方式详见此方法 currentUser.login(token); System.out.println("登录成功!"); return 200; } catch (Exception e) { logger.error("登录失败,用户名[{}]", username, e); token.clear(); return 500; } }
Example #22
Source File: ShiroJwtVerifyingFilterTest.java From cassandra-reaper with Apache License 2.0 | 6 votes |
@Test public void testAuthorization1() throws Exception { try { SecurityUtils.setSecurityManager(new DefaultSecurityManager()); new ShiroJwtProvider(Mockito.mock(AppContext.class)); HttpServletRequest req = Mockito.mock(HttpServletRequest.class); Mockito.when(req.getHeader("Authorization")).thenReturn("Bearer "); ShiroJwtVerifyingFilter filter = new ShiroJwtVerifyingFilter(); Assertions.assertThat( filter.isAccessAllowed( req, Mockito.mock(ServletResponse.class), Mockito.mock(Object.class))) .isFalse(); } finally { ThreadContext.unbindSubject(); ThreadContext.unbindSecurityManager(); } }
Example #23
Source File: ManageController.java From PhrackCTF-Platform-Team with Apache License 2.0 | 6 votes |
/** * 添加提示的控制器 * * @return * @throws Exception */ @RequestMapping(value = "/admin/addhint",method={RequestMethod.GET}) public ModelAndView AddHint() throws Exception { ModelAndView mv = new ModelAndView("admin/addhint"); Subject currentUser = SecurityUtils.getSubject(); CommonUtils.setControllerName(request, mv); CommonUtils.setUserInfo(currentUser, userServices, teamServices,submissionServices,mv); if (CommonUtils.CheckIpBanned(request, bannedIpServices)) { currentUser.logout(); return new ModelAndView("redirect:/showinfo?err=-99"); } List<Challenges> challs = challengeServices.getAllChallenges(); mv.addObject("allchalls", challs); mv.setViewName("admin/addhint"); return mv; }
Example #24
Source File: ShiroTag.java From pybbs with GNU Affero General Public License v3.0 | 5 votes |
public boolean hasPermissionOr(String... name) { boolean[] permitted = SecurityUtils.getSubject().isPermitted(name); for (boolean b : permitted) { // 如果有一个权限,就成功 if (b) { return true; } } return false; }
Example #25
Source File: BaseController.java From mysiteforme with Apache License 2.0 | 5 votes |
public User getCurrentUser() { ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal(); if(shiroUser == null) { return null; } User loginUser = userService.selectById(shiroUser.getId()); return loginUser; }
Example #26
Source File: ExpireTokenUserFilter.java From civism-sso with Apache License 2.0 | 5 votes |
@Override protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) { try { Serializable id = SecurityUtils.getSubject().getSession(false).getId(); byte[] value = redisClient.get((String) id); if (value != null) { UserInfo userInfo = SerializeUtil.deserialize(value, UserInfo.class); redisClient.expire((String) id, userInfo.getExpireTime() == null ? SsoConstants.DEFAULT_LOGIN_EXPIRE : userInfo.getExpireTime()); } } catch (Exception e) { logger.error("error ", e); } return true; }
Example #27
Source File: ShiroPermissingTag.java From mumu with Apache License 2.0 | 5 votes |
/** * 验证用户是否具有以下任意一个角色。 * @param roleNames 角色列表 * @return 用户是否具有以下任意一个角色 */ public boolean hasAnyRoles(String[] roleNames) { Subject subject = SecurityUtils.getSubject(); if (subject != null && roleNames != null) { for (int i = 0; i < roleNames.length; i++) { String role = roleNames[i]; if (role != null && subject.hasRole(role.trim()) == true) { return true; } } } return false; }
Example #28
Source File: BaseSupportAction.java From bamboobsc with Apache License 2.0 | 5 votes |
public String getIsSuperRole() { Subject subject = SecurityUtils.getSubject(); if (subject.hasRole(Constants.SUPER_ROLE_ADMIN) || subject.hasRole(Constants.SUPER_ROLE_ALL)) { return YesNo.YES; } return YesNo.NO; }
Example #29
Source File: AccountManager.java From DWSurvey with GNU Affero General Public License v3.0 | 5 votes |
/** * 取出当前登陆用户 */ public User getCurUser(){ Subject subject=SecurityUtils.getSubject(); if(subject!=null){ Object principal=subject.getPrincipal(); if(principal!=null){ User user = findUserByLoginName(principal.toString()); return user; } } return null; }
Example #30
Source File: Permission.java From shiro-velocity-support with Apache License 2.0 | 5 votes |
/** * 验证用户是否具有以下任意一个角色。 * * @param roleNames * 角色列表 * @return 用户是否具有以下任意一个角色 */ public boolean hasAnyRoles(String[] roleNames) { Subject subject = SecurityUtils.getSubject(); if (subject != null && roleNames != null) { for (int i = 0; i < roleNames.length; i++) { String role = roleNames[i]; if (role != null && subject.hasRole(role.trim()) == true) { return true; } } } return false; }