Java Code Examples for org.apache.shiro.subject.Subject#checkPermission()
The following examples show how to use
org.apache.shiro.subject.Subject#checkPermission() .
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: UserController.java From spring-boot-study with MIT License | 6 votes |
@GetMapping("/show") @ResponseBody public String show(){ Subject subject = SecurityUtils.getSubject(); String str=""; if(subject.hasRole("admin")){ str=str+"您拥有 admin 权限"; }else{ str=str+"您没有 admin 权限"; } if(subject.hasRole("sale")){ str=str+"您拥有 sale 权限"; } else{ str=str+"您没有 sale 权限"; } try{ subject.checkPermission("app:setting:setting"); str=str+"您拥有 app:setting:setting 权限"; }catch (UnauthenticatedException ex){ str=str+"您没有 app:setting:setting 权限"; } return str; }
Example 2
Source File: ShiroTest.java From spring-tutorial with Creative Commons Attribution Share Alike 4.0 International | 6 votes |
private void login(String username, String password) { Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(username, password); try { subject.login(token); subject.checkRole("admin"); subject.checkPermission("user:create"); log.debug("username: {}, password: {},登录成功!", username, password); } catch (Exception e) { log.debug("username: {}, password: {} 登录失败!", username, password); } finally { userRealm.clearAllCache(); if (subject.isAuthenticated()) { subject.logout(); } } }
Example 3
Source File: QuestionnaireResource.java From gazpachoquest with GNU General Public License v3.0 | 6 votes |
@GET @Path("/{questionnaireId}/page") @ApiOperation(value = "Fetch the next, current or previous page for the given questionnaire", notes = "More notes about this method", response = QuestionnairePageDTO.class) @ApiResponses(value = { @ApiResponse(code = 404, message = "Invalid invitation token supplied"), @ApiResponse(code = 200, message = "questionnaires available") }) public Response getPage( @NotNull @PathParam("questionnaireId") @ApiParam(value = "Questionnaire id", required = true) Integer questionnaireId, @ApiParam(name = "mode", value = "Refers how many questions are returned by page.", required = false, defaultValue = "SECTION_BY_SECTION", allowableValues = "QUESTION_BY_QUESTION,SECTION_BY_SECTION,ALL_IN_ONE", allowMultiple = true) @QueryParam("mode") String modeStr, @ApiParam(name = "preferredLanguage", value = "Preferred Language for the page is availabe", required = true, defaultValue = "EN", allowableValues = "EN,ES,FI", allowMultiple = true) @QueryParam("preferredLanguage") String preferredLanguageStr, @ApiParam(name = "action", value = "Action fired for the respondent", required = true, defaultValue = "ENTERING", allowableValues = "NEXT,PREVIOUS,ENTERING", allowMultiple = true) @QueryParam("action") String actionStr) { Subject subject = SecurityUtils.getSubject(); User principal = (User) SecurityUtils.getSubject().getPrincipal(); subject.checkPermission("questionnaire:read:" + questionnaireId); logger.info("Fetching questionnaire {} for {} user {}", questionnaireId, principal.getFullName()); RenderingMode mode = StringUtils.isNotBlank(modeStr) ? RenderingMode.fromValue(modeStr) : null; NavigationAction action = NavigationAction.fromString(actionStr); Language preferredLanguage = Language.fromString(preferredLanguageStr); QuestionnairePageDTO page = questionnaireFacade.resolvePage(questionnaireId, mode, preferredLanguage, action); return Response.ok(page).build(); }
Example 4
Source File: QuestionnaireResource.java From gazpachoquest with GNU General Public License v3.0 | 6 votes |
@POST @Path("/{questionnaireId}/answer") @Consumes(MediaType.APPLICATION_JSON) @ApiOperation(value = "Allow the respondent save answers") @ApiResponses(value = { @ApiResponse(code = 404, message = "Invalid invitation token supplied"), @ApiResponse(code = 200, message = "Answer saved correctly") }) public Response saveAnswer( @ApiParam(value = "Answer", required = true) Answer answer, @NotNull @PathParam("questionnaireId") @ApiParam(value = "Questionnaire id", required = true) Integer questionnaireId, @NotNull @QueryParam("questionCode") @ApiParam(value = "Question Code", required = true) String questionCode) { Subject subject = SecurityUtils.getSubject(); User principal = (User) SecurityUtils.getSubject().getPrincipal(); subject.checkPermission("questionnaire:update:" + questionnaireId); logger.debug("User {} saving answers for questionnaireId {}", principal.getFullName(), questionnaireId); questionnaireFacade.saveAnswer(questionnaireId, questionCode, answer); return Response.ok().build(); }
Example 5
Source File: ResearchResource.java From gazpachoquest with GNU General Public License v3.0 | 6 votes |
@POST @Path("/{researchId}/addRespondent") @Consumes(MediaType.APPLICATION_JSON) @ApiOperation(value = "Add the respondent to existing research") @ApiResponses(value = { @ApiResponse(code = 404, message = "Invalid invitation token supplied"), @ApiResponse(code = 200, message = "Respondent added correctly") }) public Response saveAnswer(@ApiParam(value = "Respondent", required = true) UserDTO respondentDTO, @NotNull @PathParam("researchId") @ApiParam(value = "Research id", required = true) Integer researchId) { Subject subject = SecurityUtils.getSubject(); User principal = (User) SecurityUtils.getSubject().getPrincipal(); subject.checkPermission("research:update:" + researchId); logger.debug("User {} adding respondent to researchId = {}", principal.getFullName(), researchId); researchFacade.addRespondent(researchId, respondentDTO); return Response.ok().build(); }
Example 6
Source File: MyShiroRealmTest.java From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
@Test public void testAuthentication() { // 构建 SecurityManager DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager(); defaultSecurityManager.setRealm(myRealm); // Subject 提交认证请求 SecurityUtils.setSecurityManager(defaultSecurityManager); // 设置 SecurityManager Subject subject = SecurityUtils.getSubject(); // 获取当前 Subject // 登录 UsernamePasswordToken token = new UsernamePasswordToken("root", "root"); subject.login(token); // subject.isAuthenticated() 用于判断用户是否认证成功 System.out.println("isAuthenticated:" + subject.isAuthenticated()); Assertions.assertTrue(subject.isAuthenticated()); // 判断 subject 是否是指定的一个或多个角色 subject.checkRoles("admin", "user"); Assertions.assertTrue(subject.hasRole("admin")); Assertions.assertTrue(subject.hasRole("user")); Assertions.assertFalse(subject.hasRole("xxx")); Assertions.assertTrue(subject.hasAllRoles(Arrays.asList("admin", "user"))); Assertions.assertFalse(subject.hasAllRoles(Arrays.asList("admin", "user", "xxx"))); // 判断 subject 是否是拥有指定的一个或多个权限 subject.checkPermission("user:add"); subject.checkPermission("user:delete"); subject.checkPermissions("user:add", "user:delete"); Assertions.assertTrue(subject.isPermitted("user:add")); Assertions.assertTrue(subject.isPermitted("user:delete")); Assertions.assertTrue(subject.isPermittedAll("user:add", "user:delete")); Assertions.assertFalse(subject.isPermittedAll("user:add", "user:delete", "user:update")); }
Example 7
Source File: ShiroRequiresPermissionsProcesser.java From jboot with Apache License 2.0 | 5 votes |
@Override public AuthorizeResult authorize() { try { String[] perms = requiresPermissions.value(); Subject subject = SecurityUtils.getSubject(); if (perms.length == 1) { subject.checkPermission(perms[0]); return AuthorizeResult.ok(); } if (Logical.AND.equals(requiresPermissions.logical())) { subject.checkPermissions(perms); return AuthorizeResult.ok(); } if (Logical.OR.equals(requiresPermissions.logical())) { // Avoid processing exceptions unnecessarily - "delay" throwing the // exception by calling hasRole first boolean hasAtLeastOnePermission = false; for (String permission : perms) if (subject.isPermitted(permission)) hasAtLeastOnePermission = true; // Cause the exception if none of the role match, note that the // exception message will be a bit misleading if (!hasAtLeastOnePermission) subject.checkPermission(perms[0]); } return AuthorizeResult.ok(); } catch (AuthorizationException e) { return AuthorizeResult.fail(AuthorizeResult.ERROR_CODE_UNAUTHORIZATION); } }
Example 8
Source File: AuthorizationResourceFilter.java From emodb with Apache License 2.0 | 5 votes |
/** * Authorizes the client for the annotated permissions. If any authorizations fail an {@link AuthorizationException} * will be thrown, otherwise the original request is returned. */ @Override public ContainerRequest filter(ContainerRequest request) { Subject subject = ThreadContext.getSubject(); String[] permissions = resolvePermissions(request); if (permissions.length == 1 || _logical == Logical.AND) { // Shortcut call to check all permissions at once subject.checkPermissions(permissions); } else { // Check each permission until any passes boolean anyPermitted = false; int p = 0; while (!anyPermitted) { try { subject.checkPermission(permissions[p]); anyPermitted = true; } catch (AuthorizationException e) { // If this is the last permission then pass the exception along if (++p == permissions.length) { throw e; } } } } return request; }
Example 9
Source File: EmptyRoleTest.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Test public void testAuthorizeUserWithEmptyRole() throws Exception { SecuritySystem securitySystem = this.lookup(SecuritySystem.class); RealmManager realmManager = lookup(RealmManager.class); RealmConfiguration realmConfiguration = new TestRealmConfiguration(); realmConfiguration.setRealmNames(ImmutableList.of(AuthenticatingRealmImpl.NAME, AuthorizingRealmImpl.NAME)); realmManager.setConfiguration(realmConfiguration); AuthorizationManager authManager = securitySystem.getAuthorizationManager("default"); // create an empty role Role emptyRole = this.buildEmptyRole(); // this should work fine authManager.addRole(emptyRole); Role normalRole = new Role("normalRole-" + Math.random(), "NormalRole", "Normal Role", "default", false, new HashSet<String>(), new HashSet<String>()); normalRole.addPrivilege(this.createTestPriv()); authManager.addRole(normalRole); // now create a user and add it to the user User user = this.buildTestUser(); user.addRole(new RoleIdentifier(emptyRole.getSource(), emptyRole.getRoleId())); user.addRole(new RoleIdentifier(normalRole.getSource(), normalRole.getRoleId())); // create the user, this user only has an empty role securitySystem.addUser(user, "password"); // now authorize the user Subject subject = securitySystem.getSubject(); subject.login(new UsernamePasswordToken(user.getUserId(), "password")); // check if the user is able to be authenticated if he has an empty role subject.checkPermission("app:config:read"); }
Example 10
Source File: QuestionnaireResource.java From gazpachoquest with GNU General Public License v3.0 | 5 votes |
@GET @Path("/{questionnaireId}/definition") @ApiOperation(value = "Get questionnaire definition", notes = "More notes about this method", response = QuestionnaireDefinitionDTO.class) @ApiResponses(value = { @ApiResponse(code = 404, message = "Invalid invitation token supplied"), @ApiResponse(code = 200, message = "questionnaires available") }) public Response getDefinition( @NotNull @PathParam("questionnaireId") @ApiParam(value = "Questionnaire id", required = true) Integer questionnaireId) { Subject subject = SecurityUtils.getSubject(); User principal = (User) SecurityUtils.getSubject().getPrincipal(); subject.checkPermission("questionnaire:read:" + questionnaireId); logger.debug("Fetching Questionnaire Definition {} for user {}", questionnaireId, principal.getFullName()); QuestionnaireDefinitionDTO questionnaireDefinitionDTO = questionnaireFacade.getDefinition(questionnaireId); return Response.ok(questionnaireDefinitionDTO).build(); }
Example 11
Source File: SubjectUtils.java From usergrid with Apache License 2.0 | 5 votes |
public static void checkPermission( String permission ) { Subject currentUser = getSubject(); if ( currentUser == null ) { return; } try { currentUser.checkPermission( permission ); } catch ( org.apache.shiro.authz.UnauthenticatedException e ) { if (logger.isTraceEnabled()) { logger.trace("checkPermission(): Subject is anonymous"); } } }