List of usage examples for org.apache.shiro SecurityUtils setSecurityManager
public static void setSecurityManager(SecurityManager securityManager)
From source file:org.sonatype.nexus.security.internal.DefaultSecuritySystem.java
License:Open Source License
@Inject public DefaultSecuritySystem(final EventBus eventBus, final CacheManager cacheManager, final RealmSecurityManager realmSecurityManager, final RealmManager realmManager, final AnonymousManager anonymousManager, final Map<String, AuthorizationManager> authorizationManagers, final Map<String, UserManager> userManagers) { this.eventBus = checkNotNull(eventBus); this.cacheManager = checkNotNull(cacheManager); this.realmSecurityManager = checkNotNull(realmSecurityManager); this.realmManager = checkNotNull(realmManager); this.anonymousManager = checkNotNull(anonymousManager); this.authorizationManagers = checkNotNull(authorizationManagers); this.userManagers = checkNotNull(userManagers); // FIXME: Why not on start? Seems on start is too late? SecurityUtils.setSecurityManager(realmSecurityManager); eventBus.register(this); started = false;/* w w w . j a va 2 s . c om*/ }
From source file:org.sonatype.nexus.security.NexusHttpAuthenticationFilterTest.java
License:Open Source License
@Before public void bindSubjectToThread() { // setup a simple realm for authc SimpleAccountRealm simpleAccountRealm = new SimpleAccountRealm(); simpleAccountRealm.addAccount("anonymous", "anonymous"); DefaultSecurityManager securityManager = new DefaultSecurityManager(); securityManager.setRealm(simpleAccountRealm); SecurityUtils.setSecurityManager(securityManager); DefaultSessionManager sessionManager = (DefaultSessionManager) securityManager.getSessionManager(); sessionDAO = new EnterpriseCacheSessionDAO(); sessionManager.setSessionDAO(sessionDAO); simpleSession = new SimpleSession(); sessionDAO.create(simpleSession);// w w w.ja v a 2 s . c o m List<PrincipalCollection> principalCollectionList = new ArrayList<PrincipalCollection>(); principalCollectionList.add(new SimplePrincipalCollection("other Principal", "some-realm")); simpleSession.setAttribute(DelegatingSubject.class.getName() + ".RUN_AS_PRINCIPALS_SESSION_KEY", principalCollectionList); DelegatingSession delegatingSession = new DelegatingSession(sessionManager, new DefaultSessionKey(simpleSession.getId())); // set the user subject = new DelegatingSubject(new SimplePrincipalCollection("anonymous", "realmName"), true, null, delegatingSession, securityManager); ThreadContext.bind(subject); }
From source file:org.sonatype.nexus.security.StatelessAndStatefulWebSessionManagerTest.java
License:Open Source License
@Before public void setupSecurityObjects() { // make sure the static securityManager is NOT set SecurityUtils.setSecurityManager(null); SimpleAccountRealm simpleAccountRealm = new SimpleAccountRealm(); simpleAccountRealm.addAccount("user", "user123"); securityManager = new NexusWebRealmSecurityManager(new HashMap<String, RolePermissionResolver>()); securityManager.setRealm(simpleAccountRealm); securityManager.init();/*from ww w. jav a 2s. c om*/ sessionManager = (StatelessAndStatefulWebSessionManager) securityManager.getSessionManager(); sessionDAO = (CachingSessionDAO) sessionManager.getSessionDAO(); setupCacheManager(securityManager); initCache(sessionDAO); }
From source file:org.sonatype.security.DefaultSecuritySystem.java
License:Open Source License
@Inject public DefaultSecuritySystem(final EventBus eventBus, final Map<String, AuthorizationManager> authorizationManagers, final Map<String, Realm> realmMap, final SecurityConfigurationManager securityConfiguration, final RealmSecurityManager securityManager, final CacheManager cacheManager, final Map<String, UserManager> userManagers) { this.eventBus = eventBus; this.authorizationManagers = authorizationManagers; this.realmMap = realmMap; this.securityConfiguration = securityConfiguration; this.securityManager = securityManager; this.cacheManager = cacheManager; this.eventBus.register(this); this.userManagers = userManagers; SecurityUtils.setSecurityManager(this.getSecurityManager()); started = false;/* w w w . java 2 s . c om*/ }
From source file:org.springframework.data.gemfire.config.annotation.ApacheShiroSecurityConfiguration.java
License:Apache License
/** * Registers the given Apache Shiro {@link org.apache.shiro.mgt.SecurityManager} with the Apache Shiro * security framework.// ww w . java 2 s . co m * * @param securityManager {@link org.apache.shiro.mgt.SecurityManager} to register. * @return the given {@link org.apache.shiro.mgt.SecurityManager} reference. * @throws IllegalArgumentException if {@link org.apache.shiro.mgt.SecurityManager} is {@literal null}. * @see org.apache.shiro.SecurityUtils#setSecurityManager(org.apache.shiro.mgt.SecurityManager) * @see org.apache.shiro.mgt.SecurityManager */ protected org.apache.shiro.mgt.SecurityManager registerSecurityManager( org.apache.shiro.mgt.SecurityManager securityManager) { Assert.notNull(securityManager, "The Apache Shiro SecurityManager to register must not be null"); SecurityUtils.setSecurityManager(securityManager); return securityManager; }
From source file:pe.gob.sunat.tecnologia3.arquitectura.framework.desktop.seguridad.Autenticador.java
private Subject autenticar(UsuarioPrincipal principal) { logger.log(Level.INFO, "(class)Autenticador.autenticar..."); try {/*from w ww . j a v a 2s. c o m*/ SecurityUtils.setSecurityManager(getSecurityManager()); currentUser = getSubject(); AuthenticationTokenFactory.setPrincipal(principal); AuthenticationToken token = AuthenticationTokenFactory.getInstance(); currentUser.login(token); } catch (UnknownAccountException | IncorrectCredentialsException e) { logger.log(Level.SEVERE, e.getMessage(), e); String messageError = NbBundle.getMessage(Autenticador.class, "usuario.no.autenticado.db", principal.getUsuario()); throw new AuthenticationException(messageError, e); } return currentUser; }
From source file:presentation.webgui.vitroappservlet.Common.java
License:Open Source License
public static String printDDMenu(String context_App_RealPath, HttpServletRequest request) { StringBuilder authInfoAndButtonHTMLBld = new StringBuilder(); // todo: if commons is refactored as singleton, we could do this only once and store it as a class member (the currentUser object) boolean foundWebEnvInAppContext = false; if (Common.getCommon().getAppContext() != null) { WebEnvironment webEnv = WebUtils.getRequiredWebEnvironment(Common.getCommon().getAppContext()); WebSecurityManager webSecurityManager = webEnv.getWebSecurityManager(); if (webSecurityManager != null) { SecurityUtils.setSecurityManager(webSecurityManager); foundWebEnvInAppContext = true; LOG.info("Success: Retrieved WebEnvironment from context! "); }/*from w w w . j a v a2 s . co m*/ } // // get the currently executing user: // Subject currentUser = SecurityUtils.getSubject(); if (!foundWebEnvInAppContext) { LOG.info("Unable to retrieve WebEnvironment from context! "); Factory<org.apache.shiro.mgt.SecurityManager> factory = new IniSecurityManagerFactory( "classpath:shiro.ini"); org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); } // A simple Shiro environment is set up // get the currently executing user: Subject currentUser = SecurityUtils.getSubject(); // Tests with session variables (todo: remove this after verifying what works and what not -session range / expiration / cleanup) Session session = currentUser.getSession(); String value = (String) session.getAttribute("someKey"); if (value == null || value.trim().isEmpty()) { LOG.info("Session did not have the value stored! "); session.setAttribute("someKey", "aValue"); value = (String) session.getAttribute("someKey"); } if (value.equals("aValue")) { LOG.info("Retrieved the correct value! [" + value + "]"); } authInfoAndButtonHTMLBld.append("<li id=\"loginout\">"); Field[] list = currentUser.getClass().getDeclaredFields(); for (Field f : list) LOG.info(f.getName()); if (currentUser.isAuthenticated()) { String myRole = ""; LOG.info("User [" + currentUser.getPrincipal() + "] logged in successfully."); if (currentUser.hasRole("vsp")) { LOG.info("Role: VSP!"); myRole = "advanced"; } else if (currentUser.hasRole("wsie")) { LOG.info("Role: WSI Enabler!"); myRole = "advanced"; } else if (currentUser.hasRole("user")) { LOG.info("Role: Simple User!"); myRole = "user"; } else { LOG.info("Undefined Role."); myRole = "Undefined"; } //authInfoAndButtonHTMLBld.append("Hello "); //authInfoAndButtonHTMLBld.append( currentUser.getPrincipal()); //authInfoAndButtonHTMLBld.append(" ("); //authInfoAndButtonHTMLBld.append(myRole); authInfoAndButtonHTMLBld.append("<a href=\"" + request.getContextPath() + "/logout\">Logout</a>"); //all done - log out! //currentUser.logout(); } else { LOG.info("Not Authenticated!"); authInfoAndButtonHTMLBld.append("<a href=\"" + request.getContextPath() + "/login.jsp\" >Login</a>"); } authInfoAndButtonHTMLBld.append("</li>"); StringBuilder strBuildToRet = new StringBuilder(); strBuildToRet.append(""); try { String menuWrapperfileContents = readFile( context_App_RealPath + File.separator + "topMenuActions" + File.separator + "_proDD.htm", "UTF-8"); String menuUserActionsContents = ""; if (currentUser.isAuthenticated()) menuUserActionsContents = readFile(context_App_RealPath + File.separator + "topMenuActions" + File.separator + "_proUserActions.htm", "UTF-8"); menuWrapperfileContents = menuWrapperfileContents.replaceAll("#userRoleMenuActionsPlaceHolder#", menuUserActionsContents); // menuWrapperfileContents = menuWrapperfileContents.replaceAll("#vspRoleMenuActionsPlaceHolder#", menuVSPActionsContents); // menuWrapperfileContents = menuWrapperfileContents.replaceAll("#wsieRoleMenuActionsPlaceHolder#", menuWSIEActionsContents); //menuWrapperfileContents = menuWrapperfileContents.replaceAll("#auxMenuActionsPlaceHolder#", menuAuxActionsContents); // as a final step we replace the plcholder for the contextPATH info menuWrapperfileContents = menuWrapperfileContents.replaceAll("#plcholder#", request.getContextPath()); strBuildToRet.append("<div class=\"navbar navbar-fixed-top\">"); strBuildToRet.append("<div id=\"bar\" class=\"navbar-inner\">"); strBuildToRet.append("<ul class=\"nav nav-pills\">"); strBuildToRet.append( "<li id=\"dashboardLogo\"><a href=\"" + request.getContextPath() + "\"> </a></li>"); strBuildToRet.append("</ul>"); strBuildToRet.append("<div class=\"container\" id=\"buttonbar\">"); //strBuildToRet.append("<div class=\"row-fluid\" align=\"center\">"); strBuildToRet.append("<ul class=\"nav nav-pills\">"); strBuildToRet.append(menuWrapperfileContents); strBuildToRet.append("</ul>"); strBuildToRet.append("<ul class=\"nav nav-pills pull-right\">"); strBuildToRet.append(authInfoAndButtonHTMLBld.toString()); strBuildToRet.append("</ul>"); strBuildToRet.append("</div>"); strBuildToRet.append("<div style=\"position:absolute;top:42px;right:0;\">"); strBuildToRet.append("<a href=\"http://www.linkedin.com/groups/VITRO-4305849\">"); strBuildToRet.append("<img src=\"" + request.getContextPath() + "/img/btn_cofollow_badge.png\" alt=\"Follow VITRO on LinkedIn\"></a>"); strBuildToRet.append("</div>"); //strBuildToRet.append("</div>") ; strBuildToRet.append("</div>"); strBuildToRet.append("</div>"); } catch (IOException ioe) { System.out.print(ioe.getMessage()); } return strBuildToRet.toString(); }
From source file:presentation.webgui.vitroappservlet.Common.java
License:Open Source License
public static String printDDBody(String context_App_RealPath, HttpServletRequest request) { StringBuilder authInfoAndButtonHTMLBld = new StringBuilder(); // todo: if commons is refactored as singleton, we could do this only once and store it as a class member (the currentUser object) boolean foundWebEnvInAppContext = false; if (Common.getCommon().getAppContext() != null) { WebEnvironment webEnv = WebUtils.getRequiredWebEnvironment(Common.getCommon().getAppContext()); WebSecurityManager webSecurityManager = webEnv.getWebSecurityManager(); if (webSecurityManager != null) { SecurityUtils.setSecurityManager(webSecurityManager); foundWebEnvInAppContext = true; LOG.info("Success: Retrieved WebEnvironment from context! "); }/*from ww w . j a va 2s. c om*/ } // // get the currently executing user: // Subject currentUser = SecurityUtils.getSubject(); if (!foundWebEnvInAppContext) { LOG.info("Unable to retrieve WebEnvironment from context! "); Factory<org.apache.shiro.mgt.SecurityManager> factory = new IniSecurityManagerFactory( "classpath:shiro.ini"); org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); } // A simple Shiro environment is set up // get the currently executing user: Subject currentUser = SecurityUtils.getSubject(); // Tests with session variables (todo: remove this after verifying what works and what not -session range / expiration / cleanup) Session session = currentUser.getSession(); String value = (String) session.getAttribute("someKey"); if (value == null || value.trim().isEmpty()) { LOG.info("Session did not have the value stored! "); session.setAttribute("someKey", "aValue"); value = (String) session.getAttribute("someKey"); } if (value.equals("aValue")) { LOG.info("Retrieved the correct value! [" + value + "]"); } Field[] list = currentUser.getClass().getDeclaredFields(); for (Field f : list) LOG.info(f.getName()); if (currentUser.isAuthenticated()) { authInfoAndButtonHTMLBld.append("<div class=\"container\" style=\"padding-top: 100px;\">"); authInfoAndButtonHTMLBld.append("</div>"); } else { authInfoAndButtonHTMLBld.append("<div class=\"container\" style=\"padding-top: 100px;\">"); authInfoAndButtonHTMLBld.append("</div>"); authInfoAndButtonHTMLBld.append("<div id=\"notloggedin\" class=\"well\">"); authInfoAndButtonHTMLBld.append("Login to use the VITRO functionalities!"); authInfoAndButtonHTMLBld.append("</div>"); // authInfoAndButtonHTMLBld.append("<div id=\"logoHome\" align=\"center\">"); // authInfoAndButtonHTMLBld.append("<img src=" + request.getContextPath() +"/img/Vitrologo.jpg>"); // authInfoAndButtonHTMLBld.append("</div>"); } StringBuilder strBuildToRet = new StringBuilder(); strBuildToRet.append(""); // strBuildToRet.append("<div id=\"bar\"><table id=general_table><tr>"); // strBuildToRet.append(menuWrapperfileContents); strBuildToRet.append(authInfoAndButtonHTMLBld.toString()); // strBuildToRet.append("</tr></table></div>") ; return strBuildToRet.toString(); }
From source file:presentation.webgui.vitroappservlet.Common.java
License:Open Source License
public static String printSideMenu(String context_App_RealPath, HttpServletRequest request) { StringBuilder authInfoAndButtonHTMLBld = new StringBuilder(); // todo: if commons is refactored as singleton, we could do this only once and store it as a class member (the currentUser object) boolean foundWebEnvInAppContext = false; if (Common.getCommon().getAppContext() != null) { WebEnvironment webEnv = WebUtils.getRequiredWebEnvironment(Common.getCommon().getAppContext()); WebSecurityManager webSecurityManager = webEnv.getWebSecurityManager(); if (webSecurityManager != null) { SecurityUtils.setSecurityManager(webSecurityManager); foundWebEnvInAppContext = true; LOG.info("Success: Retrieved WebEnvironment from context! "); }//from w ww. j a va2 s .co m } // // get the currently executing user: // Subject currentUser = SecurityUtils.getSubject(); if (!foundWebEnvInAppContext) { LOG.info("Unable to retrieve WebEnvironment from context! "); Factory<org.apache.shiro.mgt.SecurityManager> factory = new IniSecurityManagerFactory( "classpath:shiro.ini"); org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); } // A simple Shiro environment is set up // get the currently executing user: Subject currentUser = SecurityUtils.getSubject(); // Tests with session variables (todo: remove this after verifying what works and what not -session range / expiration / cleanup) Session session = currentUser.getSession(); String value = (String) session.getAttribute("someKey"); if (value == null || value.trim().isEmpty()) { LOG.info("Session did not have the value stored! "); session.setAttribute("someKey", "aValue"); value = (String) session.getAttribute("someKey"); } if (value.equals("aValue")) { LOG.info("Retrieved the correct value! [" + value + "]"); } Field[] list = currentUser.getClass().getDeclaredFields(); for (Field f : list) LOG.info(f.getName()); if (currentUser.isAuthenticated()) { String myRole = ""; LOG.info("User [" + currentUser.getPrincipal() + "] logged in successfully."); if (currentUser.hasRole("vsp")) { LOG.info("Role: advanced!"); myRole = "advanced"; } else if (currentUser.hasRole("wsie")) { LOG.info("Role: WSI Enabler!"); myRole = "advanced"; } else if (currentUser.hasRole("user")) { LOG.info("Role: Simple User!"); myRole = "user"; } else { LOG.info("Undefined Role."); myRole = "Undefined"; } authInfoAndButtonHTMLBld.append("<div id=\"sidebar\" class=\"sidebar-nav\">"); authInfoAndButtonHTMLBld.append("<ul class=\"nav nav-tabs nav-stacked\">"); //demo layout if (myRole.equals("user") || myRole.equals("advanced")) { authInfoAndButtonHTMLBld.append("<li id=\"srv-custnew\"><a href=\"" + request.getContextPath() + "/roleEndUser/newservice.jsp\">New service</a></li>"); authInfoAndButtonHTMLBld.append("<li id=\"srv-new\"><a href=\"" + request.getContextPath() + "/roleEndUser/GetComposedServiceDeployListAdvanced\">Deploy services</a></li>"); authInfoAndButtonHTMLBld.append("<li id=\"srv-list\"><a href=\"" + request.getContextPath() + "/roleEndUser/GetComposedServiceListAction\">Manage services</a></li>"); } //reserved for WSI enabler? // if (currentUser.hasRole("wsie")){ // authInfoAndButtonHTMLBld.append("<li id=\"sens-edit\"><a href=\"#\">Edit existing sensors</a></li>"); // authInfoAndButtonHTMLBld.append("<li id=\"sens-discover\"><a href=\"#\">Discover new sensors</a></li>"); // authInfoAndButtonHTMLBld.append("<li id=\"sens-remove\"><a href=\"#\">Remove sensors</a></li>"); //} if (myRole.equals("advanced")) { authInfoAndButtonHTMLBld.append("<li id=\"WSIE\" class=\"dropdown all-camera-dropdown\">"); authInfoAndButtonHTMLBld.append( "<a class=\"dropdown-toggle\" data-toggle=\"dropdown\" href=\"#\">Advanced settings<b class=\"caret\"></b></a>"); authInfoAndButtonHTMLBld.append(" <ul class=\"dropdown-menu\">"); authInfoAndButtonHTMLBld.append("<li data-filter-camera-type=\"all\"><a href=\"" + request.getContextPath() + "/roleWSIE/WSIEnewIsland.jsp\">Register new Island</a></li>"); //authInfoAndButtonHTMLBld.append("<li data-filter-camera-type=\"all\"><a href=\""+request.getContextPath()+"/roleWSIE/WSIEeditIslands.jsp\">View Islands</a></li>"); authInfoAndButtonHTMLBld.append("<li data-filter-camera-type=\"all\"><a href=\"" + request.getContextPath() + "/roleVSP/VSPeditGateways.jsp\">Manage gateways</a></li>"); authInfoAndButtonHTMLBld.append("</ul>"); authInfoAndButtonHTMLBld.append("</li>"); } authInfoAndButtonHTMLBld.append("</ul>"); authInfoAndButtonHTMLBld.append("</div>"); //<li class="dropdown all-camera-dropdown"> // <a class="dropdown-toggle" data-toggle="dropdown" href="#">Control panel<b class="caret"></b></a> // <ul class="dropdown-menu"> // <li data-filter-camera-type="all"><a data-toggle="tab" href="#plcholder#/help/helpcontents.jsp"">Help Topics</a></li> // <li data-filter-camera-type="all"><a data-toggle="tab" href="#plcholder#/help/aboutapp.jsp">About</a></li> // </ul> // </li> } else { } StringBuilder strBuildToRet = new StringBuilder(); strBuildToRet.append(""); // strBuildToRet.append("<div id=\"bar\"><table id=general_table><tr>"); // strBuildToRet.append(menuWrapperfileContents); strBuildToRet.append(authInfoAndButtonHTMLBld.toString()); // strBuildToRet.append("</tr></table></div>") ; return strBuildToRet.toString(); }
From source file:ru.gemini.security.shiro.Main.java
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 + "]"); }/* w w w . j a va2 s. c om*/ // 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); }