spring boot using shiro + redis management authority

spring boot in a relatively simple rights management chose to use shiro

Then shiro-redis management session, as follows:

Creating a shiroConfing, which set ShiroFilterFactoryBean ------ SecurityManager ------ myShiroRealm

Then set the cache and the session management securityManager in a manner as defined by the specified sessionManager operated session redis

Then turn shiro AOP annotation support.

Create your own realm inherited AuthorizingRealm do the certification process with landing rights.

code show as below

@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean shirFile(SecurityManager securityManager) {
        log.info("ShiroConfiguration.shirFilter()");
        ShiroFilterFactoryBean ShiroFilterFactoryBean = New ShiroFilterFactoryBean ();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        // interceptor 
        the Map <String, String> = filterChainDefinitionMap new new a LinkedHashMap <String, String> ();
         // custom interceptor 
        the Map <String, the Filter> Filters = new new a LinkedHashMap <String, the Filter> ();
        filters.put("authc", new MyFormAuthenticationFilter());
        shiroFilterFactoryBean.setFilters(filters);

        // Configure link order is not intercepted determined 
        filterChainDefinitionMap.put ( "/ static / **", "anon" ); // disposed exit filter, wherein the specific exit code Shiro has been achieved for us 
        filterChainDefinitionMap.put ( "/ Zimbabwe Logout", "Zimbabwe Logout" );
         // <-! filter chain is defined, the implementation of the order from top to bottom, generally / ** on the most bottom ->: this is a pit of it, accidentally not so that the code;
         // <- authc:! All url must be certified before they can access through; anon: All url can have anonymous access -> 
        filterChainDefinitionMap.put ( "/ **", "authc" );
         // If you do not set a default will automatically find "/login.jsp" page under the Web project root 
        shiroFilterFactoryBean.setLoginUrl ( "/ the Login" );
         // after a successful login to jump to the link 
        shiroFilterFactoryBean.setSuccessUrl("/index");

        // unauthorized interface; 
        shiroFilterFactoryBean.setUnauthorizedUrl ( "/ 403" );
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }

    @Bean
    public MyShiroRealm myShiroRealm(){
        MyShiroRealm myShiroRealm = new MyShiroRealm();
        myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return myShiroRealm;
    }

    /**
     * Certificate matcher
     * (Due to our password check to SimpleAuthenticationInfo Shiro were processed 
     * /
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName ( "MD5"); // hashing algorithm: MD5 algorithm used here; 
        hashedCredentialsMatcher.setHashIterations (2); // number of hash, such as the two hash corresponds md5 (md5 ( "")) ; 
        return hashedCredentialsMatcher;
    }

    @Bean
    public SecurityManager securityManager(){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(myShiroRealm());
        // custom session management using Redis 
        securityManager.setSessionManager (SessionManager ());
         // custom cache implementation uses Redis 
        securityManager.setCacheManager (CacheManager ());
         return securityManager;
    }

    //自定义sessionManager
    @Bean
    public SessionManager sessionManager() {
        SessionConfig mySessionManager = new SessionConfig();
        mySessionManager.setSessionDAO(redisSessionDAO());
        return mySessionManager;
    }

    /**
     * Arrangement shiro redisManager
     * Using open source plug shiro-redis 
     * / 
    public RedisManager redisManager () {
        RedisManager redisManager = new RedisManager();
        redisManager.setHost (Host + ":" + Port);
         // redisManager.setExpire (of 18,000); // configure the cache expiration time 
        redisManager.setTimeout (timeout);
        redisManager.setPassword(password);
        return redisManager;
    }

    /**
     * CacheManager cache to achieve redis
     * Use a shiro-redis open source plug-in 
     * /
    @Bean
    public RedisCacheManager cacheManager() {
        RedisCacheManager redisCacheManager = new RedisCacheManager();
        redisCacheManager.setRedisManager (redisManager ());
        redisCacheManager.setPrincipalIdFieldName("uid");
        return redisCacheManager;
    }

    /**
     * Achieve RedisSessionDAO shiro sessionDao layer by redis
     * <p>
     * Using open source plug-shiro-redis
     */
    @Bean
    public RedisSessionDAO redisSessionDAO() {
        RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
        redisSessionDAO.setRedisManager (redisManager ());
        return redisSessionDAO;
    }

    /**
     * On shiro aop annotation support.
     * Use a proxy way; so it is necessary to open the code support;
     * @param securityManager
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

    @Bean(name="simpleMappingExceptionResolver")
    public SimpleMappingExceptionResolver
    createSimpleMappingExceptionResolver() {
        SimpleMappingExceptionResolver r = new SimpleMappingExceptionResolver();
        Properties mappings = new Properties();
        mappings.setProperty ( "DatabaseException", "DatabaseError"); // database exception handling 
        mappings.setProperty ( "UnauthorizedException", "403" );
        r.setExceptionMappings(mappings);  // None by default
        r.setDefaultErrorView("error");    // No default
        r.setExceptionAttribute("ex");     // Default is "exception"
        return r;
    }
}

 

public  class MyShiroRealm the extends AuthorizingRealm { / ** 
     * login authentication implementation * /
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo (AuthenticationToken token) throws AuthenticationException { // Find by username User object from the database, if found, could not find.
         // actual project, where you can do a cache according to the actual situation, if not, Shiro also have their own time spacing mechanism, not over 2 minutes repeat the process 
        the UserInfo queryInfo = new new the UserInfo ();
        queryInfo.setUsername((String) token.getPrincipal());
     //--------------------------------------------------------
List<SysRole> roleList = new ArrayList<>(); for (UserInfo info : userInfos) { List <SysRole> = tmpRoleList info.getRoleList (); for (SysRole sysRole: tmpRoleList) { sysRole.setPermissions (sysPermissionMapper.selectPermissionByRoleId (sysRole.getId ())); roleList.add(sysRole); } } userInfo.setRoleList(roleList); SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo( userInfo, // username userInfo.getPassword (), // password ByteSource.Util.bytes (userInfo.getCredentialsSalt ()), // here is the password + salt getName()//realm name ); return authenticationInfo; } /** * ASD */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); UserInfo userInfo = (UserInfo) principalCollection.getPrimaryPrincipal(); for (SysRole sysRole : userInfo.getRoleList()) { authorizationInfo.addRole (sysRole.getRole ()); for (SysPermission permission : sysRole.getPermissions()) { authorizationInfo.addStringPermission(permission.getPermission()); } } return authorizationInfo; } }

