Shiro中loginUrl与unauthorizedUrl

    项目中有用到Shiro框架,但是只使用了身份认证,即登录功能,未用到授权 权限验证功能,在使用的时候对loginUrl和unauthorizedUrl没有区分太清,一直以为unauthorizedUrl是被拦截后要跳转到的页面,今天特意查了一下,才清楚loginUrl是登录页面,unauthorizedUrl是没有资源权限时跳转到的页面。即:

    loginUrl:没有登录的用户请求需要登录的页面时自动跳转到登录页面。 

    unauthorizedUrl:没有权限默认跳转的页面,登录的用户访问了没有被授权的资源自动跳转到的页面。

其他的一些配置,如下:   

    successUrl:登录成功默认跳转页面,不配置则跳转至”/”,可以不配置,直接通过代码进行处理。

    securityManager:这个属性是必须的,配置为securityManager就好了。

    filterChainDefinitions:配置过滤规则,从上到下的顺序匹配。

    在SpringBoot中通过Java代码来实现Shiro的配置。

示例:

package com.config;


import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by
 * Description
 */
@Configuration
public class ShiroConfiguration {

   

    @Bean
    public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {

        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        //拦截器.
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
        //登录界面        
        shiroFilterFactoryBean.setLoginUrl("/index.do");
        //未授权界面
        shiroFilterFactoryBean.setUnauthorizedUrl("/index");
      
        // 配置不会被拦截的链接 顺序判断
        filterChainDefinitionMap.put("/static/**", "anon");       
        filterChainDefinitionMap.put("/public/**", "anon"); 
        。。。。       
        filterChainDefinitionMap.put("/logout", "logout");
        filterChainDefinitionMap.put("/**", "authc");

        // 登录成功后要跳转的链接
        shiroFilterFactoryBean.setSuccessUrl("/main.do");
        
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }

    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
       
        securityManager.setRealm(myShiroRealm());
        securityManager.setSessionManager(sessionManager());
      
        return securityManager;
    }

    @Bean
    public UserAuthenticationRealm myShiroRealm() {
        //UserAuthenticationRealmo为认证和授权具体实现类
        UserAuthenticationRealm myShiroRealm = new UserAuthenticationRealm();
        return myShiroRealm;
    }

    

    @Bean
    public SessionManager sessionManager() {
        DefaultWebSessionManager manager = new DefaultWebSessionManager();
        manager.setCacheManager(new MemoryConstrainedCacheManager());// 加入缓存管理器
        manager.setSessionDAO(sessionDao());// 设置SessionDao
        manager.setDeleteInvalidSessions(true);// 删除过期的session
        manager.setGlobalSessionTimeout(sessionTimeOut);// 设置全局session超时时间
        manager.setSessionValidationSchedulerEnabled(true);// 是否定时检查session、
        manager.setSessionIdCookieEnabled(true);
        manager.setSessionIdCookie(simpleCookie());
        return manager;
    }

    @Bean
    public CustomerSessionDao sessionDao() {
        CustomerSessionDao sessionDao = new CustomerSessionDao(redisSessionRepository());
        return sessionDao;
    }
    @Bean
    public RedisSessionRepository redisSessionRepository() {
        RedisSessionRepository shiroSessionRepository = new RedisSessionRepository();
        return shiroSessionRepository;
    }

    @Bean
    public SimpleCookie simpleCookie() {
        SimpleCookie simpleCookie = new SimpleCookie(sessionName);
        simpleCookie.setPath("/");
        simpleCookie.setHttpOnly(true);
        return simpleCookie;
    }
}

其中UserAuthenticationRealm为认证和授权具体实现类, 需要继承AuthorizingRealm,并实现其doGetAuthenticationInfo和doGetAuthorizationInfo两个方法,doGetAuthenticationInfo为登录认证方法, doGetAuthorizationInfo为授权认证方法。

public class UserAuthenticationRealm extends AuthorizingRealm {

    private Logger logger = LoggerFactory.getLogger(UserAuthenticationRealm.class);

    @Resource
    private IUserAuthenticationService userAuthenticationService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //具体实现, 若不使用授权管理,可以返回null
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        logger.info("用户登录验证开始");
        //具体实现        
        return simpleAuthenticationInfo;
       
}
  • 11
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Boot与Shiro的结合可以实现灵活可扩展的权限管理系统。以下是一些可能的设计和实现方案: 1. 集成Shiro 首先,需要在pom.xml文件添加Shiro的依赖: ``` <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.4.2</version> </dependency> ``` 然后,需要在Spring Boot应用程序的配置文件添加Shiro的配置信息: ``` shiro: filterChainDefinitions: /login = anon /logout = logout /** = authc securityManager: loginUrl: /login successUrl: /home unauthorizedUrl: /unauthorized realms: - name: myRealm authenticationCacheName: authenticationCache authorizationCacheName: authorizationCache ``` 在这个配置,filterChainDefinitions指定了URL的访问规则,securityManager指定了登录、成功和未授权的URL,realms指定了数据源。 2. 定义Realm 定义Realm来实现Shiro的认证和授权功能。Realm是Shiro的核心组件之一,它是一个安全数据源,用于验证用户的身份和授权用户的访问权限。可以通过实现Realm接口来定义自己的Realm,也可以使用Shiro提供的现有的Realm实现。 自定义Realm需要实现doGetAuthenticationInfo和doGetAuthorizationInfo两个方法,分别用于身份验证和授权。 3. 集成Spring Security 另一种方案是使用Spring Security来实现权限管理。Spring Security是Spring框架的一个安全框架,它提供了身份验证、授权和其他安全功能。 集成Spring Security需要在pom.xml文件添加Spring Security的依赖: ``` <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>5.5.0</version> </dependency> ``` 然后,需要在应用程序的配置文件添加Spring Security的配置信息: ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private DataSource dataSource; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasRole("USER") .antMatchers("/login/**").permitAll() .and().formLogin(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.jdbcAuthentication().dataSource(dataSource) .usersByUsernameQuery("select username, password, enabled from users where username=?") .authoritiesByUsernameQuery("select username, authority from authorities where username=?"); } } ``` 在这个配置,configure方法用于配置HttpSecurity,authorizeRequests方法用于定义URL的访问规则,formLogin方法用于指定登录页面。configure方法用于配置AuthenticationManagerBuilder,jdbcAuthentication方法用于指定数据源和查询用户信息和角色信息的SQL语句。 总之,Spring Boot与Shiro或Spring Security的集成可以实现灵活可扩展的权限管理系统,可以根据具体业务需求选择适合的方案。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值