org.apache.shiro.subject.Subject Java Examples
The following examples show how to use
org.apache.shiro.subject.Subject.
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: ApiServiceImpl.java From wangmarket with 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 File: LoginServiceImpl.java From SpringBoot-Shiro-Vue-master-20180625 with 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 #3
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 #4
Source File: AppManagerController.java From MultimediaDesktop with 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 #5
Source File: DefaultSecuritySystemTest.java From nexus-public with 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 #6
Source File: Permission.java From shiro-velocity-support with 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 #7
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 #8
Source File: AdminAdminController.java From litemall with 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 #9
Source File: CasSubjectFactory.java From shiro-cas-spring-boot-starter with 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 #10
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 #11
Source File: HasAnyPermissionsTag.java From dubai with 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 #12
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 #13
Source File: SessionEvaluator.java From jqm with 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 #14
Source File: CommonUtils.java From PhrackCTF-Platform-Personal with 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 #15
Source File: ShiroJwtVerifyingFilterTest.java From cassandra-reaper with 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 #16
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 #17
Source File: RoleOrAuthorizationFilter.java From layui-admin with 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 #18
Source File: JwtRolesFilter.java From jsets-shiro-spring-boot-starter with 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 #19
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 #20
Source File: JwtAuthcFilter.java From jsets-shiro-spring-boot-starter with 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 #21
Source File: SubjectUtils.java From usergrid with Apache License 2.0 | 5 votes |
public static boolean isOrganizationAdmin() { if ( isServiceAdmin() ) { return true; } Subject currentUser = getSubject(); if ( currentUser == null ) { return false; } return currentUser.hasRole( ROLE_ORGANIZATION_ADMIN ); }
Example #22
Source File: LoginController.java From xmanager with Apache License 2.0 | 5 votes |
/** * 退出 * @return {Result} */ @PostMapping("/logout") @ResponseBody public Object logout() { logger.info("登出"); Subject subject = SecurityUtils.getSubject(); subject.logout(); return renderSuccess(); }
Example #23
Source File: HmacAuthcFilter.java From jsets-shiro-spring-boot-starter with Apache License 2.0 | 5 votes |
@Override protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { Subject subject = getSubject(request, response); if (null != subject && subject.isAuthenticated()) { return true; } return false; }
Example #24
Source File: TestWebController.java From jeecg-cloud with Apache License 2.0 | 5 votes |
@GetMapping("/article") public ResponseBean article() { Subject subject = SecurityUtils.getSubject(); if (subject.isAuthenticated()) { return new ResponseBean(200, "You are already logged in", null); } else { return new ResponseBean(200, "You are guest", null); } }
Example #25
Source File: ShiroUtils.java From LuckyFrameWeb with GNU Affero General Public License v3.0 | 5 votes |
public static void setSysUser(User user) { Subject subject = getSubject(); PrincipalCollection principalCollection = subject.getPrincipals(); String realmName = principalCollection.getRealmNames().iterator().next(); PrincipalCollection newPrincipalCollection = new SimplePrincipalCollection(user, realmName); // 重新加载Principal subject.runAs(newPrincipalCollection); }
Example #26
Source File: ShiroExt.java From WebStack-Guns with MIT License | 5 votes |
/** * 验证当前用户是否属于以下任意一个角色。 * * @param roleNames 角色列表 * @return 属于:true,否则false */ public boolean hasAnyRoles(String roleNames) { boolean hasAnyRole = false; Subject subject = getSubject(); if (subject != null && roleNames != null && roleNames.length() > 0) { for (String role : roleNames.split(NAMES_DELIMETER)) { if (subject.hasRole(role.trim())) { hasAnyRole = true; break; } } } return hasAnyRole; }
Example #27
Source File: AbstractService.java From usergrid with Apache License 2.0 | 5 votes |
public void checkPermissionsForPath( ServiceContext context, String path ) { Subject currentUser = SubjectUtils.getSubject(); if ( currentUser == null ) { return; } if( isServiceAdmin() ){ if(logger.isDebugEnabled()){ logger.debug("Subject is the sysadmin, short-circuiting and allowing access"); } return; } String perm = getPermissionFromPath( em.getApplicationRef().getUuid(), context.getAction().toString().toLowerCase(), path ); boolean permitted = currentUser.isPermitted( perm ); if ( logger.isDebugEnabled() ) { logger.debug( PATH_MSG, path, context.getAction(), perm, permitted ); } SubjectUtils.checkPermission( perm ); Subject subject = SubjectUtils.getSubject(); if (logger.isDebugEnabled()) { logger.debug("Checked subject {} for perm {}", subject != null ? subject.toString() : "", perm); logger.debug("------------------------------------------------------------------------------"); } }
Example #28
Source File: ShiroAuthenticatingThriftInterceptor.java From attic-aurora with Apache License 2.0 | 5 votes |
@Inject void initialize(Provider<Subject> newSubjectProvider) { checkState(!initialized); subjectProvider = requireNonNull(newSubjectProvider); initialized = true; }
Example #29
Source File: ServiceAuthorityCheckAspect.java From bamboobsc with Apache License 2.0 | 5 votes |
@Around( AspectConstants.LOGIC_SERVICE_PACKAGE ) public Object logicServiceProcess(ProceedingJoinPoint pjp) throws AuthorityException, ServiceException, Throwable { MethodSignature signature=(MethodSignature)pjp.getSignature(); Annotation[] annotations=pjp.getTarget().getClass().getAnnotations(); String serviceId = AspectConstants.getServiceId(annotations); Subject subject = SecurityUtils.getSubject(); Method method = signature.getMethod(); if (subject.hasRole(Constants.SUPER_ROLE_ALL) || subject.hasRole(Constants.SUPER_ROLE_ADMIN)) { SysEventLogSupport.log( (String)subject.getPrincipal(), Constants.getSystem(), this.getEventId(serviceId, method.getName()), true ); return pjp.proceed(); } if (StringUtils.isBlank(serviceId)) { // 沒有 service id 無法判斷檢查 SysEventLogSupport.log( (String)subject.getPrincipal(), Constants.getSystem(), this.getEventId(serviceId, method.getName()), true ); return pjp.proceed(); } if (!this.isServiceAuthorityCheck(annotations)) { // 沒有 ServiceAuthority 或 check=false 就不用檢查了 SysEventLogSupport.log( (String)subject.getPrincipal(), Constants.getSystem(), this.getEventId(serviceId, method.getName()), true ); return pjp.proceed(); } Annotation[] methodAnnotations = method.getAnnotations(); if (this.isServiceMethodAuthority(serviceId, methodAnnotations, subject)) { SysEventLogSupport.log( (String)subject.getPrincipal(), Constants.getSystem(), this.getEventId(serviceId, method.getName()), true ); return pjp.proceed(); } logger.warn( "[decline] user[" + subject.getPrincipal() + "] " + pjp.getTarget().getClass().getName() + " - " + signature.getMethod().getName()); SysEventLogSupport.log( (String)subject.getPrincipal(), Constants.getSystem(), this.getEventId(serviceId, method.getName()), false ); throw new AuthorityException(SysMessageUtil.get(GreenStepSysMsgConstants.NO_PERMISSION)); }
Example #30
Source File: GreenStepBaseFormAuthenticationFilter.java From bamboobsc with Apache License 2.0 | 5 votes |
@Override protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception { HttpServletRequest httpServletRequest = (HttpServletRequest)request; HttpServletResponse httpServletResponse = (HttpServletResponse)response; if (!this.isAjaxRequest(httpServletRequest)) { httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + this.getSuccessUrl()); } else { response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); response.getWriter().write(Constants.NO_AUTHZ_JSON_DATA); } return false; }