zoukankan      html  css  js  c++  java
  • Spring Boot:整合Shiro

    Spring Boot如何和Shiro进行整合:

    先自定义一个Realm继承AuthorizingRealm,并实现其中的两个方法,分别对应认证doGetAuthenticationInfo和授权doGetAuthorizationInfo。

    创建一个ShiroConfig的类,加上@Configuration的注解,这个类就相当于一个shiro的配置文件,可以被spring读取。在ShiroConfig中创建一个方法,此方法的返回值为ShiroFilterFactoryBean,加上@Bean注解,这就就类似在xml文件中添加一个Bean一样,可以被spring管理。ShiroFilterFactoryBean依赖DefaultWebSecurityManager,需要在创建一个DefaultWebSecurityManager的Bean,创建方法和上面类似。DefaultWebSecurityManager依赖Realm,需要创建刚才定义的Realm的Bean。

     下面是要继续完善ShiroFilterFactoryBean,设置ShiroFilterFactoryBean的一些属性,如下图:

     

    filterChainDefinitionMap可以过滤哪些url需要某些角色或者权限才能访问。

    loginUrl可以设置登陆的url,可以在创建一个登陆的Controller,为"/login",处理get请求,返回一个login.fil或者login.html的视图,视图中登陆的表单数据被提交到loginurl后,会自动被shiro拦截并调用Realm中的认证和授权方法(注意必须是post请求),这个两个方法走完之后,会回到controller,即用于处理post请求的对应的"/login"。网上很多教程中会另外在写一个controller接收登陆是提交表单的数据,然后调用subject.login方法,这个其实是没有必要的,接受post请求的controller并不用手动处理登陆逻辑,shiro的过滤器已经处理。

    successUrl登陆成功后跳转的url

    这样ShiroFilterFactoryBean就算基本配置好了,后面可以根据业务需求继续完善。

    然后就是Realm中两个方法的说明:

    doGetAuthenticationInfo方法用于认证,返回AuthenticationInfo,这个接口的实现类是SimpleAuthenticationInfo,构造函数中有四个参数SimpleAuthenticationInfo(Object principal, Object hashedCredentials, ByteSource credentialsSalt, String realmName)。这四个参数的作用分别为:

    • principal: the 'primary' principal associated with the specified realm.
    • hashedCredentials: the hashed credentials that verify the given principal.
    • credentialsSalt: the salt used when hashing the given hashedCredentials
    • realmName: the realm from where the principal and credentials were acquired.

    登陆的流程:用户访问需要登录的资源,会跳转到登陆页面,即get /login,用户提交账户密码后,会被shiro拦截,在Realm的doGetAuthenticationInfo中接收到表单提交的参数,这个方法的参数是AuthenticationToken,这是一个接口,子接口是RememberMeAuthenticationToken HostAuthenticationToken,实现类是UsernamePasswordToken ,这里面可以接受表单提交的登陆账号和密码。

    doGetAuthorizationInfo方法用于授权,返回AuthorizationInfo,这个接口的一个实现类是SimpleAuthorizationInfo,这个类中有三个属性 角色Set<String> roles 权限Set<String> stringPermissions 权限Set<Permission> objectPermissions。接受参数是 PrincipalCollection principalCollection,其中principalCollection.getPrimaryPrincipal()的返回值是SimpleAuthenticationInfo中的第一个参数Oject principal。

     END

  • 相关阅读:
    c# list排序的三种实现方式 (转帖)
    LINQ TO SQL 中的join(转帖)
    Linq to sql 增删改查(转帖)
    DBLinq (MySQL exactly) Linq To MySql
    github
    eclipse安装github插件egit
    Android中图片的目录
    Fragment
    世界500强榜单出炉:中国公司首进三强 沃尔玛居首
    经济学,不会挣钱,更不会赚钱
  • 原文地址:https://www.cnblogs.com/colin220/p/10389500.html
Copyright © 2011-2022 走看看