Log Controller

@Controller
public class LoginController {
@RequestMapping({"/", "/index"}) public String index() { System.out.println("goIndex"); return "user/index"; } @RequestMapping("/403") public String unauthorizedRole() { System.out.println ( "no authority ------ -------" ); return "403" ; } @GetMapping("/login") public String goLoginPage(Model m) { System.out.print("goLogin"); Subject currentUser = SecurityUtils.getSubject(); if(!currentUser.isAuthenticated()){ return "login"; }else{ return "user/index"; } } @PostMapping ( "/ the Login" ) public String the Login (@ModelAttribute UserInfo UserInfo, the HttpServletRequest request, the Map <String, Object> the Map) { // Login failed to obtain an exception request from the information processing shiro in. // . ShiroLoginFailure: full name of the class is the class exception shiro the Subject the currentUser = SecurityUtils.getSubject (); // by isAuthenticated Subject object determines whether the user has verified IF (! CurrentUser.isAuthenticated ()) { // If the user is not authenticated, the user account number and password obtained using UsernamePasswordToken generated in a manner that a user's credentials token UsernamePasswordToken token = new new UsernamePasswordToken ( userinfo.getUsername(), userinfo.getPassword()); // open Remember my function, where you can get the information submitted by the user, and then determines whether Remember me decide to open or close token.setRememberMe ( to true ); String exception = (String) request.getAttribute("shiroLoginFailure"); System.out.println("exception=" + exception); MSG String = "" ; the try { // to verify the user's identity via login Subject object currentUser.login (token); log.info ( "in the Login sessionid:" + .. currentUser.getSession () getId () toString ()); // If the user is not authenticated by the appropriate exception will be thrown, can be set to return by throwing an exception to the information reception } the catch (UnknownAccountException UAE) { log.info ( "no account =============== abnormal =>" + token.getPrincipal ()); msg = "UnknownAccountException -> account does not exist:" ; } catch (IncorrectCredentialsException ice) { log.info ( "Error Exception =============== password =>" + token.getPrincipal ()); msg = "IncorrectCredentialsException -> Incorrect password:" ; } catch (LockedAccountException lae) { log.info ( "the account is locked =============== abnormal =>" + token.getPrincipal ()); MSG = "kaptchaValidateFailed -> Error codes" ; } catch (AuthenticationException ae) { log.info ( "abnormal =============== i.e. authentication fails, the parent class is the first few unusual =>" + token.getPrincipal ()); msg = "else >> " + exception; } map.put("msg", msg); } // This method does not handle the login is successful, be handled by shiro return "the Login" ; } }
The successful landing of the user to jump back index page
/**
 * The successful landing of the user to jump down index
 */
public class MyFormAuthenticationFilter extends FormAuthenticationFilter {
    @Override
    protected  boolean onLoginSuccess (AuthenticationToken token, Subject Subject, ServletRequest Request, the Response ServletResponse) throws Exception {
         IF (! {StringUtils.isEmpty (getSuccessUrl ()))
             // getSession (false): If the current session is null, returns null, and instead of creating a new the session 
            the Session the session = subject.getSession ( false );
             IF (! the session = null ) {
                session.removeAttribute("shiroSavedRequest");
            }
        }
        return  Super .onLoginSuccess (token, Subject, Request, Response);
 //      or following this approach
 //         String successUrl = "/ index";
 //         WebUtils.issueRedirect (Request, Response, successUrl);
 //         the System.out. println ( "Log Home interception");
 //         return false 
    }
}

In Controller with annotation interface access control

@RequiresPermissions("student:add")

Use interceptors information processing returned insufficient permissions

@ControllerAdvice
public class ExceptionHandleController  {
    static final Logger log = LoggerFactory.getLogger(ExceptionHandleController.class);

    @ExceptionHandler(UnauthorizedException.class)
    public void handleShiroException(Exception ex,HttpServletRequest request, HttpServletResponse response) {
        log.info(ex.toString());
        WebUtils.sendJson (Response, to false , "no authority!"); // This method returns json as { "success": true, " msg": " no authority"}
 //         return "the redirect: / error / 403"; 
    }

    @ExceptionHandler(AuthorizationException.class)
    public void AuthorizationException(Exception ex) {
        log.info(ex.toString());
//        return "redirect:/error/401";
    }
}

 

Guess you like

Origin www.cnblogs.com/moerjiana/p/11967515.html