List of usage examples for org.apache.shiro SecurityUtils setSecurityManager
public static void setSecurityManager(SecurityManager securityManager)
From source file:com.netsteadfast.greenstep.base.interceptor.ControllerAuthorityCheckInterceptor.java
License:Apache License
@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(); }/*from www .ja v a 2s.c o m*/ 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; }
From source file:com.netsteadfast.greenstep.base.interceptor.UserLoginInterceptor.java
License:Apache License
@Override public String intercept(ActionInvocation actionInvocation) throws Exception { ActionContext actionContext = actionInvocation.getInvocationContext(); Map<String, Object> session = actionContext.getSession(); this.accountObj = (AccountObj) session.get(Constants.SESS_ACCOUNT); boolean getUserCurrentCookieFail = false; // sysCurrentId cookie, cookiecount tb_sys_usess ? core-web ? /*//from w ww. j av a 2s. c o m * String contextPath = ServletActionContext.getServletContext().getContextPath(); * if (!contextPath.endsWith( ApplicationSiteUtils.getContextPathFromMap(Constants.getMainSystem()) ) ) { */ if (!Constants.getSystem().equals(Constants.getMainSystem())) { /** * 1. admin * 2. admin tester * gsbsc-web http-session admin , ?core-web ??CURRENT cookie ? gsbsc-web * ??? http-session */ this.invalidCurrentSessionForDifferentAccount(actionContext); if (accountObj == null) { getUserCurrentCookie(actionContext); if (accountObj == null && UserCurrentCookie .foundCurrent((HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST))) { // sysCurrentId cookie, cookiecount tb_sys_usess ? core-web ? getUserCurrentCookieFail = true; } } } if (accountObj != null && !StringUtils.isBlank(accountObj.getAccount())) { Map<String, String> dataMap = UserCurrentCookie .getCurrentData((HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST)); String currentId = StringUtils.defaultString(dataMap.get("currentId")); if (StringUtils.isBlank(currentId)) { currentId = "NULL"; } if (uSessLogHelper.countByCurrent(accountObj.getAccount(), currentId) < 1) { return this.redirectLogin(session, getUserCurrentCookieFail); } boolean isUnknownSession = false; SecurityUtils.setSecurityManager((DefaultSecurityManager) AppContext.getBean("securityManager")); Subject subject = SecurityUtils.getSubject(); try { if (subject.isAuthenticated() && !accountObj.getAccount().equals(subject.getPrincipal())) { subject.logout(); } } catch (ExpiredSessionException ese) { logger.warn(ese.getMessage().toString()); return this.redirectLogin(session, getUserCurrentCookieFail); } catch (UnknownSessionException ue) { logger.warn(ue.getMessage().toString()); isUnknownSession = true; } /** * core-web session, gsbsc-web session, gsbsc-web http session * apache shiro session expires */ if (!subject.isAuthenticated() || isUnknownSession) { GreenStepBaseUsernamePasswordToken token = new GreenStepBaseUsernamePasswordToken(); //token.setRememberMe(true); token.setRememberMe(false); token.setCaptcha(""); token.setUsername(accountObj.getAccount()); token.setPassword(((AccountVO) accountObj).getPassword().toCharArray()); try { subject.login(token); } catch (UnknownAccountException uae) { logger.warn(uae.getMessage().toString()); subject = new Subject.Builder().buildSubject(); subject.login(token); } catch (UnknownSessionException use) { logger.warn(use.getMessage().toString()); subject = new Subject.Builder().buildSubject(); /* Serializable sessionId = subject.getSession().getId(); System.out.println("SESSION_ID=" + sessionId); subject = new Subject.Builder( (DefaultSecurityManager)AppContext.getBean("securityManager") ) .sessionId(sessionId) .buildSubject(); */ subject.login(token); } UserAccountHttpSessionSupport.create(actionContext, accountObj); } return actionInvocation.invoke(); } return this.redirectLogin(session, getUserCurrentCookieFail); }
From source file:com.netsteadfast.greenstep.base.interceptor.UserLoginInterceptor.java
License:Apache License
@Override public String intercept(ActionInvocation actionInvocation) throws Exception { ActionContext actionContext = actionInvocation.getInvocationContext(); Map<String, Object> session = actionContext.getSession(); this.accountObj = (AccountObj) session.get(Constants.SESS_ACCOUNT); boolean fromCookieCheckOrRetySubjectLogin = false; boolean getUserCurrentCookieFail = false; // sysCurrentId cookie, cookiecount tb_sys_usess ? core-web ? String contextPath = ServletActionContext.getServletContext().getContextPath(); if (!contextPath.endsWith(ApplicationSiteUtils.getContextPathFromMap(Constants.getMainSystem()))) { /**/* w w w . ja v a2s . co m*/ * 1. admin * 2. admin tester * gsbsc-web http-session admin , ?core-web ??CURRENT cookie ? gsbsc-web * ??? http-session */ this.invalidCurrentSessionForDifferentAccount(actionContext); SecurityUtils.setSecurityManager((DefaultSecurityManager) AppContext.getBean("securityManager")); Subject subject = SecurityUtils.getSubject(); if (accountObj == null) { fromCookieCheckOrRetySubjectLogin = getUserCurrentCookie(actionContext); if (!fromCookieCheckOrRetySubjectLogin && UserCurrentCookie .foundCurrent((HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST))) { // sysCurrentId cookie, cookiecount tb_sys_usess ? core-web ? getUserCurrentCookieFail = true; } } if (accountObj != null && !subject.isAuthenticated()) { fromCookieCheckOrRetySubjectLogin = true; } } if (accountObj != null && !StringUtils.isBlank(accountObj.getAccount())) { if (uSessLogHelper.countByAccount(accountObj.getAccount()) < 1) { return this.redirectLogin(session, getUserCurrentCookieFail); } if (fromCookieCheckOrRetySubjectLogin) { // core-web session, gsbsc-web session, gsbsc-web http session SecurityUtils.setSecurityManager((DefaultSecurityManager) AppContext.getBean("securityManager")); Subject subject = SecurityUtils.getSubject(); GreenStepBaseUsernamePasswordToken token = new GreenStepBaseUsernamePasswordToken(); token.setRememberMe(false); token.setCaptcha(""); token.setUsername(accountObj.getAccount()); token.setPassword(((AccountVO) accountObj).getPassword().toCharArray()); if (!subject.isAuthenticated()) { subject.login(token); } UserAccountHttpSessionSupport.create(actionContext, accountObj); } return actionInvocation.invoke(); } return this.redirectLogin(session, getUserCurrentCookieFail); }
From source file:com.netsteadfast.greenstep.sys.BackgroundProgramUserUtils.java
License:Apache License
public static void login() throws Exception { if (factory == null || securityManager == null) { throw new Exception("Security manager is null!"); }/*from ww w . j a v a 2 s. co m*/ 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); }
From source file:com.netsteadfast.greenstep.sys.SubjectBuilderForBackground.java
License:Apache License
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();/*from ww w . java 2 s . c o m*/ 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("*")); }
From source file:com.njy.shiro.helloword.Quickstart.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,SecurityUtils.getSubject() Subject currentUser = SecurityUtils.getSubject(); // Do some stuff with a Session (no need for a web or EJB container!!!) //session//ww w . j a v a 2s . c o m //?sessioncurrentUser.getSession() Session session = currentUser.getSession(); session.setAttribute("someKey", "aValue"); String value = (String) session.getAttribute("someKey"); if (value.equals("aValue")) { log.info("Retrieved the correct value! [" + value + "]"); } // let's login the current user so we can check against roles and permissions: // ?????? if (!currentUser.isAuthenticated()) { //????UsernamePasswordToken UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa"); //remenberme token.setRememberMe(true); try { // currentUser.login(token); } //UnknownAccountException catch (UnknownAccountException uae) { log.info("There is no user with username of " + token.getPrincipal()); } //???shiroIncorrectCredentialsException catch (IncorrectCredentialsException ice) { log.info("Password for account " + token.getPrincipal() + " was incorrect!"); } //? catch (LockedAccountException lae) { log.info("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.info("User [" + currentUser.getPrincipal() + "] logged in successfully."); //test a role: //?? if (currentUser.hasRole("schwartz")) { log.info("May the Schwartz be with you!"); } else { log.info("Hello, mere mortal."); } //test a typed permission (not instance-level) //?? if (currentUser.isPermitted("lightsaber:weild")) { log.info("You may use a lightsaber ring. Use it wisely."); } else { log.info("Sorry, lightsaber rings are for schwartz masters only."); } //a (very powerful) Instance Level permission: if (currentUser.isPermitted("winnebago:drive:eagle5")) { log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " + "Here are the keys - have fun!"); } else { log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!"); } //all done - log out! currentUser.logout(); System.exit(0); }
From source file:com.oakeel.LoginController.java
@RequiresRoles("admin") public String authenticate() { try {/* w w w .j a va 2 s .c o m*/ Factory<org.apache.shiro.mgt.SecurityManager> factory = new IniSecurityManagerFactory( "classpath:shiro.ini"); org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); } catch (Exception ex) { System.out.println(ex.toString()); } // Example using most common scenario of username/password pair: UsernamePasswordToken token = new UsernamePasswordToken(username, password); // "Remember Me" built-in: token.setRememberMe(rememberMe); Subject currentUser = SecurityUtils.getSubject(); log.info("Submitting login with username of " + getUsername() + " and password of " + getPassword()); try { currentUser.login(token); } catch (AuthenticationException e) { // Could catch a subclass of AuthenticationException if you like log.warn(e.getMessage()); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Login Failed: " + e.getMessage(), e.toString())); return "/login"; } return "protected?faces-redirect=true"; }
From source file:com.opslab.crm.shiro.base.QuickStart.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. SecurityUtils.getSubject(); Subject currentUser = SecurityUtils.getSubject(); // Do some stuff with a Session (no need for a web or EJB container!!!) // Session//w w w . j a v a 2 s. c om // ? Session: Subject#getSession() Session session = currentUser.getSession(); session.setAttribute("someKey", "aValue"); String value = (String) session.getAttribute("someKey"); if (value.equals("aValue")) { log.info("---> Retrieved the correct value! [" + value + "]"); } // let's login the current user so we can check against roles and permissions: // ????. ???. // Subject isAuthenticated() if (!currentUser.isAuthenticated()) { // ???? UsernamePasswordToken UsernamePasswordToken token = new UsernamePasswordToken("zhang", "123"); // rememberme token.setRememberMe(true); try { // . currentUser.login(token); } // , shiro UnknownAccountException . catch (UnknownAccountException uae) { log.info("----> There is no user with username of " + token.getPrincipal()); return; } // , ???, shiro IncorrectCredentialsException catch (IncorrectCredentialsException ice) { log.info("----> Password for account " + token.getPrincipal() + " was incorrect!"); return; } // ? LockedAccountException catch (LockedAccountException lae) { log.info("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.info("----> User [" + currentUser.getPrincipal() + "] logged in successfully."); //test a role: // ??. Subject hasRole . if (currentUser.hasRole("schwartz")) { log.info("----> May the Schwartz be with you!"); } else { log.info("----> Hello, mere mortal."); } //test a typed permission (not instance-level) // ??. Subject isPermitted() if (currentUser.isPermitted("lightsaber:weild")) { log.info("----> You may use a lightsaber ring. Use it wisely."); } else { log.info("Sorry, lightsaber rings are for schwartz masters only."); } //a (very powerful) Instance Level permission: // ??. if (currentUser.isPermitted("user:delete:zhangsan")) { log.info("----> You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " + "Here are the keys - have fun!"); } else { log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!"); } //all done - log out! // . Subject Logout() . System.out.println("---->" + currentUser.isAuthenticated()); currentUser.logout(); System.out.println("---->" + currentUser.isAuthenticated()); System.exit(0); }
From source file:com.own.shiro.tutorials.Tutorial.java
public static void main(String[] args) { log.info("My first apache shiro application"); Factory<org.apache.shiro.mgt.SecurityManager> factory = new IniSecurityManagerFactory( "classpath:shiro/shiro.ini"); SecurityManager securityManager = factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); // get the currently executing user Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); session.setAttribute("someKey", "aValue"); String value = (String) session.getAttribute("someKey"); if (value.equals("aValue")) log.info("Retrieved the correct value ! [" + value + "]"); if (!currentUser.isAuthenticated()) { UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa"); token.setRememberMe(true);/*from w ww. j a v a 2s . c o m*/ try { currentUser.login(token); } catch (UnknownAccountException uae) { log.info("There is no user with username of " + token.getPrincipal()); } catch (IncorrectCredentialsException ice) { log.info("Password for accout " + token.getPrincipal() + " is incorrect !"); } catch (LockedAccountException lae) { log.info("The account for username " + token.getPrincipal() + " is locked, Please contract your administrator to " + "unlock it ."); } // catch more exceptions here (maybe custom ones specific to your application? catch (AuthenticationException ae) { } } log.info("User [" + currentUser.getPrincipal() + "] " + "logged in successfully ."); // test a role if (currentUser.hasRole("schwartz")) { log.info("May the Schwartz be with you!"); } else { log.info("Hello, mere mortal."); } if (currentUser.isPermitted("winnebago:drive:eagle5")) { log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5' . " + "Here are the keys - have fun!"); } else { log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!"); } //all done - log out! currentUser.logout(); System.exit(0); }
From source file:com.proj.test.org.shiro.Tutorial.java
public static void main(String[] args) { System.out.println("ffffff"); Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); SecurityManager securityManager = factory.getInstance(); //make the SecurityManager instance availabe to the //entire application via static memory; SecurityUtils.setSecurityManager(securityManager); // 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")) { System.out.println("recived the correct value{" + value + "}"); }// w w w. j a v a 2s. c o m // let's login the current user so we can check against roles and // permissions if (!currentUser.isAuthenticated()) { UsernamePasswordToken token = new UsernamePasswordToken("guest", "guest"); token.setRememberMe(true); try { currentUser.login(token); } catch (UnknownAccountException uae) { System.out.println("There is no user with username of " + token.getPrincipal()); } catch (IncorrectCredentialsException ice) { System.out.println("Password for account " + token.getPrincipal() + " was incorrect!"); } catch (LockedAccountException lae) { System.out.println("The account for username" + token.getPrincipal() + "is locked." + "Please contact your administrator to unlock it."); } catch (AuthenticationException e) { System.out.println(e.getMessage()); } } // test a role if (currentUser.hasRole("guestRole")) { System.out.println("May be guestRole be with you."); } else { System.out.println("Hello, mere mortal"); } // test a typed permission (not instance-level) if (currentUser.isPermitted("guest:weild")) { System.out.println("You may use a lightsaber ring. Use it wisely."); } else { System.out.println("Sorry, lightsaber rings are for schwartz masters only."); } // a (very powerful) Instance Level permission: if (currentUser.isPermitted("winnebago:drive:eagle5")) { System.out.println("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5' . " + "Here are the keys - have fun!"); } else { System.out.println("Sorry, you aren't allowed to drive the 'eagle5' winnebago!"); } // all done - log out! currentUser.logout(); System.exit(0); }