Shiro - SprinBoot 整合

目录

 

一、官网

二、Shiro 功能说明

主要有三大功能模块:

细分功能:

三、官方 Shiro 与 Spring功能整合

Web Applications

Enabling Shiro Annotations

Annotations and Web Applications

Caching

Configuration Properties


一、官网

 官网地址 https://shiro.apache.org/

<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-spring -->
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring</artifactId>
    <version>1.7.0</version>
</dependency>

二、Shiro 功能说明

主要有三大功能模块:

  1. Subject:主体,一般指用户。
  2. SecurityManager:安全管理器,管理所有Subject,可以配合内部安全组件。(类似于SpringMVC中的DispatcherServlet)
  3. Realms:用于进行权限信息的验证,一般需要自己实现。

细分功能:

  1.  Authentication:身份认证/登录(账号密码验证)。
  2.  Authorization:授权,即角色或者权限验证。
  3.  Session Manager:会话管理,用户登录后的session相关管理。
  4.  Cryptography:加密,密码加密等。
  5.  Web Support:Web支持,集成Web环境。
  6.  Caching:缓存,用户信息、角色、权限等缓存到如redis等缓存中。
  7.  Concurrency:多线程并发验证,在一个线程中开启另一个线程,可以把权限自动传播过去。
  8.  Testing:测试支持;
  9. Run As:允许一个用户假装为另一个用户(如果他们允许)的身份进行访问。
  10. Remember Me:记住我,登录后,下次再来的话不用登录了。

三、官方 Shiro 与 Spring功能整合 

官网地址 https://shiro.apache.org/spring-framework.html

Include the Shiro Spring dependency in you application classpath (we recomend using a tool such as Apache Maven or Gradle to manage this)

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring</artifactId>
    <version>1.7.0</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${spring.version}</version>
</dependency>

Import the Shiro Spring configurations:

@Configuration
@Import({ShiroBeanConfiguration.class,
         ShiroConfiguration.class,
         ShiroAnnotationProcessorConfiguration.class})
public class CliAppConfig {
   ...
}

The above configurations do the following:

Configuration ClassDescription
org.apache.shiro.spring.config.ShiroBeanConfigurationConfigures Shiro’s lifecycle and events
org.apache.shiro.spring.config.ShiroConfigurationConfigures Shiro Beans (SecurityManager, SessionManager, etc)
org.apache.shiro.spring.config.ShiroAnnotationProcessorConfigurationEnables Shiro’s annotation processing

The only thing that is left is to configure a realm:

@Bean
public Realm realm() {
  ...
}

The easiest way to setup Shiro, so that all SecurityUtils.* methods work in all cases, is to make the SecurityManager bean a static singleton. DO NOT do this in web applications - see the Web Applications section below instead.

@Autowired
private SecurityManager securityManager;
    
 @PostConstruct
 private void initStaticSecurityManager() {
     SecurityUtils.setSecurityManager(securityManager);
 }

That is it, now you can get the current Subject using:

SecurityUtils.getSubject();

You can see a full example in our samples on Github.

Web Applications

Shiro has first-class support for Spring web applications. In a web application, all Shiro-accessible web requests must go through a master Shiro Filter. This filter itself is extremely powerful, allowing for ad-hoc custom filter chains to be executed based on any URL path expression.

Include the Shiro Spring web dependencies in you application classpath (we recomend using a tool such as Apache Maven or Gradle to manage this)

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring</artifactId>
    <version>1.7.0</version>
</dependency>
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-web</artifactId>
    <version>1.7.0</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${spring.version}</version>
</dependency>

Import the Shiro Spring configurations:

@Configuration
@Import({ShiroBeanConfiguration.class,
        ShiroAnnotationProcessorConfiguration.class,
        ShiroWebConfiguration.class,
        ShiroWebFilterConfiguration.class,
        ShiroRequestMappingConfig.class})
public class ApplicationConfig {
  ...
}

The above configurations do the following:

