ityouknow / blog-comments

15 stars 0 forks source link

springboot(十四):springboot整合shiro-登录认证和权限管理 - ityouknow's Blog #78

Open ityouknow opened 6 years ago

ityouknow commented 6 years ago

http://www.ityouknow.com/springboot/2017/06/26/springboot-shiro.html

这篇文章我们来学习如何使用Spring Boot集成Apache Shiro。安全应该是互联网公司的一道生命线,几乎任何的公司都会涉及到这方面的需求。在Java领域一般有Spring Security、Apache Shiro等安全框架,但是由于Spring Security过于庞大和复杂,大多数公司会选择Apa...

SaErNuoSi commented 6 years ago

有木有 shiro配置超时时间的。。。

JIAN-JUN-MENG commented 6 years ago

大神有点不理解啊 没有看到shiro怎么获取用户名和密码的 为什么这样就能获取用户名(String)token.getPrincipal();

topruning commented 6 years ago

salt=username+salt 初始的盐怎么得到的呢?就是8d78869f470951332959580424d4bf4f 这个值是怎么计算出来的呢?

jiubanmoli commented 6 years ago

博主有springboot整合security的案例嘛?能否麻烦博主发到623090787@qq.com邮箱一下,或者在你主页发布一下案例,一直在关注博主呢,谢谢了

wangyequn commented 6 years ago

在茫茫的网络世界中,突来就看到了你这篇博客,解决了我的问题,排除了我的疑惑,深入浅出,非常的细致,真诚的感谢你!

lanbingxing commented 6 years ago

MyShiroRealm 这个是哪个包下的

liugao206 commented 6 years ago

运行了一下,能帮忙看下吗

16:52:46.977 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : [] 16:52:46.979 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Excluded patterns for restart : [/spring-boot-starter/target/classes/, /spring-boot-autoconfigure/target/classes/, /spring-boot-starter-[\w-]+/, /spring-boot/target/classes/, /spring-boot-actuator/target/classes/, /spring-boot-devtools/target/classes/] 16:52:46.980 [main] DEBUG org.springframework.boot.devtools.restart.ChangeableUrls - Matching URLs for reloading : [file:/E:/eclipse-workspace/spring-boot-shiro/target/classes/]

