Spring Boot integrates Shiro and CAS
Before reading this article, read the following knowledge points:
1. What is Shiro? How to use it?
2. What is Cas? How to use it?
3. It is best to have Spring Basics
Let's take a look at the two articles and repeat them according to the content of the two articles:
Spring Boot Shiro permission management
CAS Single Sign-on
First, let's take a look at the following figure:
The first process is simply using Shiro.
The second process is simply using Cas.
The third figure is the process after Shiro integrates Cas.
[Flowchart link: http://www.bkjia.com/uploads/allianz 160119/0421296008-0.png]
PS: the flowchart is drawn in a hurry. There should be no overall problem. Please leave a message to correct the problem.
If you are only planning to use your Spring Boot project, you can complete the following configuration.
If you want to learn more about the details, we recommend that you configure Shiro and Cas separately.
Shiro began to provide cas integration in version 1.2 and added dependencies to pom. xml as follows:
org.apache.shiro
shiro-spring
1.2.4
org.apache.shiro
shiro-ehcache
1.2.4
org.apache.shiro
shiro-cas
1.2.4
Shiro-cas depends on shiro-web, shiro-web depends on shiro-core, so the shiro-web.jar and shiro-core.jar are automatically referenced after shiro-cas is added.
After cas is integrated by shiro, shiro adds casFilter to the filterChain of shiroFilter.
Create ShiroCasConfiguration. java in the SpringBoot Project
Package org. springboot. sample. config; import java. util. hashMap; import java. util. linkedHashMap; import java. util. map; import javax. servlet. filter; import org. apache. shiro. cache. ehcache. ehCacheManager; import org. apache. shiro. cas. casFilter; import org. apache. shiro. cas. casSubjectFactory; import org. apache. shiro. spring. lifecycleBeanPostProcessor; import org. apache. shiro. spring. security. interceptor. authorizatio NAttributeSourceAdvisor; import org. apache. shiro. spring. web. shiroFilterFactoryBean; import org. apache. shiro. web. mgt. defaultWebSecurityManager; import org. slf4j. logger; import org. slf4j. loggerFactory; import org. springboot. sample. dao. IScoreDao; import org. springboot. sample. security. myShiroCasRealm; import org. springboot. sample. service. studentService; import org. springframework. aop. framework. autoproxy. defau LtAdvisorAutoProxyCreator; import org. springframework. boot. context. embedded. filterRegistrationBean; import org. springframework. context. annotation. bean; import org. springframework. context. annotation. configuration; import org. springframework. web. filter. delegatingFilterProxy;/*** Shiro integrated Cas configuration ** @ author single redwoo (365384722) * @ myblog http://blog.csdn.net/catoop/ * @ create January 17, 2016 */@ Configurationpublic cl Ass ShiroCasConfiguration {private static final Logger logger = LoggerFactory. getLogger (ShiroCasConfiguration. class); // CasServerUrlPrefix public static final String casServerUrlPrefix = "https: // localhost: 8443/cas "; // Cas logon page address: public static final String casLoginUrl = casServerUrlPrefix + "/login"; // Cas logout page address: public static final String casLogoutUrl = casServerUrlPrefix + "/logout "; // open the current project Public static final String shiroServerUrlPrefix = "http: // localhost: 9090/myspringboot"; // casFilter UrlPattern public static final String casFilterUrlPattern = "/shiro-cas "; // The logon address is public static final String loginUrl = casLoginUrl + "? Service = "+ shiroServerUrlPrefix + casFilterUrlPattern; public EhCacheManager getEhCacheManager () {EhCacheManager em = new EhCacheManager (); em. setCacheManagerConfigFile ("classpath: ehcache-shiro.xml"); return em;}/*** register DelegatingFilterProxy (Shiro) ** @ param dispatcherServlet * @ return * @ author SHANHY * @ create January 13, 2016 */@ Bean public FilterRegistrationBean filterRegistrationBean () {FilterRegistrationBean filterRegistration = new FilterRegistrationBean (); filterRegistration. setFilter (new DelegatingFilterProxy ("shiroFilter"); // The default value is false, indicating that the lifecycle is managed by SpringApplicationContext. If it is set to true, it indicates that filterRegistration is managed by ServletContainer. addInitParameter ("targetFilterLifecycle", "true"); filterRegistration. setEnabled (true); filterRegistration. addUrlPatterns ("/*"); return filterRegistration ;}@ Bean (name = "lifecycleBeanPostProcessor") public LifecycleBeanPostProcessor submit () {return new LifecycleBeanPostProcessor ();} @ Bean public DefaultAdvisorAutoProxyCreator getdefaadadvisorautoproxycreator () {DefaultAdvisorAutoProxyCreator daap = new DefaultAdvisorAutoProxyCreator (); daap. setProxyTargetClass (true); return daap;} @ Bean (name = "securityManager") public DefaultWebSecurityManager secure (MyShiroCasRealm myShiroCasRealm) {defawebsecuritymanager dwsm = new DefaultWebSecurityManager (); dwsm. setRealm (myShiroCasRealm); // dwsm. setCacheManager (getEhCacheManager (); // specify SubjectFactory dwsm. setSubjectFactory (new CasSubjectFactory (); return dwsm;} @ Bean public jsonlistener (defawebwebsecuritymanager securityManager) {AuthorizationAttributeSourceAdvisor aasa = new AuthorizationAttributeSourceAdvisor (); aasa. setSecurityManager (securityManager); return aasa;}/*** load the shiroFilter permission control rule (read from the database and then configure it) ** @ author SHANHY * @ create January 14, 2016 */private void loadShiroFilterChain (ShiroFilterFactoryBean shiroFilterFactoryBean, StudentService stuService, IScoreDao scoreDao) {// The following rule configurations are best configured in the configuration file ////// /// // Map
FilterChainDefinitionMap = new LinkedHashMap
(); FilterChainDefinitionMap. put (casFilterUrlPattern, "casFilter"); // After shiro integrates cas, add the rule // authc: The page under the filter must be verified before access, it is a built-in interceptor org. apache. shiro. web. filter. authc. formAuthenticationFilter filterChainDefinitionMap. put ("/user", "authc"); // here, only/user is restricted for testing. In actual development, change it to the specific blocking request rule. // anon: its corresponding filter is empty, and logger.info ("####################### read permission rules from the database, load it to shiroFilter ################## "); filterChainDefiniti OnMap. put ("/user/edit/**", "authc, perms [user: edit]"); // for the purpose of testing, fixed write dead value, you can also read filterChainDefinitionMap from the database or other configurations. put ("/login", "anon"); filterChainDefinitionMap. put ("/**", "anon"); // anon can be understood as not intercepting shiroFilterFactoryBean. setFilterChainDefinitionMap (filterChainDefinitionMap);}/*** CAS filter ** @ return * @ author SHANHY * @ create January 17, 2016 */@ Bean (name = "casFilter") public CasFilter getCasFilter () {CasFilter casFilter = new CasFilter (); casFilter. setName ("casFilter"); casFilter. setEnabled (true); // the URL to jump to after logon failure, that is, Shiro executes the doGetAuthenticationInfo method of CasRealm to verify tiket casFilter to CasServer. setFailureUrl (loginUrl); // return casFilter on the logon page after failed authentication is selected;}/*** ShiroFilter ** note that the StudentService and IScoreDao parameters here are just an example, this is because we can obtain the objects for accessing the database in this way, * read the database configuration and configure it to the access rules of shiroFilterFactoryBean. In actual projects, use your own Service to process business logic. ** @ Param myShiroCasRealm * @ param stuService * @ param scoreDao * @ return * @ author SHANHY * @ create January 14, 2016 */@ Bean (name = "shiroFilter ") public Response handler (defawebwebsecuritymanager securityManager, CasFilter casFilter, StudentService stuService, IScoreDao scoreDao) {ShiroFilterFactoryBean response = new response (); // you must set SecurityManager ShiroFilterFactoryBean. setSecurityManager (securityManager); // if this parameter is not set, the system automatically searches for "/login. jsp "Page shiroFilterFactoryBean. setLoginUrl (loginUrl); // The Connection shiroFilterFactoryBean to be redirected after successful logon. setSuccessUrl ("/user"); shiroFilterFactoryBean. setUnauthorizedUrl ("/403"); // Add casFilter to shiroFilter Map
Filters = new HashMap <> (); filters. put ("casFilter", casFilter); shiroFilterFactoryBean. setFilters (filters); loadShiroFilterChain (shiroFilterFactoryBean, stuService, scoreDao); return shiroFilterFactoryBean ;}}
Create MyShiroCasRealm. java for permission Authentication
Package org. springboot. sample. security; import java. util. list; import javax. annotation. postConstruct; import org. apache. shiro. authz. authorizationInfo; import org. apache. shiro. authz. simpleAuthorizationInfo; import org. apache. shiro. cas. casRealm; import org. apache. shiro. subject. principalCollection; import org. slf4j. logger; import org. slf4j. loggerFactory; import org. springboot. sample. config. shiroCasConfiguratio N; import org. springboot. sample. dao. IUserDao; import org. springboot. sample. entity. role; import org. springboot. sample. entity. user; import org. springframework. beans. factory. annotation. autowired; import org. springframework. stereotype. service; import org. springframework. transaction. annotation. transactional; @ Service ("myShiroCasRealm") @ Transactionalpublic class MyShiroCasRealm extends CasRealm {private static Final Logger logger = LoggerFactory. getLogger (MyShiroCasRealm. class); @ Autowired private IUserDao userDao; @ PostConstruct public void initProperty () {// setDefaultRoles ("ROLE_USER"); setCasServerUrlPrefix (ShiroCasConfiguration. casServerUrlPrefix); // The client callback address setCasService (ShiroCasConfiguration. shiroServerUrlPrefix + ShiroCasConfiguration. casFilterUrlPattern);}/*** permission authentication, which grants the role and permission for the Subject currently logged on * @ s Ee tested: In this example, the call time of this method is * @ see tested when resources need to be authorized to be accessed: and the logic of this method is executed every time resources need to be authorized are accessed, this indicates that AuthorizationCache * @ see is not enabled by default in this example. tested: if the same URL (such as refresh) is accessed consecutively, this method will not be called repeatedly, shiro has a time interval (that is, cache time, configured in ehcache-shiro.xml) that refresh the page beyond this time interval, this method will be executed */@ Override protected AuthorizationInfo doGetAuthorizationInfo (PrincipalCollection principalCollection) {logger.info ("################# perform Shiro permission authentication ############## ####"); // obtain the username entered for the current logon, which is equivalent to (Strin G) principalCollection. fromRealm (getName ()). iterator (). next (); String loginName = (String) super. getAvailablePrincipal (principalCollection); // check whether the object User user = userDao exists in the database. findByName (loginName); // in the actual project, cache can be performed based on the actual situation. If not, Shiro also has a time interval mechanism, if (user! = Null) {// permission information object info, used to store all roles and permission of the user to be identified SimpleAuthorizationInfo = new SimpleAuthorizationInfo (); // user role set info. setRoles (user. getRolesName (); // all permissions corresponding to the user's role. If you only use the role to define the access permissions, the following four rows can not be List
RoleList = user. getRoleList (); for (Role role: roleList) {info. addStringPermissions (role. getPermissionsName ();} // or follow the steps below to add a role. Instead of adding a role in the configuration sense, it proves that the user has the admin role // simpleAuthorInfo. addRole ("admin"); // Add permissions // simpleAuthorInfo. addStringPermission ("admin: manage"); // logger.info ("[mike] has been granted the [admin] role and [admin: manage] Permission"); return info ;} // If null is returned, any user's access request blocked will automatically jump to the address specified by unauthorizedUrl return null ;}}
Add a method to the Controller to simplify the logon URL and provide a redirection function.
@RequestMapping(value="/login",method=RequestMethod.GET) public String loginForm(Model model){ model.addAttribute("user", new User());// return "login"; return "redirect:" + ShiroCasConfiguration.loginUrl; }
This article mainly introduces how to integrate Shiro + Cas in Spring Boot. It is not an introduction from scratch Project Creation to overall completion.
Two major Java classes are posted above, and all other code of the entire project is not coupled with Shiro and Cas. If you need jsp page, Controller, entity class, Connection database test data and other code, you can first refer to the article: http://www.bkjia.com/kf/201601/485933.html (it is recommended to read this article and then look at this article)