Java Code Examples for org.apache.shiro.SecurityUtils#setSecurityManager()
The following examples show how to use
org.apache.shiro.SecurityUtils#setSecurityManager() .
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: ShiroJwtVerifyingFilterTest.java From cassandra-reaper with Apache License 2.0 | 6 votes |
@Test public void testAuthorization3() 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 eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0LXVzZXIifQ.neIA5mbTFZsZokqG5CFwK7gIxMiBoGOU0anDZmD7kkU"); ShiroJwtVerifyingFilter filter = new ShiroJwtVerifyingFilter(); Assertions.assertThat( filter.isAccessAllowed( req, Mockito.mock(ServletResponse.class), Mockito.mock(Object.class))) .isFalse(); } finally { ThreadContext.unbindSubject(); ThreadContext.unbindSecurityManager(); } }
Example 2
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 3
Source File: CustomResolverTest.java From usergrid with Apache License 2.0 | 6 votes |
@AfterClass public static void tearDownShiro() { doClearSubject(); try { org.apache.shiro.mgt.SecurityManager securityManager = SecurityUtils.getSecurityManager(); LifecycleUtils.destroy( securityManager ); } catch ( UnavailableSecurityManagerException e ) { // we don't care about this when cleaning up the test environment // (for example, maybe the subclass is a unit test and it didn't // need a SecurityManager instance because it was using only // mock Subject instances) } SecurityUtils.setSecurityManager( null ); }
Example 4
Source File: ShiroJwtVerifyingFilterTest.java From cassandra-reaper with Apache License 2.0 | 6 votes |
@Test public void testAuthorization0() 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("junk"); ShiroJwtVerifyingFilter filter = new ShiroJwtVerifyingFilter(); Assertions.assertThat( filter.isAccessAllowed( req, Mockito.mock(ServletResponse.class), Mockito.mock(Object.class))) .isFalse(); } finally { ThreadContext.unbindSubject(); ThreadContext.unbindSecurityManager(); } }
Example 5
Source File: BaseShiroTest.java From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International | 6 votes |
@Test @DisplayName("基本认证测试例") public void testAuthentication() { // 构建 SecurityManager DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager(); defaultSecurityManager.setRealm(simpleAccountRealm); // 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.logout(); System.out.println("isAuthenticated:" + subject.isAuthenticated()); Assertions.assertFalse(subject.isAuthenticated()); }
Example 6
Source File: ShiroHelloWorldTest.java From nano-framework with Apache License 2.0 | 6 votes |
@Test public void helloWorld() { Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); SecurityManager manager = factory.getInstance(); SecurityUtils.setSecurityManager(manager); Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken("admin", "admin"); try { subject.login(token); } catch (AuthenticationException e) { LOG.error("Authentication Invalid: " + e.getMessage()); } Assert.assertEquals(true, subject.isAuthenticated()); subject.logout(); }
Example 7
Source File: SubjectBuilderForBackground.java From bamboobsc with Apache License 2.0 | 5 votes |
public static void login() throws Exception { Factory<org.apache.shiro.mgt.SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); org.apache.shiro.mgt.SecurityManager securityManager = (org.apache.shiro.mgt.SecurityManager) factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); Subject currentUser = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken( Constants.SYSTEM_BACKGROUND_USER, Constants.SYSTEM_BACKGROUND_PASSWORD); currentUser.login(token); //System.out.println(currentUser.hasRole("admin")); //System.out.println(currentUser.hasRole("*")); }
Example 8
Source File: BackgroundProgramUserUtils.java From bamboobsc with Apache License 2.0 | 5 votes |
public static void login() throws Exception { if (securityManager==null) { throw new Exception("Security manager is null!"); } SecurityUtils.setSecurityManager(securityManager); Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken( Constants.SYSTEM_BACKGROUND_USER, Constants.SYSTEM_BACKGROUND_PASSWORD); subject.login(token); subjectThreadLocal.set(subject); }
Example 9
Source File: BackgroundProgramUserUtils.java From bamboobsc with Apache License 2.0 | 5 votes |
public static void login() throws Exception { if (factory==null || securityManager==null) { throw new Exception("Security manager is null!"); } SecurityUtils.setSecurityManager(securityManager); Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken( Constants.SYSTEM_BACKGROUND_USER, Constants.SYSTEM_BACKGROUND_PASSWORD); subject.login(token); subjectThreadLocal.set(subject); }
Example 10
Source File: IngestContextListener.java From jesterj with Apache License 2.0 | 5 votes |
@Override public void contextInitialized(ServletContextEvent sce) { // Use the shiro.ini file at the root of the classpath // (file: and url: prefixes load from files and urls respectively): Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); SecurityManager securityManager = factory.getInstance(); // Since Vaadin doesn't really base its UI on distinct URL paths we will eschew // shiro web module entirely, we just don't need it. SecurityUtils.setSecurityManager(securityManager); }
Example 11
Source File: TestBindClientContextHandler.java From arcusplatform with Apache License 2.0 | 5 votes |
@Before public void setUp() throws Exception { super.setUp(); this.handler = new BindClientContextHandler(cookieConfig, registry, requestAuthorizer); this.channel = new LocalChannel(); this.context = EasyMock.createNiceMock(ChannelHandlerContext.class); EasyMock .expect(this.context.channel()) .andReturn(this.channel) .anyTimes(); SecurityUtils.setSecurityManager(manager); }
Example 12
Source File: ControllerAuthorityCheckInterceptor.java From bamboobsc with Apache License 2.0 | 4 votes |
@Override public String intercept(ActionInvocation actionInvocation) throws Exception { String actionName = actionInvocation.getProxy().getActionName(); String url = actionName + Constants._S2_ACTION_EXTENSION; Subject subject = SecurityUtils.getSubject(); if ( !Constants.getSystem().equals(Constants.getMainSystem()) ) { SecurityUtils.setSecurityManager( (DefaultSecurityManager)AppContext.getBean("securityManager") ); subject = SecurityUtils.getSubject(); } if (subject.hasRole(Constants.SUPER_ROLE_ALL) || subject.hasRole(Constants.SUPER_ROLE_ADMIN)) { SysEventLogSupport.log( (String)subject.getPrincipal(), Constants.getSystem(), url, true ); return actionInvocation.invoke(); } Annotation[] annotations = actionInvocation.getAction().getClass().getAnnotations(); Annotation[] actionMethodAnnotations = null; Method[] methods = actionInvocation.getAction().getClass().getMethods(); for (Method method : methods) { if (actionInvocation.getProxy().getMethod().equals(method.getName())) { actionMethodAnnotations = method.getAnnotations(); } } if (this.isControllerAuthority(annotations, actionMethodAnnotations, subject)) { SysEventLogSupport.log( (String)subject.getPrincipal(), Constants.getSystem(), url, true ); return actionInvocation.invoke(); } if (subject.isPermitted(url) || subject.isPermitted("/"+url)) { SysEventLogSupport.log( (String)subject.getPrincipal(), Constants.getSystem(), url, true ); return actionInvocation.invoke(); } logger.warn("[decline] user=" + subject.getPrincipal() + " url=" + url); String isDojoxContentPane = ServletActionContext.getRequest().getParameter(Constants.IS_DOJOX_CONTENT_PANE_XHR_LOAD); if (YesNo.YES.equals(isDojoxContentPane)) { // dojox.layout.ContentPane 它的 X-Requested-With 是 XMLHttpRequest SysEventLogSupport.log( (String)subject.getPrincipal(), Constants.getSystem(), url, false ); return Constants._S2_RESULT_NO_AUTHORITH; } String header = ServletActionContext.getRequest().getHeader("X-Requested-With"); if ("XMLHttpRequest".equalsIgnoreCase(header)) { PrintWriter printWriter = ServletActionContext.getResponse().getWriter(); printWriter.print(Constants.NO_AUTHZ_JSON_DATA); printWriter.flush(); printWriter.close(); SysEventLogSupport.log( (String)subject.getPrincipal(), Constants.getSystem(), url, false ); return null; } SysEventLogSupport.log( (String)subject.getPrincipal(), Constants.getSystem(), url, false ); return Constants._S2_RESULT_NO_AUTHORITH; }
Example 13
Source File: AbstractShiroTest.java From gazpachoquest with GNU General Public License v3.0 | 4 votes |
protected static void setSecurityManager(SecurityManager securityManager) { SecurityUtils.setSecurityManager(securityManager); }
Example 14
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 15
Source File: CustomResolverTest.java From usergrid with Apache License 2.0 | 4 votes |
@BeforeClass public static void setSecurityManager() { DefaultSecurityManager manager = new DefaultSecurityManager(); SecurityUtils.setSecurityManager( manager ); }
Example 16
Source File: Main.java From java-course-ee with MIT License | 4 votes |
public static void main(String[] args) { // The easiest way to create a Shiro SecurityManager with configured // realms, users, roles and permissions is to use the simple INI config. // We'll do that by using a factory that can ingest a .ini file and // return a SecurityManager instance: // Use the shiro.ini file at the root of the classpath // (file: and url: prefixes load from files and urls respectively): Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); SecurityManager securityManager = factory.getInstance(); // for this simple example quickstart, make the SecurityManager // accessible as a JVM singleton. Most applications wouldn't do this // and instead rely on their container configuration or web.xml for // webapps. That is outside the scope of this simple quickstart, so // we'll just do the bare minimum so you can continue to get a feel // for things. SecurityUtils.setSecurityManager(securityManager); // Now that a simple Shiro environment is set up, let's see what you can do: // get the currently executing user: Subject currentUser = SecurityUtils.getSubject(); // Do some stuff with a Session (no need for a web or EJB container!!!) Session session = currentUser.getSession(); session.setAttribute("someKey", "aValue"); String value = (String) session.getAttribute("someKey"); if (value.equals("aValue")) { log("Retrieved the correct value! [" + value + "]"); } // let's login the current user so we can check against roles and permissions: if (!currentUser.isAuthenticated()) { UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa"); token.setRememberMe(true); try { currentUser.login(token); } catch (UnknownAccountException uae) { log("There is no user with username of " + token.getPrincipal()); } catch (IncorrectCredentialsException ice) { log("Password for account " + token.getPrincipal() + " was incorrect!"); } catch (LockedAccountException lae) { log("The account for username " + token.getPrincipal() + " is locked. " + "Please contact your administrator to unlock it."); } // ... catch more exceptions here (maybe custom ones specific to your application? catch (AuthenticationException ae) { //unexpected condition? error? } } //say who they are: //print their identifying principal (in this case, a username): log("User [" + currentUser.getPrincipal() + "] logged in successfully."); //test a role: if (currentUser.hasRole("schwartz")) { log("May the Schwartz be with you!"); } else { log("Hello, mere mortal."); } //test a typed permission (not instance-level) if (currentUser.isPermitted("lightsaber:weild")) { log("You may use a lightsaber ring. Use it wisely."); } else { log("Sorry, lightsaber rings are for schwartz masters only."); } //a (very powerful) Instance Level permission: if (currentUser.isPermitted("winnebago:drive:eagle5")) { log("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " + "Here are the keys - have fun!"); } else { log("Sorry, you aren't allowed to drive the 'eagle5' winnebago!"); } //all done - log out! currentUser.logout(); System.exit(0); }
Example 17
Source File: IrisAbstractApplication.java From arcusplatform with Apache License 2.0 | 4 votes |
public static void exec(Class<? extends IrisAbstractApplication> appClazz, Collection<Class<? extends Module>> modules, Arguments arguments) { SLF4JBridgeHandler.removeHandlersForRootLogger(); SLF4JBridgeHandler.install(); try { Bootstrap.Builder builder = Bootstrap.builder(); if(arguments.configFile != null) { builder.withConfigPaths(arguments.configFile); } builder.withConstants(mapFromArgs(arguments)); builder.withBootstrapModules(new IrisApplicationModule()); builder.withModuleClasses(modules); //if(arguments.modules != null) { // builder.withModuleClassnames(arguments.modules); //} Injector injector = builder.build().bootstrap(); ServiceLocator.init(GuiceServiceLocator.create(injector)); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { System.out.println("Shutting down..."); ServiceLocator.destroy(); } })); // XXX: is this the right place? Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); // If a security manager is present then initialize it List<? extends SecurityManager> secManager = ServiceLocator.getInstancesOf(SecurityManager.class); if (secManager != null && !secManager.isEmpty()) { if (secManager.size() > 1) { logger.warn("more than one security manager is installed, using first: {}", secManager); } logger.info("installing configured security manager"); SecurityUtils.setSecurityManager(secManager.get(0)); } // Startup the application if its present IrisAbstractApplication app = null; if(appClazz != null) { app = ServiceLocator.getInstance(appClazz); } if (app != null) { logger.info( "starting configured application:\n\t{} v{} [application directory: {}]", app.getApplicationName(), app.getApplicationVersion(), app.getApplicationDir() ); if (app.getApplicationName().equals(IrisApplicationModule.DEFAULT_APPLICATION_NAME)) { logger.error("Application cannot start without a name"); System.exit(1); } StartupListener.publishStarted(); app.start(); } } catch(Exception e) { System.err.println(e.getMessage() + "\n"); e.printStackTrace(System.err); logger.error("Application failed to start", e); System.exit(1); } }
Example 18
Source File: ClientServer.java From arcusplatform with Apache License 2.0 | 4 votes |
@Override protected void start() throws Exception { // Initialize Shiro SecurityUtils.setSecurityManager(ServiceLocator.getInstance(SecurityManager.class)); super.start(); }
Example 19
Source File: AbstractShiroTest.java From seed with Mozilla Public License 2.0 | 4 votes |
protected static void setSecurityManager(SecurityManager securityManager) { SecurityUtils.setSecurityManager(securityManager); }
Example 20
Source File: AlexaServer.java From arcusplatform with Apache License 2.0 | 4 votes |
@Override protected void start() throws Exception { SecurityUtils.setSecurityManager(ServiceLocator.getInstance(SecurityManager.class)); super.start(); }