. _ _ /\ / '_ () \ \ \ \ ( ( )\ | ' | '| | ' \/ ` | \ \ \ \ \/ _)| |)| | | | | || (| | ) ) ) ) ' |__| .|| ||| |\, | / / / / =========|_|==============|__/=//// :: Spring Boot :: (v1.5.4.RELEASE)

2018-03-06 16:52:47.417 INFO 7956 --- [ restartedMain] com.neo.SpringBootShiroApplication : Starting SpringBootShiroApplication on denglg-PC with PID 7956 (E:\eclipse-workspace\spring-boot-shiro\target\classes started by denglg in E:\eclipse-workspace\spring-boot-shiro) 2018-03-06 16:52:47.418 INFO 7956 --- [ restartedMain] com.neo.SpringBootShiroApplication : No active profile set, falling back to default profiles: default 2018-03-06 16:52:47.715 INFO 7956 --- [ restartedMain] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1c52c12: startup date [Tue Mar 06 16:52:47 CST 2018]; root of context hierarchy 2018-03-06 16:52:49.283 INFO 7956 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$10ae9d25] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2018-03-06 16:52:49.326 INFO 7956 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'shiroConfig' of type [com.neo.config.ShiroConfig$$EnhancerBySpringCGLIB$$aee372b4] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2018-03-06 16:52:50.295 INFO 7956 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'hashedCredentialsMatcher' of type [org.apache.shiro.authc.credential.HashedCredentialsMatcher] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2018-03-06 16:52:50.339 INFO 7956 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean '(inner bean)#6374ae' of type [org.springframework.beans.factory.config.PropertiesFactoryBean] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2018-03-06 16:52:50.339 INFO 7956 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean '(inner bean)#6374ae' of type [java.util.Properties] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2018-03-06 16:52:50.343 INFO 7956 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean '(inner bean)#1494ccf' of type [org.springframework.data.repository.core.support.PropertiesBasedNamedQueries] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2018-03-06 16:52:50.348 INFO 7956 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean '(inner bean)#19e9756' of type [org.springframework.data.repository.query.ExtensionAwareEvaluationContextProvider] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2018-03-06 16:52:50.351 WARN 7956 --- [ restartedMain] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shirFilter' defined in class path resource [com/neo/config/ShiroConfig.class]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'authorizationAttributeSourceAdvisor' defined in class path resource [com/neo/config/ShiroConfig.class]: Unsatisfied dependency expressed through method 'authorizationAttributeSourceAdvisor' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityManager' defined in class path resource [com/neo/config/ShiroConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.shiro.mgt.SecurityManager]: Factory method 'securityManager' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myShiroRealm': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userInfoServiceImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userInfoDao': Cannot create inner bean '(inner bean)#12bbde0' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#12bbde0': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available 2018-03-06 16:52:50.356 ERROR 7956 --- [ restartedMain] o.s.b.f.s.DefaultListableBeanFactory : Destroy method on bean with name 'org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor' threw an exception

java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1c52c12: startup date [Tue Mar 06 16:52:47 CST 2018]; root of context hierarchy at org.springframework.context.support.AbstractApplicationContext.getApplicationEventMulticaster(AbstractApplicationContext.java:414) [spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE] at org.springframework.context.support.ApplicationListenerDetector.postProcessBeforeDestruction(ApplicationListenerDetector.java:97) ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE] at org.springframework.beans.factory.support.DisposableBeanAdapter.destroy(DisposableBeanAdapter.java:253) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroyBean(DefaultSingletonBeanRegistry.java:578) [spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingleton(DefaultSingletonBeanRegistry.java:554) [spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingleton(DefaultListableBeanFactory.java:961) [spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingletons(DefaultSingletonBeanRegistry.java:523) [spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingletons(DefaultListableBeanFactory.java:968) [spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at org.springframework.context.support.AbstractApplicationContext.destroyBeans(AbstractApplicationContext.java:1030) [spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:556) [spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE] at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at com.neo.SpringBootShiroApplication.main(SpringBootShiroApplication.java:10) [classes/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_144] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_144] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_144] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_144] at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-1.5.4.RELEASE.jar:1.5.4.RELEASE]

2018-03-06 16:52:50.361 ERROR 7956 --- [ restartedMain] o.s.b.f.s.DefaultListableBeanFactory : Destroy method on bean with name 'org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory' threw an exception

java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1c52c12: startup date [Tue Mar 06 16:52:47 CST 2018]; root of context hierarchy at org.springframework.context.support.AbstractApplicationContext.getApplicationEventMulticaster(AbstractApplicationContext.java:414) [spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE] at org.springframework.context.support.ApplicationListenerDetector.postProcessBeforeDestruction(ApplicationListenerDetector.java:97) ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE] at org.springframework.beans.factory.support.DisposableBeanAdapter.destroy(DisposableBeanAdapter.java:253) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroyBean(DefaultSingletonBeanRegistry.java:578) [spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingleton(DefaultSingletonBeanRegistry.java:554) [spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingleton(DefaultListableBeanFactory.java:961) [spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingletons(DefaultSingletonBeanRegistry.java:523) [spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingletons(DefaultListableBeanFactory.java:968) [spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at org.springframework.context.support.AbstractApplicationContext.destroyBeans(AbstractApplicationContext.java:1030) [spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:556) [spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE] at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at com.neo.SpringBootShiroApplication.main(SpringBootShiroApplication.java:10) [classes/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_144] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_144] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_144] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_144] at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-1.5.4.RELEASE.jar:1.5.4.RELEASE]

2018-03-06 16:52:50.369 INFO 7956 --- [ restartedMain] utoConfigurationReportLoggingInitializer :

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled. 2018-03-06 16:52:50.501 ERROR 7956 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :


APPLICATION FAILED TO START


Description:

Parameter 0 of method authorizationAttributeSourceAdvisor in com.neo.config.ShiroConfig required a bean named 'entityManagerFactory' that could not be found.

Action:

Consider defining a bean named 'entityManagerFactory' in your configuration.

enjoyCoding666 commented 6 years ago

大神,你这里只有插入表的sql,我没有找到创建表的sql。。

wavesZh commented 6 years ago

@firefoxer1992 大神,你这里只有插入表的sql,我没有找到创建表的sql。。

运行程序 会自动建表的

pc-dong commented 6 years ago

博主,我想请教一下你,你有没有用Spring security 开发过项目,我不太能理解你还要网上好多博客说的Spring security过于庞大和复杂?我个人觉得Spring security 在易用性和复杂度上不比Shiro差,而且属于Spring 下的子项目,与Spring 极易集成。Spring security 在spring boot中只需要几个简单的配置就能实现最简单的认证,通过实现几个接口也很容易将完整RBAC模型集成进来,跟进一步应用Spring Security OAuth2 也很容易实现OAuth2协议。

yxqc4396 commented 6 years ago

这个项目有下载下 看懂的没。

Jakeylove commented 6 years ago

为什么在登录前,静态资源也被拦截了,登录页面无法加载CSS和JS啊。。设置filterChainDefinitionMap.put("/static/**", "anon");不管用吗?

Jakeylove commented 6 years ago

设置不拦截链接的时候,发现不能写“ /static/ ”,写成filterChainDefinitionMap.put("/css/", "anon"); filterChainDefinitionMap.put("/img/**", "anon"); 才好使啊。。。

vipcolud commented 6 years ago

可以

sunzhch commented 6 years ago

我改成mybatis之后就不好使了是怎么回事?登录验证还是可以的 但是权限验证doGetAuthorizationInfo 不走 是怎么回事, 有人遇到过这个问题吗?

java-aodeng commented 6 years ago

学完去装逼

baked-pan commented 6 years ago

@JIAN-JUN-MENG 大神有点不理解啊 没有看到shiro怎么获取用户名和密码的 为什么这样就能获取用户名(String)token.getPrincipal();

public Object org.apache.shiro.authc.UsernamePasswordToken.getPrincipal() {
return getUsername(); 
}
baked-pan commented 6 years ago

@topruning salt=username+salt 初始的盐怎么得到的呢?就是8d78869f470951332959580424d4bf4f 这个值是怎么计算出来的呢? INSERT INTOuser_info(uid,username,name,password,salt,state) VALUES ('1', 'admin', '管理员', 'd3c59d25033dbf980d29554025c23a75', '8d78869f470951332959580424d4bf4f', 0); From: spring-boot-examples-master\spring-boot-shiro\src\main\resources\database\import.sql 盐可以自定义字符串

whatalittlebear commented 6 years ago

@lanbingxing MyShiroRealm 这个是哪个包下的

我感觉是自己创建的,需要继承AuthorizingRealm,之后就对上了

ConnerXie commented 6 years ago

博主,我按照你的配置去配置了,但是没有自动生成表请教下是什么原因?

huayedi commented 6 years ago

博主可以写个关于Spring Security文章吗

foolself commented 6 years ago

请教问题,学习中遇到的Bug,是在重写protected AuthenticationInfo doGetAuthenticationInfo()方法中,

两个问题

代码:

        String username = (String) token.getPrincipal();
        System.out.println("username: " + username);
        System.out.println("----> authenticationToken.getCredentials(): ");
        System.out.println(token.getCredentials());
        System.out.println("----------> 1");
        System.out.println(userInfoService);
        UserInfo userInfo = userInfoService.findByUsername(username);
        System.out.println("---------->userInfo=" + userInfo);

控制台部分错误信息

MyShiroRealm.doGetAuthenticationInfo
username: admin
----> authenticationToken.getCredentials(): 
[C@323278df
----------> 1
null
2018-10-05 10:14:22.213  WARN 244 --- [nio-8080-exec-8] o.a.shiro.authc.AbstractAuthenticator    : Authentication failed for token submission [org.apache.shiro.authc.UsernamePasswordToken - admin, rememberMe=false (0:0:0:0:0:0:0:1)].  Possible unexpected error? (Typical or expected login exceptions should extend from AuthenticationException).

java.lang.NullPointerException: null
    at com.foolself.demo.config.MyShiroRealm.doGetAuthenticationInfo(MyShiroRealm.java:55) ~[classes/:na]
foolself commented 6 years ago

看下边好多不知道数据库中密码是怎么来的,在这里替博主解释下。 其实这个密码就是对明密(比如“123456”)做了 hash 算法,有很多途径可以得到一个字符串的 hash 值,这里因为在讲 Shiro 用法,正好 Shiro 也有 hash 的实现,下面代码供参考:

int hashIterations = 2;//加密的次数
Object salt = "admin";//盐值(博主这里的salt是 username+salt(一般是用户名加一个随机字符串), 这里以字符串“admin”为例)
Object credentials = "123456";//密码
String hashAlgorithmName = "MD5";//加密方式
Object simpleHash = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);
System.out.println("加密后的值----->" + simpleHash);

如此就得到以 用户名“admin” 为salt,明密“123456”的 hash 值 simplehash,把输出的simplehash的值写入数据库就OK了。

Blackcatfish commented 6 years ago

大神您这个没有看出来有权限的关系啊 登录直接就是index 而且这个前端没有写action的路径怎么就能找到登录的方法呢?

baochao09 commented 5 years ago

我擦,密码不对,头疼

sunzhch commented 5 years ago

shiroConfig中缺少一段代码,否则权限校验不好使 @Bean @ConditionalOnMissingBean public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){ DefaultAdvisorAutoProxyCreator app=new DefaultAdvisorAutoProxyCreator(); app.setProxyTargetClass(true); return app; }

lizhilungit commented 5 years ago

在login页面 表单提交后 controller并没有看到给令牌赋值的地方 但是在Realm中就直接获取到了 问一下博主 是不是shiro的过滤器可以自动获取表单提交的name值分别是 username和password这两个的表单元素值呢?

zengfanlin commented 5 years ago

角色和权限不写死在shirFilter里面要怎么办?

yuhangchange commented 5 years ago

出现密码不对是啥情况啊

CrazyroasterDuck commented 5 years ago

@AIWUFAN 出现密码不对是啥情况啊

你看一下你的sql语句有没有执行,没有的话,你直接将数据插入数据库

CuteCodevx commented 5 years ago

@AIWUFAN 出现密码不对是啥情况啊

我也遇到了 请问你解决了吗

@CrazyroasterDuck

@AIWUFAN 出现密码不对是啥情况啊

你看一下你的sql语句有没有执行,没有的话,你直接将数据插入数据库

我直接插的数据进去,登录还是密码不对。。