Configuration ClassDescription
org.apache.shiro.spring.config.ShiroBeanConfigurationConfigures Shiro’s lifecycle and events
org.apache.shiro.spring.config.ShiroAnnotationProcessorConfigurationEnables Shiro’s annotation processing
org.apache.shiro.spring.web.config.ShiroWebConfigurationConfigures Shiro Beans for web usage (SecurityManager, SessionManager, etc)
org.apache.shiro.spring.web.config.ShiroWebFilterConfigurationConfigures Shiro’s web filter
org.apache.shiro.spring.web.config.ShiroRequestMappingConfigConfigures Spring with Shiro’s UrlPathHelper implementation to ensure URLs are processed the same both frameworks

Provide a Realm implementation:

@Bean
public Realm realm() {
  ...
}

And finally a ShiroFilterChainDefinition which will map any application specific paths to a given filter, in order to allow different paths different levels of access.

@Bean
public ShiroFilterChainDefinition shiroFilterChainDefinition() {
    DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
    
    // logged in users with the 'admin' role
    chainDefinition.addPathDefinition("/admin/**", "authc, roles[admin]");
    
    // logged in users with the 'document:read' permission
    chainDefinition.addPathDefinition("/docs/**", "authc, perms[document:read]");
    
    // all other paths require a logged in user
    chainDefinition.addPathDefinition("/**", "authc");
    return chainDefinition;
}

If you are using Shiro’s annotations see the annotation section below.

You can see a full example in our samples on Github.

Enabling Shiro Annotations

In both standalone and web applications, you might want to use Shiro’s Annotations for security checks (for example, @RequiresRoles@RequiresPermissions, etc.) These annotations are enabled by importing the ShiroAnnotationProcessorConfiguration Spring configuration in both sections above.

Simply annotate your methods in order to use them:

@RequiresPermissions("document:read")
public void readDocument() {
    ...
}

Annotations and Web Applications

Shiro annotations are fully supported for use in @Controller classes, for example:

@Controller
public class AccountInfoController {

    @RequiresRoles("admin")
    @RequestMapping("/admin/config")
    public String adminConfig(Model model) {
        return "view";
    }
}

ShiroFilterChainDefinition bean with at least one definition is still required for this to work, either configure all paths to be accessable via the anon filter or a filter in ‘permissive’ mode, for example: authcBasic[permissive].

@Bean
public ShiroFilterChainDefinition shiroFilterChainDefinition() {
    DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
    chainDefinition.addPathDefinition("/**", "anon"); // all paths are managed via annotations
    
    // or allow basic authentication, but NOT require it.
    // chainDefinition.addPathDefinition("/**", "authcBasic[permissive]"); 
    return chainDefinition;
}

Caching

Enabling caching is as simple as providing a CacheManager bean:

@Bean
protected CacheManager cacheManager() {
    return new MemoryConstrainedCacheManager();
}

Configuration Properties

KeyDefault ValueDescription
shiro.sessionManager.deleteInvalidSessionstrueRemove invalid session from session storage
shiro.sessionManager.sessionIdCookieEnabledtrueEnable session ID to cookie, for session tracking
shiro.sessionManager.sessionIdUrlRewritingEnabledtrueEnable session URL rewriting support
shiro.userNativeSessionManagerfalseIf enabled Shiro will manage the HTTP sessions instead of the container
shiro.sessionManager.cookie.nameJSESSIONIDSession cookie name
shiro.sessionManager.cookie.maxAge-1Session cookie max age
shiro.sessionManager.cookie.domainnullSession cookie domain
shiro.sessionManager.cookie.pathnullSession cookie path
shiro.sessionManager.cookie.securefalseSession cookie secure flag
shiro.rememberMeManager.cookie.namerememberMeRememberMe cookie name
shiro.rememberMeManager.cookie.maxAgeone yearRememberMe cookie max age
shiro.rememberMeManager.cookie.domainnullRememberMe cookie domain
shiro.rememberMeManager.cookie.pathnullRememberMe cookie path
shiro.rememberMeManager.cookie.securefalseRememberMe cookie secure flag
shiro.loginUrl/login.jspLogin URL used when unauthenticated users are redirected to login page
shiro.successUrl/Default landing page after a user logs in (if alternative cannot be found in the current session)
shiro.unauthorizedUrlnullPage to redirect user to if they are unauthorized (403 page)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值