shiro和spring security 都是安全框架,都可以授权认证。
对比来讲spring security自定义能力更强点,shiro单纯配置来说更复杂点.
不过我技术不精,还是使用我更熟悉的shiro来进行授权认证功能的实现
下图是shiro的3层构造,而我们写也是根据这三层构造来写的,用户->安全事务管理器->realm对象
1.依赖shiro包
还是在pom文件写入
<!--shiro整合spring-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-starter</artifactId>
<version>1.5.1</version>
</dependency>
2.创建config文件和Realm文件
config文件:
@Configuration
public class ShiroConfig {
//shiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager){
ShiroFilterFactoryBean bean=new ShiroFilterFactoryBean();
//关联SecurityManager
bean.setSecurityManager(securityManager);
return bean;
}
//DefaultwebSecurityManager 配置核心安全事务管理器
@Bean(name="securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("myRealm") MyRealm myRealm){
DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
//关联Realm
securityManager.setRealm(myRealm);
return securityManager;
}
//创建realm对象(需要自定义)
@Bean
public MyRealm myRealm(@Qualifier("credentialsMatcher") HashedCredentialsMatcher credentialsMatcher){
MyRealm myRealm=new MyRealm();
myRealm.setCredentialsMatcher(credentialsMatcher);
return myRealm;
}
//以上三层是shiro的三层结构
//下面是附加的
// 配置密码比较器(密码加密)
@Bean(name="credentialsMatcher")
public HashedCredentialsMatcher credentialsMatcher() {
//RetryLimitHashedCredentialsMatcher为另外类的构造函数
HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
credentialsMatcher.setHashAlgorithmName("md5");//散列算法:这里使用MD5算法;
credentialsMatcher.setHashIterations(0);//散列的次数,比如散列两次,相当于 md5(md5(""));
return credentialsMatcher;
}
}
Realm文件:
public class MyRealm extends AuthorizingRealm {
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行授权!!!!!");
return null;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("执行认证!!!!!");
return null;
}
}
3.完善config文件
config文件:
我们还可以在shiroFilterFactoryBean那一层加配置设置很多东西
//shiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager){
ShiroFilterFactoryBean bean=new ShiroFilterFactoryBean();
//关联SecurityManager 配置核心安全事务管理器
bean.setSecurityManager(securityManager);
//配置登录的URL(未登录的用户访问的页面)
//bean.setLoginUrl("/auth/login");