Java Code Examples for org.apache.shiro.subject.Subject
The following examples show how to use
org.apache.shiro.subject.Subject.
These examples are extracted from open source projects.
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 Project: wangmarket Author: xnx3 File: ApiServiceImpl.java License: Apache License 2.0 | 6 votes |
public UserVO identityVerifyAndSession(String key) { UserVO vo = identityVerify(key); if(vo.getResult() - UserVO.FAILURE == 0){ return vo; } UsernamePasswordToken token = new UsernamePasswordToken(vo.getUser().getUsername(), vo.getUser().getUsername()); token.setRememberMe(false); Subject currentUser = SecurityUtils.getSubject(); try { currentUser.login(token); } catch ( UnknownAccountException uae ) { uae.printStackTrace(); } catch ( IncorrectCredentialsException ice ) { ice.printStackTrace(); } catch ( LockedAccountException lae ) { lae.printStackTrace(); } catch ( ExcessiveAttemptsException eae ) { eae.printStackTrace(); } catch ( org.apache.shiro.authc.AuthenticationException ae ) { ae.printStackTrace(); } return vo; }
Example #2
Source Project: MultimediaDesktop Author: wu560130911 File: AppManagerController.java License: Apache License 2.0 | 6 votes |
@RequestMapping(value = "/app/listHotApp") public void listAllApplication(Model model, Integer page, Integer limit) { ArrayList<UserRole> roles = new ArrayList<>(); roles.add(UserRole.用户); Subject subject = SecurityUtils.getSubject(); if (subject.hasRole(UserRole.开发者.getRole())) { roles.add(UserRole.开发者); } else if (subject.hasRole(UserRole.管理员.getRole())) { roles.add(UserRole.管理员); } OrderDto order = new OrderDto(Direction.DESC, "useCount"); PageDto<ApplicationDto> apps = applicationService.findBy(null, null, null, null, null, roles, Boolean.TRUE, new PageSize(page, limit), new SortDto(order)); model.addAttribute("apps", apps.getValues()); model.addAttribute("total", apps.getTotalElements()); }
Example #3
Source Project: SpringBoot-Shiro-Vue-master-20180625 Author: gwh2008 File: LoginServiceImpl.java License: Apache License 2.0 | 6 votes |
/** * 登录表单提交 * * @param jsonObject * @return */ @Override public JSONObject authLogin(JSONObject jsonObject) { String username = jsonObject.getString("username"); String password = jsonObject.getString("password"); JSONObject returnData = new JSONObject(); Subject currentUser = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(username, password); try { currentUser.login(token); returnData.put("result", "success"); } catch (AuthenticationException e) { returnData.put("result", "fail"); } return CommonUtil.successJson(returnData); }
Example #4
Source Project: nexus-public Author: sonatype File: DefaultSecuritySystemTest.java License: Eclipse Public License 1.0 | 6 votes |
@Test public void testLogout() throws Exception { SecuritySystem securitySystem = this.getSecuritySystem(); // bind to a servlet request/response // this.setupLoginContext( "test" ); // login UsernamePasswordToken token = new UsernamePasswordToken("jcoder", "jcoder"); Subject subject = securitySystem.getSubject(); Assert.assertNotNull(subject); subject.login(token); // check the logged in user Subject loggedinSubject = securitySystem.getSubject(); // Assert.assertEquals( subject.getSession().getId(), loggedinSubject.getSession().getId() ); Assert.assertTrue(subject.isAuthenticated()); Assert.assertTrue("Subject principal: " + loggedinSubject.getPrincipal() + " is not logged in", loggedinSubject.isAuthenticated()); loggedinSubject.logout(); // the current user should be null subject = securitySystem.getSubject(); Assert.assertFalse(subject.isAuthenticated()); Assert.assertFalse(loggedinSubject.isAuthenticated()); }
Example #5
Source Project: litemall Author: linlinjava File: AdminAdminController.java License: MIT License | 6 votes |
@RequiresPermissions("admin:admin:delete") @RequiresPermissionsDesc(menu = {"系统管理", "管理员管理"}, button = "删除") @PostMapping("/delete") public Object delete(@RequestBody LitemallAdmin admin) { Integer anotherAdminId = admin.getId(); if (anotherAdminId == null) { return ResponseUtil.badArgument(); } // 管理员不能删除自身账号 Subject currentUser = SecurityUtils.getSubject(); LitemallAdmin currentAdmin = (LitemallAdmin) currentUser.getPrincipal(); if (currentAdmin.getId().equals(anotherAdminId)) { return ResponseUtil.fail(ADMIN_DELETE_NOT_ALLOWED, "管理员不能删除自己账号"); } adminService.deleteById(anotherAdminId); logHelper.logAuthSucceed("删除管理员", admin.getUsername()); return ResponseUtil.ok(); }
Example #6
Source Project: shiro-cas-spring-boot-starter Author: hiwepy File: CasSubjectFactory.java License: Apache License 2.0 | 6 votes |
@Override public Subject createSubject(SubjectContext context) { //the authenticated flag is only set by the SecurityManager after a successful authentication attempt. boolean authenticated = context.isAuthenticated(); //although the SecurityManager 'sees' the submission as a successful authentication, in reality, the //login might have been just a CAS rememberMe login. If so, set the authenticated flag appropriately: if (authenticated) { AuthenticationToken token = context.getAuthenticationToken(); if (token != null && token instanceof CasToken) { CasToken casToken = (CasToken) token; // set the authenticated flag of the context to true only if the CAS subject is not in a remember me mode if (casToken.isRememberMe()) { context.setAuthenticated(false); } } } return super.createSubject(context); }
Example #7
Source Project: PhrackCTF-Platform-Personal Author: zjlywjh001 File: RegisterController.java License: 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 #8
Source Project: dubai Author: guuuuo File: HasAnyPermissionsTag.java License: MIT License | 6 votes |
@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; }
Example #9
Source Project: thymeleaf-extras-shiro Author: theborakompanioni File: ShiroDialectTest.java License: 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 #10
Source Project: cassandra-reaper Author: thelastpickle File: ShiroJwtVerifyingFilterTest.java License: Apache License 2.0 | 6 votes |
@Test public void testIsAuthenticated() throws Exception { try { Subject subject = Mockito.mock(Subject.class); Mockito.when(subject.getPrincipal()).thenReturn(Mockito.mock(Object.class)); Mockito.when(subject.isAuthenticated()).thenReturn(true); ThreadContext.bind(subject); ShiroJwtVerifyingFilter filter = new ShiroJwtVerifyingFilter(); Assertions.assertThat( filter.isAccessAllowed( Mockito.mock(HttpServletRequest.class), Mockito.mock(ServletResponse.class), Mockito.mock(Object.class))) .isTrue(); } finally { ThreadContext.unbindSubject(); } }
Example #11
Source Project: PhrackCTF-Platform-Team Author: zjlywjh001 File: ManageController.java License: 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 #12
Source Project: mumu Author: babymm File: ShiroPermissingTag.java License: 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 #13
Source Project: jsets-shiro-spring-boot-starter Author: wj596 File: JwtAuthcFilter.java License: Apache License 2.0 | 6 votes |
@Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { if(isJwtSubmission(request)){ AuthenticationToken token = createJwtToken(request, response); try { Subject subject = getSubject(request, response); subject.login(token); return true; } catch (AuthenticationException e) { LOGGER.error(request.getRemoteHost()+" JWT认证 "+e.getMessage()); CommonUtils.restFailed(WebUtils.toHttp(response) ,ShiroProperties.REST_CODE_AUTH_UNAUTHORIZED,e.getMessage()); } } CommonUtils.restFailed(WebUtils.toHttp(response) ,ShiroProperties.REST_CODE_AUTH_UNAUTHORIZED ,ShiroProperties.REST_MESSAGE_AUTH_UNAUTHORIZED); return false; }
Example #14
Source Project: jsets-shiro-spring-boot-starter Author: wj596 File: JwtRolesFilter.java License: Apache License 2.0 | 6 votes |
@Override protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { Subject subject = getSubject(request, response); if ((null == subject || !subject.isAuthenticated()) && isJwtSubmission(request)) { AuthenticationToken token = createJwtToken(request, response); try { subject = getSubject(request, response); subject.login(token); return this.checkRoles(subject,mappedValue); } catch (AuthenticationException e) { LOGGER.error(request.getRemoteHost()+" JWT鉴权 "+e.getMessage()); CommonUtils.restFailed(WebUtils.toHttp(response) ,ShiroProperties.REST_CODE_AUTH_UNAUTHORIZED,e.getMessage()); } } return false; }
Example #15
Source Project: layui-admin Author: gameloft9 File: RoleOrAuthorizationFilter.java License: MIT License | 6 votes |
@Override protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { Subject subject = getSubject(request, response); String[] rolesArray = (String[]) mappedValue; if (rolesArray == null || rolesArray.length == 0) { return true; } for(int i=0;i<rolesArray.length;i++) { if(subject.hasRole(rolesArray[i])) { // 有一个满足即可 return true; } } return false; }
Example #16
Source Project: PhrackCTF-Platform-Personal Author: zjlywjh001 File: CommonUtils.java License: Apache License 2.0 | 6 votes |
public static Users setUserInfo(Subject currentUser,UserServices userServices,SubmissionServices submissionServices,ModelAndView mv) { if (currentUser==null) { return null; } if (currentUser.isRemembered()||currentUser.isAuthenticated()) { Users userobj = userServices.getUserByEmail((String)currentUser.getPrincipal()); String NickName = userobj.getUsername(); Long score = userobj.getScore(); long rank = getUserrank(userobj,userServices,submissionServices); mv.addObject("nickname", NickName); mv.addObject("score", score); mv.addObject("rank", rank); return userobj; } return null; }
Example #17
Source Project: jqm Author: enioka File: SessionEvaluator.java License: Apache License 2.0 | 6 votes |
@Override public boolean isSessionStorageEnabled(Subject subject) { // If disabled in request (e.g. by using the noSessionCreation filter, it stays disabled. if (WebUtils.isWeb(subject)) { HttpServletRequest request = WebUtils.getHttpRequest(subject); Object o = request.getAttribute(DefaultSubjectContext.SESSION_CREATION_ENABLED); if (o != null && !((Boolean) o)) { return false; } } // Then only allow humans, not API-only users, to create a session if (subject.hasRole("human")) { return true; } // By default, no sessions allowed. return false; }
Example #18
Source Project: PhrackCTF-Platform-Team Author: zjlywjh001 File: ManageController.java License: 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 #19
Source Project: thymeleaf-extras-shiro Author: theborakompanioni File: ShiroFacadeTest.java License: 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 #20
Source Project: shiro-velocity-support Author: eduosi File: Permission.java License: Apache License 2.0 | 6 votes |
/** * 验证用户是否具有以下任意一个权限。 * * @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; }
Example #21
Source Project: tianti Author: xujeff File: LoginController.java License: Apache License 2.0 | 5 votes |
@RequestMapping("/login_out") public String loginOut(HttpServletRequest request){ Subject subject = SecurityUtils.getSubject(); subject.logout(); return "redirect:/login"; }
Example #22
Source Project: dpCms Author: summerDp File: LoginController.java License: Apache License 2.0 | 5 votes |
@RequestMapping(value = "/logout.do") @ResponseBody public Response logout() { Response response = ResponseFactory.getResponse(); Subject currentUser = SecurityUtils.getSubject(); currentUser.logout(); return response; }
Example #23
Source Project: emodb Author: bazaarvoice File: AuthenticationResourceFilter.java License: Apache License 2.0 | 5 votes |
@Override public ContainerResponse filter(ContainerRequest request, ContainerResponse response) { Subject subject = ThreadContext.getSubject(); if (subject != null) { if (subject.isAuthenticated()) { subject.logout(); } ThreadContext.unbindSubject(); } return response; }
Example #24
Source Project: mysiteforme Author: wangl1989 File: LoginController.java License: Apache License 2.0 | 5 votes |
@GetMapping("login") public String login(HttpServletRequest request) { LOGGER.info("跳到这边的路径为:"+request.getRequestURI()); Subject s = SecurityUtils.getSubject(); LOGGER.info("是否记住登录--->"+s.isRemembered()+"<-----是否有权限登录----->"+s.isAuthenticated()+"<----"); if(s.isAuthenticated()){ return "redirect:index"; }else { return "login"; } }
Example #25
Source Project: Shop-for-JavaWeb Author: EleTeam File: SessionCacheManager.java License: MIT License | 5 votes |
public Session getSession(){ Session session = null; try{ Subject subject = SecurityUtils.getSubject(); session = subject.getSession(false); if (session == null){ session = subject.getSession(); } }catch (InvalidSessionException e){ logger.error("Invalid session error", e); }catch (UnavailableSecurityManagerException e2){ logger.error("Unavailable SecurityManager error", e2); } return session; }
Example #26
Source Project: SciGraph Author: SciGraph File: BasicAuthenticator.java License: Apache License 2.0 | 5 votes |
@Override public java.util.Optional<Principal> authenticate(BasicCredentials credentials) throws AuthenticationException { Subject subject = SecurityUtils.getSubject(); try { subject.login(new UsernamePasswordToken(credentials.getUsername(), credentials.getPassword(), false)); User user = new User(subject); return Optional.of(user); } catch (UnknownAccountException | IncorrectCredentialsException | LockedAccountException e) { logger.log(Level.WARNING, e.getMessage(), e); } catch (org.apache.shiro.authc.AuthenticationException ae) { logger.log(Level.WARNING, ae.getMessage(), ae); } return Optional.empty(); }
Example #27
Source Project: mall Author: bigspiders File: AdminAuthController.java License: MIT License | 5 votes |
@RequiresAuthentication @PostMapping("/logout") public Object login() { Subject currentUser = SecurityUtils.getSubject(); currentUser.logout(); return ResponseUtil.ok(); }
Example #28
Source Project: mblog Author: langhsu File: MenusDirective.java License: GNU General Public License v3.0 | 5 votes |
private List<Menu> filterMenu(Subject subject) { List<Menu> menus = MenuJsonUtils.getMenus(); if (!subject.hasRole(Role.ROLE_ADMIN)) { menus = check(subject, menus); } return menus; }
Example #29
Source Project: attic-polygene-java Author: apache File: PasswordDomainTest.java License: Apache License 2.0 | 5 votes |
@Test public void test() throws UnitOfWorkCompletionException { UnitOfWork uow = unitOfWorkFactory.newUnitOfWork(); UserFactory userFactory = serviceFinder.findService( UserFactory.class ).get(); // START SNIPPET: usage User user = userFactory.createNewUser( "foo", "bar" ); // END SNIPPET: usage uow.complete(); uow = unitOfWorkFactory.newUnitOfWork(); // START SNIPPET: usage Subject currentUser = SecurityUtils.getSubject(); currentUser.login( new UsernamePasswordToken( "foo", "bar" ) ); // END SNIPPET: usage assertNotNull( "Unable to authenticate against PasswordRealmService", currentUser.getPrincipal() ); assertFalse( currentUser.hasRole( "role-one" ) ); uow.discard(); }
Example #30
Source Project: usergrid Author: apache File: SubjectUtils.java License: Apache License 2.0 | 5 votes |
public static boolean isAnonymous() { Subject currentUser = getSubject(); if ( currentUser == null ) { return true; } return !currentUser.isAuthenticated() && !currentUser.isRemembered(); }