Java Code Examples for org.apache.shiro.subject.Subject#logout()
The following examples show how to use
org.apache.shiro.subject.Subject#logout() .
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: GuestTagTest.java From thymeleaf-extras-shiro with Apache License 2.0 | 6 votes |
@Test public void itShouldNotRenderGuestTagContentOnLoggedInUser() { Subject subjectUnderTest = createSubject(); setSubject(subjectUnderTest); subjectUnderTest.login(new UsernamePasswordToken(ALICE.email(), ALICE.password())); checkArgument(ALICE.email().equals(subjectUnderTest.getPrincipal())); // sanity String result = processThymeleafFile(FILE_UNDER_TEST, new Context()); assertThat(result, not(containsString("shiro:"))); assertThat(result, not(containsString("GUEST_ATTRIBUTE"))); assertThat(result, not(containsString("GUEST_ELEMENT"))); subjectUnderTest.logout(); }
Example 2
Source File: ShiroFacadeTest.java From thymeleaf-extras-shiro with Apache License 2.0 | 6 votes |
@Test public void itShouldVerifyUserCaesarRolesAndPermissions() throws Exception { final Subject subject = createAndLoginSubject(TestUsers.CAESAR); assertThat("Caesar has permission", hasPermission(PERMISSION_TYPE_1_ACTION_2.label())); assertThat("Caesar does not have permission", !hasPermission("foo")); assertThat("Caesar lacks permission", lacksPermission("foo")); assertThat("Caesar does not lack permission", !lacksPermission(PERMISSION_TYPE_1_ACTION_2.label())); assertThat("Caesar has all permissions", hasAllPermissions(PERMISSION_TYPE_1_ACTION_2.label())); assertThat("Caesar does not have all permissions", !hasAllPermissions(Collections.<String>emptySet())); assertThat("Caesar does not have all permissions", !hasAllPermissions("foo", "bar")); assertThat("Caesar has any permissions", hasAnyPermissions("foo", PERMISSION_TYPE_1_ACTION_2.label())); assertThat("Caesar does not have any permissions", !hasAnyPermissions(Collections.<String>emptySet())); assertThat("Caesar does not have any permissions", !hasAnyPermissions("foo", "bar")); subject.logout(); }
Example 3
Source File: ManageController.java From PhrackCTF-Platform-Team with Apache License 2.0 | 6 votes |
/** * 添加赛题页面 * * @return * @throws Exception */ @RequestMapping(value = "/admin/addprob",method={RequestMethod.GET}) public ModelAndView AddChallengePage() throws Exception { ModelAndView mv = new ModelAndView("admin/addprob"); 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"); } /*显示Category列表*/ List<Categories> cates = categoryServices.selectAllCategory(); if (cates!=null) { mv.addObject("allcates", cates); } mv.setViewName("admin/addprob"); return mv; }
Example 4
Source File: JsetsLogoutFilter.java From jsets-shiro-spring-boot-starter with Apache License 2.0 | 6 votes |
@Override protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception { Subject subject = getSubject(request, response); // Check if POST only logout is enabled if (isPostOnlyLogout()) { // check if the current request's method is a POST, if not redirect if (!WebUtils.toHttp(request).getMethod().toUpperCase(Locale.ENGLISH).equals("POST")) { return onLogoutRequestNotAPost(request, response); } } String redirectUrl = getRedirectUrl(request, response, subject); //try/catch added for SHIRO-298: try { String account = (String) subject.getPrincipal(); subject.logout(); this.authListenerManager.onLogout(request, account); } catch (SessionException ise) { LOGGER.debug("Encountered session exception during logout. This can generally safely be ignored.", ise); } issueRedirect(request, response, redirectUrl); return false; }
Example 5
Source File: UserTagTest.java From thymeleaf-extras-shiro with Apache License 2.0 | 6 votes |
@Test public void itShouldRenderUserTagContentOnLoggedInUser() { Subject subjectUnderTest = createSubject(); setSubject(subjectUnderTest); // Logged in user subjectUnderTest.login(new UsernamePasswordToken(ALICE.email(), ALICE.password())); String result = processThymeleafFile(FILE_UNDER_TEST, new Context()); assertThat(result, not(containsString("shiro:"))); assertThat(result, containsString("USER_ATTRIBUTE")); assertThat(result, containsString("USER_ELEMENT")); assertThat(result, containsString("USER_TH")); subjectUnderTest.logout(); }
Example 6
Source File: ManageController.java From PhrackCTF-Platform-Personal with Apache License 2.0 | 5 votes |
/** * 编辑赛题页面控制器 * * @param id * @return * @throws Exception */ @RequestMapping(value = "/admin/editprob/{id}",method={RequestMethod.GET}) public ModelAndView EditChallenge(@PathVariable long id) throws Exception { ModelAndView mv = new ModelAndView("admin/editprob"); 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"); } Challenges thischallenge = challengeServices.getChallengeById(id); if (thischallenge == null) { return new ModelAndView("redirect:/showinfo?err=404"); } mv.addObject("thischall",thischallenge); /*显示Category列表*/ List<Categories> cates = categoryServices.selectAllCategory(); if (cates!=null) { mv.addObject("allcates", cates); } /*这道题的所有文件*/ List<Files> attaches = fileServices.getFilesByChallengeId(id); if (attaches!=null) { mv.addObject("attachlist", attaches); } mv.setViewName("admin/editprob"); return mv; }
Example 7
Source File: AuthenticationInterceptor.java From EasyEE with MIT License | 5 votes |
@Override public void afterSuccess(ServletRequest request, ServletResponse response, AuthenticationToken token) throws Exception { Subject subject = SecurityUtils.getSubject(); // 不要强制转换,防止 devtools 的 RestartClassLoader 导致的 cast exception UsernamePasswordEncodeToken downToken = new UsernamePasswordEncodeToken(); downToken.setUserId(Integer.valueOf(token.getClass().getMethod("getUserId").invoke(token).toString())); downToken.setName(token.getClass().getMethod("getName").invoke(token).toString()); downToken.setPassword((char[])token.getClass().getMethod("getPassword").invoke(token)); downToken.setRealName(token.getClass().getMethod("getRealName").invoke(token).toString()); downToken.setStatus(Integer.valueOf(token.getClass().getMethod("getStatus").invoke(token).toString())); // 用户锁定 if (downToken.getStatus() == SysUser.STATUS_LOCK) { subject.logout(); throw new LockedAccountException("账户已锁定!"); } // 存入用户信息到Session // SysUser sysUser=new SysUser(downToken.getName(), new // String(downToken.getPassword())); SysUser sysUser = new SysUser(downToken.getName(), ""); sysUser.setPassword(new String(downToken.getPassword())); sysUser.setRealName(downToken.getRealName()); sysUser.setStatus(downToken.getStatus()); sysUser.setUserId(downToken.getUserId()); subject.getSession().setAttribute("USER", sysUser); // 初始化菜单列表 initMenu(subject.getSession(), downToken); // System.out.println("登录成功!"); // System.out.println(sysOperationPermissionService.getAllOpreationNames()); // 保存所有权限对应的权限名称,权限备注 subject.getSession().setAttribute("operationsName", sysOperationPermissionService.getAllOpreationNames()); }
Example 8
Source File: OnlineSessionFilter.java From ruoyiplus with MIT License | 5 votes |
/** * 表示当访问拒绝时是否已经处理了;如果返回true表示需要继续处理;如果返回false表示该拦截器实例已经处理了,将直接返回即可。 */ @Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { Subject subject = getSubject(request, response); if (subject != null) { subject.logout(); } saveRequestAndRedirectToLogin(request, response); return false; }
Example 9
Source File: ManageController.java From PhrackCTF-Platform-Personal with Apache License 2.0 | 5 votes |
/** * 后台操作日志查看界面 * * @return * @throws Exception */ @RequestMapping(value="/admin/oplogs",method = {RequestMethod.GET}) public ModelAndView OperationLogs() throws Exception { ModelAndView mv = new ModelAndView("admin/oplogs"); 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<Operatelog> alllogs = operateLogServices.getAllLogs(); ArrayList<OpLogDisp> displist = new ArrayList<OpLogDisp>(); if (alllogs!=null) { for (Operatelog log:alllogs) { OpLogDisp old = new OpLogDisp(); old.setId(log.getId()); old.setIpaddr(log.getIpaddr()); old.setname(userServices.getUserById(log.getOperatorid()).getUsername()); old.setOperatorid(log.getOperatorid()); old.setOperatefunc(log.getOperatefunc()); old.setOperatetime(log.getOperatetime()); displist.add(old); } } mv.addObject("ops", displist); mv.setViewName("admin/oplogs"); return mv; }
Example 10
Source File: LogoutServlet.java From opensoc-streaming with Apache License 2.0 | 5 votes |
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { logger.info( "Doing logout here..." ); Subject currentUser = SecurityUtils.getSubject(); currentUser.logout(); Cookie authCookie = new Cookie("authToken", "Logout" ); authCookie.setMaxAge( 0 ); resp.addCookie(authCookie); resp.sendRedirect( "/login.jsp" ); }
Example 11
Source File: ShiroDialectTest.java From thymeleaf-extras-shiro with Apache License 2.0 | 5 votes |
@Test public void testHasAnyRoles() { 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("HASANYROLES1")); assertFalse(result.contains("HASANYROLES2")); // Logged in user 1 subjectUnderTest.login(new UsernamePasswordToken(USER1, PASS1)); assertTrue(subjectUnderTest.hasRole("rolea")); // sanity result = templateEngine.process(TEST_TEMPLATE_PATH, context); assertFalse(result.contains("shiro:")); assertTrue(result.contains("HASANYROLES1")); assertTrue(result.contains("HASANYROLES2")); subjectUnderTest.logout(); // Logged in user 2 subjectUnderTest.login(new UsernamePasswordToken(USER2, PASS2)); assertFalse(subjectUnderTest.hasRole("rolea")); // sanity result = templateEngine.process(TEST_TEMPLATE_PATH, context); assertFalse(result.contains("shiro:")); assertFalse(result.contains("HASANYROLES1")); assertFalse(result.contains("HASANYROLES2")); subjectUnderTest.logout(); }
Example 12
Source File: OnlineSessionFilter.java From LuckyFrameWeb with GNU Affero General Public License v3.0 | 5 votes |
/** * 表示当访问拒绝时是否已经处理了;如果返回true表示需要继续处理;如果返回false表示该拦截器实例已经处理了,将直接返回即可。 */ @Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { Subject subject = getSubject(request, response); if (subject != null) { subject.logout(); } saveRequestAndRedirectToLogin(request, response); return false; }
Example 13
Source File: LogoutFilter.java From supplierShop with MIT License | 5 votes |
@Override protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception { try { Subject subject = getSubject(request, response); String redirectUrl = getRedirectUrl(request, response, subject); try { SysUser user = ShiroUtils.getSysUser(); if (StringUtils.isNotNull(user)) { String loginName = user.getLoginName(); // 记录用户退出日志 AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginName, Constants.LOGOUT, MessageUtils.message("user.logout.success"))); // 清理缓存 cache.remove(loginName); } // 退出登录 subject.logout(); } catch (SessionException ise) { log.error("logout fail.", ise); } issueRedirect(request, response, redirectUrl); } catch (Exception e) { log.error("Encountered session exception during logout. This can generally safely be ignored.", e); } return false; }
Example 14
Source File: LoginService.java From centraldogma with Apache License 2.0 | 5 votes |
private static void logoutUserQuietly(ServiceRequestContext ctx, @Nullable Subject user) { try { if (user != null && !user.isAuthenticated()) { user.logout(); } } catch (Exception cause) { logger.debug("{} Failed to logout a user: {}", ctx, user, cause); } }
Example 15
Source File: LoginController.java From Moss with Apache License 2.0 | 4 votes |
@GetMapping("/logout") public String logout() { Subject subject = SecurityUtils.getSubject(); subject.logout(); return "redirect:/login"; }
Example 16
Source File: Main.java From tutorials with MIT License | 4 votes |
public static void main(String[] args) { IniRealm realm = new IniRealm(); Ini ini = Ini.fromResourcePath(Main.class.getResource("/com/baeldung/shiro/permissions/custom/shiro.ini").getPath()); realm.setIni(ini); realm.setPermissionResolver(new PathPermissionResolver()); realm.init(); SecurityManager securityManager = new DefaultSecurityManager(realm); SecurityUtils.setSecurityManager(securityManager); Subject currentUser = SecurityUtils.getSubject(); if (!currentUser.isAuthenticated()) { UsernamePasswordToken token = new UsernamePasswordToken("paul.reader", "password4"); token.setRememberMe(true); try { currentUser.login(token); } catch (UnknownAccountException uae) { log.error("Username Not Found!", uae); } catch (IncorrectCredentialsException ice) { log.error("Invalid Credentials!", ice); } catch (LockedAccountException lae) { log.error("Your Account is Locked!", lae); } catch (AuthenticationException ae) { log.error("Unexpected Error!", ae); } } log.info("User [" + currentUser.getPrincipal() + "] logged in successfully."); if (currentUser.hasRole("admin")) { log.info("Welcome Admin"); } else if(currentUser.hasRole("editor")) { log.info("Welcome, Editor!"); } else if(currentUser.hasRole("author")) { log.info("Welcome, Author"); } else { log.info("Welcome, Guest"); } if(currentUser.isPermitted("/articles/drafts/new-article")) { log.info("You can access articles"); } else { log.info("You cannot access articles!"); } currentUser.logout(); }
Example 17
Source File: UserServiceImpl.java From spring-boot-shiro with Apache License 2.0 | 4 votes |
@Override public void logout() { Subject subject = SecurityUtils.getSubject(); subject.logout(); }
Example 18
Source File: LoginRegisterController.java From DouBiNovel with Apache License 2.0 | 4 votes |
@RequestMapping("/logout") public String logout() { Subject subject = SecurityUtils.getSubject(); subject.logout(); return "redirect:/index"; }
Example 19
Source File: ManageController.java From PhrackCTF-Platform-Personal with Apache License 2.0 | 4 votes |
/** * 所有用户信息的列表 * * @return * @throws Exception */ @RequestMapping(value="/admin/userlist",method = {RequestMethod.GET}) public ModelAndView UserList() throws Exception { ModelAndView mv = new ModelAndView("admin/userlist"); 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<Users> alluser = userServices.getAllUsers(); List<Countries> allcountries = countryServices.SelectAllCountry(); List<IpLogs> alllogs = ipLogServices.getAllOrderByUserId(); ArrayList<UserList> ulist = new ArrayList<UserList>(); if (alluser!=null) { for (Users u:alluser) { UserList user = new UserList(); Countries usercon = null; for (Countries country:allcountries) { if (u.getCountryid()-country.getId()==0) { usercon = country; break; } } //Countries usercon = countryServices.getCountryById(u.getCountryid()); user.setcountrycode(usercon.getCountrycode()); user.setCountryid(u.getCountryid()); user.setcountryname(usercon.getCountryname()); user.setDescription(u.getDescription()); user.setEmail(u.getEmail()); user.setId(u.getId()); //user.setips(ipLogServices.countByUserId(u.getId())); int index1 = -1; int index2 = -1; for (int j=0;j<alllogs.size();j++) { if (alllogs.get(j).getUserid()-u.getId()==0) { index1 = j; break; } } if (index1!=-1) { for (int j=index1;j<alllogs.size();j++) { if (alllogs.get(j).getUserid()-u.getId()!=0) { index2 = j; break; } } if (index2==-1) { index2 = alllogs.size(); } user.setips(index2-index1); } else { user.setips(0); } user.setIsenabled(u.getIsenabled()); user.setLastactive(u.getLastactive()); user.setOrganization(u.getOrganization()); user.setRegtime(u.getRegtime()); user.setRole(u.getRole()); user.setUsername(u.getUsername()); ulist.add(user); } } mv.addObject("userlist",ulist); mv.setViewName("admin/userlist"); return mv; }
Example 20
Source File: CountryController.java From PhrackCTF-Platform-Personal with Apache License 2.0 | 4 votes |
@SuppressWarnings("unchecked") @RequestMapping(value = "/country/{code}",method = {RequestMethod.GET}) public ModelAndView CountryView(@PathVariable String code) throws Exception { ModelAndView mv = new ModelAndView("country"); Subject currentUser = SecurityUtils.getSubject(); CommonUtils.setControllerName(request, mv); CommonUtils.setUserInfo(currentUser, userServices, submissionServices,mv); if (CommonUtils.CheckIpBanned(request, bannedIpServices)) { currentUser.logout(); } Countries countryobj = countryServices.getCountryByCode(code); if (countryobj==null) { return new ModelAndView("redirect:/showinfo?err=404"); } mv.addObject("countryname",countryobj.getCountryname()); mv.addObject("countrycode", countryobj.getCountrycode()); List<Users> userforrank = userServices.getUsersForRank(); ArrayList<RanklistObj> ranklist = new ArrayList<RanklistObj>(); if (userforrank==null) { mv.setViewName("country"); return mv; } for (Users u:userforrank) { RanklistObj aobj = new RanklistObj(); Submissions last = submissionServices.getLastCorrectSubmitByUserId(u.getId()); if (last==null) { aobj.setLastSummit(new Date()); } else { aobj.setLastSummit(last.getSubmitTime()); } aobj.setuserobj(u); ranklist.add(aobj); } CompareScore c = new CompareScore(); Collections.sort(ranklist,c); ArrayList<CountryRank> crl = new ArrayList<CountryRank>(); int rank; rank = 0; for (RanklistObj ro:ranklist) { rank++; CountryRank cr = new CountryRank(); if (ro.getuserobj().getCountryid().equals(countryobj.getId()) && ro.getuserobj().getScore()!=0) { cr.setid(ro.getuserobj().getId()); cr.setname(ro.getuserobj().getUsername()); cr.setrank(rank); cr.setscore(ro.getuserobj().getScore()); crl.add(cr); } } mv.addObject("country_users", crl); mv.setViewName("country"); return mv; }