关于spring security安全退出问题 2C

目前实现了security 会话并发控制 仅允许1个用户同时在线(同一账号)
但是后来发现问题 如果用户通过浏览器 主动清除session

那么再次登录就会出现登录不进去的情况
请问 有什么办法解决吗?图片说明

4个回答

第二种方法配置:

    <session-management invalid-session-url="/sessionException?msg=SESSION.INVALID" session-fixation-protection="migrateSession" >
        <!-- 
            配置同一用户多次登录的情况, 需要重写UserDetailsServiceImpl实现类loadUserByUsername方法返回的User重写equals和hashCode, 
            还需要在 web.xml中配置 org.springframework.security.web.session.HttpSessionEventPublisher 监听器

            max-sessions=1  配置同一用户最多可以同时登录多少次,超出后根据 error-if-maximum-exceeded 来处理

            error-if-maximum-exceeded 值为true时,如果一个用户已经登录,然后又进行登录,则无法登陆,
                                          值为false时,如果一个用户已经登录,然后又进行登录,则将踢掉上一个用户。

            expired-url 表示被提出的用户跳转到那个页面
        -->
        <concurrency-control max-sessions="1" error-if-maximum-exceeded="false" expired-url="/sessionException?msg=SESSION.MULTI"/>
    </session-management>

spring security 有两种方法解决 仅允许1个用户同时在线(同一账号)

第一种是 : a 登陆后再进行登陆,服务器拒绝后面登陆的用户。
第二种是 : a 登陆后再进行登陆,服务器会把已登录用户踢掉,让最后登陆的用户登陆。

你这种用第二种比较好

绑定用户登录的IP
出现这个问题的原因:手动消除cookie后与服务端就断开连接了,但是服务端的session还没有失效,这时候使用用户名密码登录时可以从session中
获取到该用户,所以提示用户已登录。

解决方案:将用户的登录IP保存在用户信息中,登录时如果session中已经该用户信息时,在检验用户的登录IP是否一样,如果一样登录成功,否则提示
用户已登录。

可能存在问题,同一个电脑上用另一个浏览器重复登录时也可以登录成功。
优化方案:同时绑定IP和浏览器信息或其它具有唯一性的信息。

qq_19380987
qq_19380987 意思是需要和在线用户的信息逐一比对 那如果在线用户量很大 那岂不是很影响性能
2 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
使用spring security提示Access is denied?
``` org.springframework.security.access.AccessDeniedException: Access is denied at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84) at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:124) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:158) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:526) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1579) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:748) ``` +++++++++++++++++++++++ 配置文件: spring-security.xml ``` <security:global-method-security pre-post-annotations="enabled" jsr250-annotations="enabled" secured-annotations="enabled"></security:global-method-security> <!-- 配置不拦截的资源 --> <security:http pattern="/pages/login.jsp" security="none"/> <security:http pattern="/failer.jsp" security="none"/> <security:http pattern="/css/**" security="none"/> <security:http pattern="/img/**" security="none"/> <security:http pattern="/plugins/**" security="none"/> <security:http auto-config="true" use-expressions="true"> <!-- 配置具体的拦截的规则 pattern="请求路径的规则" access="访问系统的人,必须有ROLE_USER的角色" --> <security:intercept-url pattern="/**" access="hasAnyRole('ROLE_USER','ROLE_ADMIN')"/> <!-- 定义跳转的具体的页面 --> <security:form-login login-page="/pages/login.jsp" login-processing-url="/login" default-target-url="/index.jsp" authentication-failure-url="/failer.jsp" authentication-success-forward-url="/pages/main.jsp" /> <!-- 关闭跨域请求 --> <security:csrf disabled="true"/> <!-- 退出 --> <security:logout invalidate-session="true" logout-url="/logout" logout-success-url="/pages/login.jsp"/> </security:http> <!-- 切换成数据库中的用户名和密码 --> <security:authentication-manager> <security:authentication-provider user-service-ref="userService"> <!-- 配置加密的方式--> <security:password-encoder ref="passwordEncoder"/> </security:authentication-provider> </security:authentication-manager> <!-- 配置加密类 --> <bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/> <security:authentication-manager> <security:authentication-provider> <security:user-service> <security:user name="123" password="{noop}123" authorities="ROLE_USER"/> </security:user-service> </security:authentication-provider> </security:authentication-manager> ``` +++++++++++++++++++++++ web.xml ![图片说明](https://img-ask.csdn.net/upload/201912/29/1577584767_128990.png) +++++++++++++++++++++++ login.jsp ![图片说明](https://img-ask.csdn.net/upload/201912/29/1577584799_61926.png) +++++++++++++++++ 请问大神是怎么回事呢?
Spring Security为什么LogoutHandler获取不到authentication
我想实现用户退出登录的时候进行日志记录(操作数据库中的登出记录表),然后自定义退出登录logout,自己实现了一个LogoutHandler,但LogoutHandler中logout函数的authentication始终获取不到,不知道为什么 ``` @Component public class MyLogoutHandler implements LogoutHandler { String username; @Override public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { System.out.println("进入MyLogoutHandler"); if(authentication != null) { username = SecurityUtils.getUsername(authentication); System.out.println("获得当前登录用户名:"+username); //...操作数据库的代码省略 } else { System.out.println("authentication is null"); return; } } } ``` 下面是WebSecurityConfigurerAdapter中的部分代码 ``` @Override protected void configure(HttpSecurity http) throws Exception { // 禁用 csrf, 由于使用的是JWT,我们这里不需要csrf http.cors().and().csrf().disable() .authorizeRequests() // 跨域预检请求 .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() // web jars .antMatchers("/webjars/**").permitAll() // 查看SQL监控(druid) .antMatchers("/druid/**").permitAll() // 首页和登录页面 .antMatchers("/").permitAll() .antMatchers("/login").permitAll() // swagger .antMatchers("/swagger-ui.html").permitAll() .antMatchers("/doc.html").permitAll() .antMatchers("/swagger-resources/**").permitAll() .antMatchers("/v2/api-docs").permitAll() .antMatchers("/webjars/springfox-swagger-ui/**").permitAll() // 验证码 .antMatchers("/captcha.jpg**").permitAll() // 服务监控 .antMatchers("/actuator/**").permitAll() // 其他所有请求需要身份认证 .anyRequest().authenticated(); http.headers().frameOptions().disable(); // 退出登录处理器 http.logout().logoutUrl("/logout").addLogoutHandler(myLogoutHandler); // token验证过滤器 http.addFilterBefore(new JwtAuthenticationFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class); } ``` 点击登录按钮之后,转跳到/logout 但控制台一直输出authentication is null,后来我又换成了继承LogoutSuccessHandler,依旧是获取不了当前用户authentication,但我在其他非退出登录的操作中获取authentication是正常的 也尝试了添加.antMatchers("/logout").permitAll() 另外我想问一下大家,还有什么比较好的办法在用户退出登录的时候记录日志,最好能做到用户主动点击退出登录和session自动失效都能记录日志
spring-security 配置<security:form-login>不起作用
其他的标签配置都有效就这个标签无效导致了一直无法拿到自己设置的自定义username参数,请问这是什么问题 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:security="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd"> <!-- 设置不拦截的资源url--> <security:http security="none" pattern="/css/**" /> <security:http security="none" pattern="/js/**" /> <security:http security="none" pattern="/images/**" /> <security:http security="none" pattern="/favicon.ico"/> <security:http security="none" pattern="/login*" /> <security:http security="none" pattern="/login/sendSms" /> <security:http security="none" pattern="/captchaServlet"/> <security:http security="none" pattern="/activecode*"/> <security:http security="none" pattern="/sendEmail*"/> <security:http security="none" pattern="/register*" /> <security:http security="none" pattern="/check/**" /> <security:http security="none" pattern="/accessDenied"/> <security:http security="none" pattern="/page/reply"/> <security:http security="none" pattern="/page/pages"/> <security:http auto-config="false" access-decision-manager-ref="accessDecisionManager" use-expressions="true" entry-point-ref="loginEntryPoint"> <!-- 禁用frame-option不禁用会阻止加载任何frame页面,包括图片上传超时--> <security:headers> <security:frame-options disabled="true"></security:frame-options> </security:headers> <!-- 配置登录页信息,分别为登录 URL、认证失败跳转 URL、认证成功跳转 URL、登录 URL、password 和 username 请求参数名称--> <security:form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?error=1" login-processing-url="/login/doLogin" password-parameter="password" default-target-url="/personal/list" username-parameter="email" /> <security:access-denied-handler ref="accessDeniedHandler" /> <!-- 禁用csrf--> <security:csrf disabled="true"/> <security:intercept-url pattern="/" access="permitAll"/> <security:intercept-url pattern="/index**" access="permitAll"/> <security:intercept-url pattern="/login/sendSms" access="permitAll"/> <security:intercept-url pattern="/**" access="hasRole('ROLE_USER')"/> <!-- session失效url session策略--> <security:session-management invalid-session-url="/index.jsp" session-authentication-strategy-ref="sessionStrategy"> </security:session-management> <!-- spring-security提供的过滤器 以及我们自定义的过滤器 authenticationFilter--> <security:custom-filter ref="logoutFilter" position="LOGOUT_FILTER" /> <security:custom-filter before="FORM_LOGIN_FILTER" ref="authenticationFilter"/> <security:custom-filter ref="concurrencyFilter" position="CONCURRENT_SESSION_FILTER"/> </security:http> <bean id="accessDeniedHandler" class="com.dream.sercurity.Account.MyAccessDeniedHandler"> <property name="errorPage" value="/accessDenied.jsp" /> </bean> <bean id="loginEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint"> <!-- 用户未登录访问保护资源后弹到默认登录页的url --> <constructor-arg value="/login.jsp?error=login"/> </bean> <!-- 启用表达式 为了后面的投票器做准备 --> <bean class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler" id="expressionHandler"/> <bean class="org.springframework.security.web.access.expression.WebExpressionVoter" id="expressionVoter"> <property name="expressionHandler" ref="expressionHandler"/> </bean> <!-- 认证管理器,使用自定义的accountService,并对密码采用md5加密 --> <security:authentication-manager alias="authenticationManager"> <security:authentication-provider user-service-ref="accountService"> <security:password-encoder hash="md5"> <security:salt-source user-property="email"></security:salt-source> </security:password-encoder> </security:authentication-provider> </security:authentication-manager> <bean id="authenticationFilter" class="com.dream.sercurity.Account.AccountAuthenticationFilter"> <property name="filterProcessesUrl" value="/login/doLogin"></property> <property name="authenticationManager" ref="authenticationManager"></property> <property name="sessionAuthenticationStrategy" ref="sessionStrategy"></property> <property name="authenticationSuccessHandler"> <bean class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler"> <property name="defaultTargetUrl" value="/personal/list"></property> </bean> </property> <property name="authenticationFailureHandler"> <bean class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"> <property name="defaultFailureUrl" value="/login.jsp?error=fail"></property> </bean> </property> </bean> <bean id="logoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter"> <!-- 处理退出的虚拟url --> <property name="filterProcessesUrl" value="/loginout" /> <!-- 退出处理成功后的默认显示url --> <constructor-arg index="0" value="/login.jsp?logout" /> <constructor-arg index="1"> <!-- 退出成功后的handler列表 --> <array> <bean id="securityContextLogoutHandler" class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler" /> </array> </constructor-arg> </bean> <!-- ConcurrentSessionFilter过滤器配置(主要设置账户session过期路径) --> <bean id="concurrencyFilter" class="org.springframework.security.web.session.ConcurrentSessionFilter"> <constructor-arg ref="sessionRegistry"></constructor-arg> <constructor-arg value="/login?error=expired"></constructor-arg> </bean> <bean id="sessionStrategy" class="org.springframework.security.web.authentication.session.CompositeSessionAuthenticationStrategy"> <constructor-arg> <list> <bean class="org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy"> <property name="maximumSessions" value="1"></property> <property name="exceptionIfMaximumExceeded" value="false"></property> <constructor-arg ref="sessionRegistry"/> </bean> <bean class="org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy"/> <bean class="org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy"> <constructor-arg ref="sessionRegistry"/> </bean> </list> </constructor-arg> </bean> <bean id="sessionRegistry" scope="singleton" class="org.springframework.security.core.session.SessionRegistryImpl"></bean> <bean id="accountService" class="com.dream.sercurity.Account.AccountDetailsService"/> <!-- An access decision voter that reads ROLE_* configuration settings --> <bean id="roleVoter" class="org.springframework.security.access.vote.RoleVoter"/> <bean id="authenticatedVoter" class="org.springframework.security.access.vote.AuthenticatedVoter"/> <bean id="accessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased"> <constructor-arg> <list> <ref bean="roleVoter"/> <ref bean="authenticatedVoter"/> <ref bean="expressionVoter"/> </list> </constructor-arg> </bean> </beans> ``` ```
spring security的多登陆怎么配置?
<?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd"> <http auto-config="true" create-session="always" access-denied-page="/static/common/denied.html" use-expressions="true" disable-url-rewriting="true"> <!-- 配置不要过滤的图片等静态资源,其中**代表可以跨越目录,*不可以跨越目录。 --> <!-- 后面带一个*,因为请求页面的时候可能会带一些参数 --> <intercept-url pattern="/services*" filters="none"/> <intercept-url pattern="/services/*" filters="none"/> <intercept-url pattern="/static/**" filters="none"/> <!-- 不过滤图片等静态资源 --> <intercept-url pattern="/login.jsp*" filters="none"/> <!-- 登录页面不过滤 --> <intercept-url pattern="/index1.jsp*" filters="none"/> <!-- 登录页面不过滤 --> <intercept-url pattern="/front/login" filters="none"/> <!-- 登录页面不过滤 --> <intercept-url pattern="/install.jsp*" filters="none"/> <!-- 系统初始化配置不过滤 --> <intercept-url pattern="/sys/init" filters="none"/> <intercept-url pattern="/front/**" filters="none"/> <intercept-url pattern="/**/*.swf" filters="none" /> <!-- 配置登录页面 --> <!-- <form-login login-page="/front/login.jsp" login-processing-url="/j_spring_security_check" --> <!-- authentication-failure-url="/front/login?error=true" --> <!-- default-target-url="/front/index" --> <!-- always-use-default-target="true" --> <!-- authentication-success-handler-ref="authenticationSuccess" --> <!-- authentication-failure-handler-ref="exceptionMappingAuthenticationFailureHandler"/> --> <form-login login-page="/login.jsp" login-processing-url="/j_spring_security_check" authentication-failure-url="/login.jsp?error=true" default-target-url="/index" always-use-default-target="true" authentication-success-handler-ref="authenticationSuccess" authentication-failure-handler-ref="exceptionMappingAuthenticationFailureHandler"/> <!--"记住我"功能,采用持久化策略(将用户的登录信息存放cookie) --> <remember-me use-secure-cookie="true"/> <!-- 用户退出的跳转页面 --> <logout invalidate-session="true" logout-url="/j_spring_security_logout" logout-success-url="/login.jsp"/> <!-- 会话管理,设置最多登录异常,error-if-maximum-exceeded = false为第二次登录就会使前一个登录失效 --> <session-management invalid-session-url="/login.jsp"> <concurrency-control max-sessions="1" error-if-maximum-exceeded="false" expired-url="/login.jsp?expired=true"/> </session-management> <!--添加自定义的过滤器 放在FILTER_SECURITY_INTERCEPTOR之前有效 --> <custom-filter ref="customFilterSecurityInterceptor" before="FILTER_SECURITY_INTERCEPTOR" /> <anonymous enabled="false" /> </http> <beans:bean id="authenticationSuccess" class="edu.buaa.hsps.system.service.MySavedRequestAwareAuthenticationSuccessHandler"> <beans:property name="defaultTargetUrl" value="/index"/> </beans:bean> <authentication-manager alias="authenticationManager"> <authentication-provider user-service-ref="customUserDetailsService"> <password-encoder hash="md5" base64="true"> <salt-source user-property="username"/> </password-encoder> </authentication-provider> </authentication-manager> <beans:bean id="exceptionMappingAuthenticationFailureHandler" class="org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler"> <beans:property name="exceptionMappings"> <beans:props> <beans:prop key="org.springframework.security.authentication.DisabledException">/login.jsp?role=false</beans:prop> <beans:prop key="org.springframework.security.authentication.BadCredentialsException">/login.jsp?error=true</beans:prop> </beans:props> </beans:property> </beans:bean> </beans:beans> ``` ``` 在这个配置里面要怎么修改,需要一个前台登录,这里只配置了后台
关于sping-security的Access is denied问题
编译时没问题,但是刚进到网页的时候就会报Access is denied,但是却不妨碍登陆,登陆进去查询,添加都能完成,求各位大神指点! **这是一个ssm整合的项目** 日志 ``` org.springframework.security.access.AccessDeniedException: Access is denied at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84) at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:124) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:158) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748) ``` sping-security.xml配置文件 ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:security="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd"> <!-- 配置不拦截的资源 --> <security:http pattern="/login.jsp" security="none"/> <security:http pattern="/failer.jsp" security="none"/> <security:http pattern="/css/**" security="none"/> <security:http pattern="/img/**" security="none"/> <security:http pattern="/plugins/**" security="none"/> <!-- 配置具体的规则 auto-config="true" 不用自己编写登录的页面,框架提供默认登录页面 use-expressions="false" 是否使用SPEL表达式(没学习过) --> <security:http auto-config="true" use-expressions="false"> <!-- 配置具体的拦截的规则 pattern="请求路径的规则" access="访问系统的人,必须有ROLE_USER的角色" --> <security:intercept-url pattern="/**" access="ROLE_USER,ROLE_ADMIN"/> <!-- 定义跳转的具体的页面 --> <security:form-login login-page="/login.jsp" login-processing-url="/login.do" default-target-url="/index.jsp" authentication-failure-url="/failer.jsp" authentication-success-forward-url="/pages/main.jsp" /> <!-- 关闭跨域请求 --> <security:csrf disabled="true"/> <!-- 退出 --> <security:logout invalidate-session="true" logout-url="/logout.do" logout-success-url="/login.jsp" /> </security:http> <!-- 切换成数据库中的用户名和密码 --> <security:authentication-manager> <security:authentication-provider user-service-ref="userService"> <!--配置加密的方式--> <!--<security:password-encoder ref="passwordEncoder"/>--> </security:authentication-provider> </security:authentication-manager> <!-- 配置加密类 --> <bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/> </beans> ``` ``` @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { UserInfo userInfo = null; try { userInfo = userDao.findByUsername(s); } catch (Exception e) { e.printStackTrace(); } //User user = new User(userInfo.getUsername(),"{noop}"+userInfo.getPassword(),getAuthority(userInfo.getRoles())); User user = new User(userInfo.getUsername(),"{noop}"+userInfo.getPassword(),userInfo.getStatus() == 0 ? false : true,true,true,true,getAuthority(userInfo.getRoles())); return user; } public List<SimpleGrantedAuthority> getAuthority(List<Role> roles){ List<SimpleGrantedAuthority> list = new ArrayList<>(); for (Role role:roles){ list.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName())); } return list; } ```
Spring Security 4 : 获取当前登录用户, 有时成功有时失败. 求解
场景描述:<br/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;H5端登录成功以后, 在请求需要用户登录才能访问的接口前, 会调用一个检测是否有用户登录的接口. <br/> 问题描述: <br/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;当第一次H5端登录成功后, 一切是正常的, 访问其他接口也是. &nbsp;但...如果现在退出登录并立马去登录页进行第二次登录的时候, 登录成功了, 去访问需要权限的接口时, 调用检测接口时, 就会出现获取当前用户失败的情况出现!!! <br/> 求各位大佬解惑!!! <br/> 代码情况: <br/> ![图片说明](https://img-ask.csdn.net/upload/201908/26/1566805298_249886.png)
spring security怎么实现浏览器关闭session也关闭 最好详细点 ,谢谢
<!-- max-sessions:允许用户帐号登录的次数。范例限制用户只能登录一次。exception-if-maximum-exceeded:默认为false 此值表示:用户第二次登录时,前一次的登录信息都被清空。当exception-if-maximum-exceeded="true"时系统会拒绝第二次登录--> <session-management> <concurrency-control error-if-maximum-exceeded="true" max-sessions="1" /> </session-management> <!-- invalidate-session:指定在退出系统时是否要销毁Session。logout-success-url:退出系统后转向的URL。logout-url:指定了用于响应退出系统请求的URL。其默认值为:/logout。 --> <logout invalidate-session="true" logout-success-url="/login.jsp" logout-url="/logout" /> 但是直接关闭浏览器,不能销毁session,再登陆这个用户,会提示用户已登陆,只能等session过期, 有没有什么办法可以解决这个问题?
springSecurity如何在配置文件中配置需要放行的
1.虽然注册页面我配置了放行,但是注册页面上的请求全部被springsecurity安全框架拦截了,请问如何在配置文件中配置放行指定的get/post请求吗?以下是配置文件 ``` <!--放行不需要拦截的资源页面--> <security:http pattern="/login.jsp" security="none"></security:http> <security:http pattern="/failer.jsp" security="none"></security:http> <security:http pattern="/403.jsp" security="none"></security:http> <security:http pattern="/register.jsp" security="none"></security:http> <security:http pattern="/sampling.jsp" security="none"></security:http> <!--<security:http pattern="/index.jsp" security="none"></security:http>--> <security:http pattern="/css/**" security="none"></security:http> <security:http pattern="/img/**" security="none"></security:http> <security:http pattern="/pages/**" security="none"></security:http> <security:http pattern="/plugins/**" security="none"></security:http> <!--配置拦截的规则和放行的条件 auto-config 支持默认的配置 use-expression 使用表达式 为false 关闭表达式 intercept-url 拦截的资源规则 access 允许访问的角色条件 --> <security:http auto-config="true" use-expressions="false"> <!--多个角色之间是或者的关系 任意角色即可登录--> <security:intercept-url pattern="/**" access="ROLE_USER,ROLE_TEST"></security:intercept-url> <!-- login-page 自定义登录页面 login-processing-url 登录页面form表单请求的url地址 default-target-url 登录成功目标页面 authentication-failure-url 登录失败的页面 --> <security:form-login login-page="/login.jsp" login-processing-url="/login" default-target-url="/index.jsp" authentication-failure-url="/failer.jsp"></security:form-login> <!--配置登录成功权限不足的处理--> <security:access-denied-handler error-page="/403.jsp"></security:access-denied-handler> <!--关闭跨域请求的拦截--> <security:csrf disabled="true"></security:csrf> <!--配置退出的过滤器 invalidate-session="true" session过期 logout-success-url 退出成功的跳转页 logout-url 页面发起退出请求的路径 --> <security:logout invalidate-session="true" logout-success-url="/login.jsp" logout-url="/logout"></security:logout> </security:http> <!--配置拦截访问的验证--> <security:authentication-manager> <security:authentication-provider user-service-ref="userService"> <!--验证过的业务实现类使用框架的UserDetailService--> <!--初始化固定的账号用于测试 {noop}表示密码验证方式为明文验证 原始密码 123456 密文验证 加密密码 fd34falfacdffa34rfafadfa <security:user name="user" password="{noop}user" authorities="ROLE_USER"></security:user> <security:user name="admin" password="{noop}admin" authorities="ROLE_ADMIN"></security:user> --> <!--选择系统默认的加密方式--> <security:password-encoder hash="bcrypt"></security:password-encoder> </security:authentication-provider> </security:authentication-manager> <!--配置加密工具类的bean对象--> <bean id="pwdEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"></bean> </beans> ```
退出登录,session不知道怎么失效了,获取不到session里面的值?
登录页面我弄了一个验证码,存放到session中,刷新页面第一次登录可以验证, 但是退出登录后,再次登录session里面的值获取不到了,报空指针,为什么?我调试 发现退出登录的时候,session中也存放值了,为什么就是获取不到呢? ``` 09:25:06.144 [5200279@qtp-16921957-13 - /servlet/captchaServlet?method=getJPGCodeServlet] DEBUG org.mortbay.log - RESPONSE /servlet/captchaServlet 200 09:25:10.228 [5200279@qtp-16921957-13] DEBUG org.mortbay.log - EOF 09:25:19.968 [5200279@qtp-16921957-13 - /training_security_check] DEBUG org.mortbay.log - REQUEST /training_security_check on org.mortbay.jetty.HttpConnection@1be372a 09:25:19.968 [5200279@qtp-16921957-13 - /training_security_check] DEBUG org.mortbay.log - Got Session ID 13ke4zpaqcz65188p4bhmhpnre from cookie 09:25:19.968 [5200279@qtp-16921957-13 - /training_security_check] DEBUG org.mortbay.log - sessionManager=org.mortbay.jetty.servlet.HashSessionManager@6c8a0c 09:25:19.968 [5200279@qtp-16921957-13 - /training_security_check] DEBUG org.mortbay.log - session=null 09:25:19.968 [5200279@qtp-16921957-13 - /training_security_check] DEBUG org.mortbay.log - servlet=default 09:25:19.968 [5200279@qtp-16921957-13 - /training_security_check] DEBUG org.mortbay.log - chain=Set Character Encoding->springSecurityFilterChain->default 09:25:19.968 [5200279@qtp-16921957-13 - /training_security_check] DEBUG org.mortbay.log - servlet holder=default 09:25:19.968 [5200279@qtp-16921957-13 - /training_security_check] DEBUG org.mortbay.log - call filter Set Character Encoding 09:25:19.968 [5200279@qtp-16921957-13 - /training_security_check] DEBUG org.mortbay.log - call filter springSecurityFilterChain 09:25:19.968 [5200279@qtp-16921957-13 - /training_security_check] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/training_security_check'; against '/js/**' 09:25:19.969 [5200279@qtp-16921957-13 - /training_security_check] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/training_security_check'; against '/image/**' 09:25:19.969 [5200279@qtp-16921957-13 - /training_security_check] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/training_security_check'; against '/css/**' 09:25:19.969 [5200279@qtp-16921957-13 - /training_security_check] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/training_security_check'; against '/img/**' 09:25:19.969 [5200279@qtp-16921957-13 - /training_security_check] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/training_security_check'; against '/check-**' 09:25:19.969 [5200279@qtp-16921957-13 - /training_security_check] DEBUG o.s.security.web.FilterChainProxy - /training_security_check at position 1 of 5 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter' 09:25:19.969 [5200279@qtp-16921957-13 - /training_security_check] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - No HttpSession currently exists 09:25:19.969 [5200279@qtp-16921957-13 - /training_security_check] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: null. A new one will be created. 09:25:19.969 [5200279@qtp-16921957-13 - /training_security_check] DEBUG o.s.security.web.FilterChainProxy - /training_security_check at position 2 of 5 in additional filter chain; firing Filter: 'LogoutFilter' 09:25:19.969 [5200279@qtp-16921957-13 - /training_security_check] DEBUG o.s.security.web.FilterChainProxy - /training_security_check at position 3 of 5 in additional filter chain; firing Filter: 'CspUsernamePasswordAuthenticationFilter' 09:25:19.969 [5200279@qtp-16921957-13 - /training_security_check] DEBUG c.a.v.s.w.a.CspUsernamePasswordAuthenticationFilter - Request is to process authentication 09:25:24.804 [5200279@qtp-16921957-13 - /training_security_check] DEBUG o.s.s.w.s.HttpSessionEventPublisher - Publishing event: org.springframework.security.web.session.HttpSessionCreatedEvent[source=org.mortbay.jetty.servlet.HashSessionManager$Session:1j6zr4li8qb2m10zam8dqsmj1y@15216624] 09:29:26.160 [5200279@qtp-16921957-13 - /training_security_check] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession. 09:29:29.129 [5200279@qtp-16921957-13 - /training_security_check] DEBUG o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed 09:29:39.700 [5200279@qtp-16921957-13 - /training_security_check] ERROR org.mortbay.log - /training_security_check java.lang.NullPointerException: null at com.auchan.via.security.web.authentication.CspUsernamePasswordAuthenticationFilter.attemptAuthentication(CspUsernamePasswordAuthenticationFilter.java:113) ~[classes/:na] at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:211) ~[spring-security-web-3.2.5.RELEASE.jar:3.2.5.RELEASE] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) ~[spring-security-web-3.2.5.RELEASE.jar:3.2.5.RELEASE] at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110) ~[spring-security-web-3.2.5.RELEASE.jar:3.2.5.RELEASE] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) ~[spring-security-web-3.2.5.RELEASE.jar:3.2.5.RELEASE] at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87) ~[spring-security-web-3.2.5.RELEASE.jar:3.2.5.RELEASE] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) ~[spring-security-web-3.2.5.RELEASE.jar:3.2.5.RELEASE] at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192) ~[spring-security-web-3.2.5.RELEASE.jar:3.2.5.RELEASE] at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160) ~[spring-security-web-3.2.5.RELEASE.jar:3.2.5.RELEASE] at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344) ~[spring-web-4.0.6.RELEASE.jar:4.0.6.RELEASE] at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261) ~[spring-web-4.0.6.RELEASE.jar:4.0.6.RELEASE] at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1212) ~[jetty-6.1.26.jar:6.1.26] at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) ~[spring-web-4.0.6.RELEASE.jar:4.0.6.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.0.6.RELEASE.jar:4.0.6.RELEASE] at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1212) ~[jetty-6.1.26.jar:6.1.26] at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:399) ~[jetty-6.1.26.jar:6.1.26] at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216) [jetty-6.1.26.jar:6.1.26] at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182) [jetty-6.1.26.jar:6.1.26] at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:766) [jetty-6.1.26.jar:6.1.26] at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:450) [jetty-6.1.26.jar:6.1.26] at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) [jetty-6.1.26.jar:6.1.26] at org.mortbay.jetty.Server.handle(Server.java:322) [jetty-6.1.26.jar:6.1.26] at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542) [jetty-6.1.26.jar:6.1.26] at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:945) [jetty-6.1.26.jar:6.1.26] at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:756) [jetty-6.1.26.jar:6.1.26] at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218) [jetty-6.1.26.jar:6.1.26] at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404) [jetty-6.1.26.jar:6.1.26] at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:410) [jetty-6.1.26.jar:6.1.26] at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582) [jetty-util-6.1.26.jar:6.1.26] 09:29:39.911 [5200279@qtp-16921957-13 - /training_security_check] DEBUG org.mortbay.log - POST /training_security_check HTTP/1.1 ```
shiro 登录认证页面不跳转
认证是没有问题的,登录之后一直在登录页面,然后直接输入index.jsp又是可以访问的, 说明认证成功了 直接上图帐号代码,求大神。。。 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"> <!-- web.xml中shiro的filter对应的bean --> <!-- Shiro 的Web过滤器 --> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager"/> <!-- loginUrl认证提交地址,如果没有认证将会请求此地址进行认证,请求此地址将由formAuthenticationFilter进行表单认证 --> <property name="loginUrl" value="/login/login.html"/> <!-- 认证成功统一跳转到first.action,建议不配置,shiro认证成功自动到上一个请求路径 --> <property name="successUrl" value="/index.jsp"/> <!-- 通过unauthorizedUrl指定没有权限操作时跳转页面--> <!--<property name="unauthorizedUrl" value="/WEB-INF/pages/refuse.jsp"/>--> <!-- 自定义filter配置 --> <property name="filters"> <map> <!--将自定义 的FormAuthenticationFilter注入shiroFilter中--> <entry key="authc" value-ref="formAuthenticationFilter"/> </map> </property> <!-- 过虑器链定义,从上向下顺序执行,一般将/**放在最下边 --> <property name="filterChainDefinitions"> <value> <!-- 对静态资源设置匿名访问 --> /css/** = anon /datas/** = anon /html/** = anon /images/** = anon /js/** = anon /plugins/** = anon /temp/** = anon /login/login.html = anon /login/checkLogin.json = anon <!--请求这个地址退出登录 shiro清除session--> /login/logout = logout <!--所有url都必须认证通过才可以访问--> /** = authc <!--anon所有url都可以匿名访问--> <!--/** = anon--> </value> </property> </bean> <!-- securityManager安全管理器 --> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="customRealm"/> <!-- 注入缓存管理器 --> <!--<property name="cacheManager" ref="cacheManager"/>--> <!-- 注入session管理器 --> <!--<property name="sessionManager" ref="sessionManager"/>--> <!-- 记住我 --> <!--<property name="rememberMeManager" ref="rememberMeManager"/>--> </bean> <!-- realm --> <bean id="customRealm" class="com.infore.common.CustomRealm"> </bean> <!-- 缓存管理器 --> <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"> <property name="cacheManagerConfigFile" value="classpath:/shiro/shiro-ehcache.xml"/> </bean> <bean id="formAuthenticationFilter" class="com.infore.common.CustomFormAuthenticationFilter"> <!-- 表单中账号的input名称 --> <property name="usernameParam" value="username" /> <!-- 表单中密码的input名称 --> <property name="passwordParam" value="password" /> </bean> <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> <property name="securityManager" ref="securityManager" /> </bean> </beans> @ResponseBody @RequestMapping("/checkLogin.json") public AjaxResult<String> checkLogin(HttpServletRequest request){ AjaxResult<String> result = new AjaxResult<String>(); String username = request.getParameter("username"); String password = request.getParameter("password"); try{ /*if(username == null || "".equals(username)){ result.setSuccess(false); result.setMsg("请输入账号"); return result; } if(password == null || "".equals(password)){ result.setSuccess(false); result.setMsg("请输入密码"); return result; } EmpDto emp = empService.selectByUsername(username); if(emp == null){ result.setSuccess(false); result.setMsg("账号不存在"); return result; }**/ ByteSource salt = ByteSource.Util.bytes("emp"); SimpleHash simpleHash = new SimpleHash("MD5", password, salt, 2); String password_md5 = simpleHash.toString(); /*if(!emp.getPassword().equals(password_md5)){ result.setSuccess(false); result.setMsg("密码不正确"); return result; }*/ UsernamePasswordToken token = new UsernamePasswordToken(username, password_md5); Subject currentUser = SecurityUtils.getSubject(); //使用shiro来验证 token.setRememberMe(true); try { currentUser.login(token); EmpDto empDto = (EmpDto) currentUser.getPrincipal(); logger.info("User [" + empDto.getUsername() + "] logged in successfully."); //验证通过保存emp信息 super.getSession().setAttribute("emp", currentUser.getPrincipal()); super.getSession().setAttribute("username", username); super.getSession().setAttribute("empNo", empDto.getEmpNo()); } catch ( UnknownAccountException uae ) { uae.printStackTrace(); result.setSuccess(false); result.setMsg("账号不存在"); return result; } catch ( IncorrectCredentialsException ice ) { ice.printStackTrace(); result.setSuccess(false); result.setMsg("账号/密码不正确"); return result; } catch (LockedAccountException lae) { lae.printStackTrace(); result.setSuccess(false); result.setMsg("用户已被锁定"); return result; } catch (ExcessiveAttemptsException eae ) { eae.printStackTrace(); } }catch (Exception e){ logger.error("验证登录信息异常[checkLogin]",e); publicUtil.insertLog(0,e,0); result.setSuccess(false); result.setMsg("验证登录信息异常"); } return result; } /** * realm的认证方法,从数据库查询用户信息 * @param authToken * @return * @throws AuthenticationException */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authToken; EmpDto emp = empService.selectByUsername(token.getUsername()); if(emp == null){ throw new UnknownAccountException("账号不存在"); } SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(emp, emp.getPassword(), getName()); return simpleAuthenticationInfo; }
shiro添加了sessionDAO如果不进登陆页面就会报错,不能进行拦截跳转
``` 严重: Servlet.service() for servlet [com.hhwy.fweb.framework.mvc.MainDispather] in context with path [/security] threw exception [javax.servlet.ServletException: java.lang.IllegalStateException: Cannot create a session after the response has been committed] with root cause java.lang.IllegalStateException: Cannot create a session after the response has been committed at org.apache.catalina.connector.Request.doGetSession(Request.java:3030) at org.apache.catalina.connector.Request.getSession(Request.java:2468) at org.apache.catalina.connector.RequestFacade.getSession(RequestFacade.java:896) at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:231) at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:571) at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:542) at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:240) at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:240) at org.apache.jasper.runtime.PageContextImpl.initialize(PageContextImpl.java:137) at org.apache.jasper.runtime.JspFactoryImpl.internalGetPageContext(JspFactoryImpl.java:109) at org.apache.jasper.runtime.JspFactoryImpl.getPageContext(JspFactoryImpl.java:60) at org.apache.jsp.WEB_002dINF.classes.META_002dINF.resources.WEB_002dINF.jsp.ac.index_jsp._jspService(index_jsp.java:100) at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:476) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330) at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:728) at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:591) at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:527) at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:162) at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:314) at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1325) at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1069) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1008) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) at com.hhwy.fweb.framework.mvc.MainDispather.doService(MainDispather.java:95) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:870) at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855) at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at com.hhwy.fweb.framework.mvc.filter.LandFilter.doFilter(LandFilter.java:42) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at com.hhwy.fweb.framework.mvc.filter.CommonFilter.doFilter(CommonFilter.java:32) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745) ``` 下面是session的配置 ``` <bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.MemorySessionDAO"/> <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager"> <property name="sessionDAO" ref="sessionDAO"/> </bean> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="acRealm"></property> <property name="rememberMeManager" ref="rememberMeManager" /> <!-- 定义要使用的缓存管理器 --> <property name="cacheManager" ref="shiroCacheManager"/> <property name="sessionManager" ref="sessionManager" /> </bean> ``` 而且为什么登陆进去之后通过sessionDAO.getActiveSessions获取在线用户,会获取到很多个session(只有我一个人登陆),不关闭浏览器多次退出登陆和登陆还会增加session,求大神解答 重点是上面的错误怎么解决啊,大神们TAT
springboot下 shiro + redis 验证后无动作
shiro + redis 由于shiro之前没有用过 , 这次使用也是比较仓促 希望大佬们多多帮组 > 跪谢 可以在redis中看到 session的存储 验证后并不跳转到首页 附上 代码 1. 目录结构 ![图片说明](https://img-ask.csdn.net/upload/201904/26/1556279189_984298.jpg) 2. shiroConfig.java ``` import com.chenzs.common.mapper.RoleMapper; import org.apache.shiro.authc.credential.HashedCredentialsMatcher; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.apache.shiro.web.session.mgt.DefaultWebSessionManager; import org.crazycake.shiro.RedisCacheManager; import org.crazycake.shiro.RedisManager; import org.crazycake.shiro.RedisSessionDAO; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.annotation.Resource; import java.util.LinkedHashMap; import java.util.Map; /** * @author ChenZS */ @Configuration public class ShiroConfig { @Resource private RoleMapper roleMapper; @Bean public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) { System.err.println("ShiroConfiguration.shirFilter() ---> start "); ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); shiroFilterFactoryBean.setSecurityManager(securityManager); //拦截器. Map<String,String> filterChainDefinitionMap = new LinkedHashMap<String,String>(); // 配置不会被拦截的链接 顺序判断 // filterChainDefinitionMap.put("/css/**", "authc"); // filterChainDefinitionMap.put("/js/**", "authc"); // filterChainDefinitionMap.put("/img/**", "authc"); // filterChainDefinitionMap.put("/components/**", "authc"); // filterChainDefinitionMap.put("/favicon.ico", "authc"); //配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了 // filterChainDefinitionMap.put("/logout", "logout"); //<!-- 过滤链定义,从上向下顺序执行,一般将/**放在最为下边 -->:这是一个坑呢,一不小心代码就不好使了; //<!-- authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问--> // filterChainDefinitionMap.put("/**", "authc"); // 如果不设置默认会自动寻找Web工程根目录下的"/login"页面 shiroFilterFactoryBean.setLoginUrl("/login"); // // 登录成功后要跳转的链接 shiroFilterFactoryBean.setSuccessUrl("/blog"); //未授权界面; shiroFilterFactoryBean.setUnauthorizedUrl("/404"); filterChainDefinitionMap.put("/static/**", "anon"); // filterChainDefinitionMap.put("/", "perms[admin]"); // filterChainDefinitionMap.put("/user/**", "authc"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); // //从数据库获取 对应角色 // List<Role> list = roleMapper.selectByExample(null); // // for (SysPermissionInit sysPermissionInit : list) { // filterChainDefinitionMap.put(sysPermissionInit.getUrl(), // sysPermissionInit.getPermissionInit()); // } // // shiroFilterFactoryBean // .setFilterChainDefinitionMap(filterChainDefinitionMap); System.out.println("Shiro拦截器工厂类注入成功"); return shiroFilterFactoryBean; } /** * 凭证匹配器 * (由于我们的密码校验交给Shiro的SimpleAuthenticationInfo进行处理了 * ) * @return */ @Bean public HashedCredentialsMatcher hashedCredentialsMatcher(){ HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher(); //散列算法:这里使用MD5算法; hashedCredentialsMatcher.setHashAlgorithmName("md5"); //散列的次数,比如散列两次,相当于 md5(md5("")); hashedCredentialsMatcher.setHashIterations(1); return hashedCredentialsMatcher; } @Bean public MyShiroRealm myShiroRealm(){ MyShiroRealm myShiroRealm = new MyShiroRealm(); myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher()); return myShiroRealm; } @Bean public SecurityManager securityManager(){ DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); //设置realm securityManager.setRealm(myShiroRealm()); // 自定义缓存实现 使用redis securityManager.setCacheManager(cacheManager()); // 自定义session管理 使用redis securityManager.setSessionManager(sessionManager()); return securityManager; } /** * 开启shiro aop注解支持. * 使用代理方式;所以需要开启代码支持; * @param securityManager * @return */ @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){ AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); return authorizationAttributeSourceAdvisor; } /** * cacheManager 缓存 redis实现 * 使用的是shiro-redis开源插件 * * @return */ public RedisCacheManager cacheManager() { RedisCacheManager redisCacheManager = new RedisCacheManager(); redisCacheManager.setRedisManager(redisManager()); return redisCacheManager; } /** * 配置shiro redisManager * 使用的是shiro-redis开源插件 * * @return */ public RedisManager redisManager() { RedisManager redisManager = new RedisManager(); redisManager.setHost("192.168.0.12"); redisManager.setPort(6379); redisManager.setExpire(1800 * 60 *30);// 配置缓存过期时间 redisManager.setTimeout(0); redisManager.setPassword("123456789+"); // redisManager.setPassword(password); return redisManager; } /** * Session Manager * 使用的是shiro-redis开源插件 */ @Bean public DefaultWebSessionManager sessionManager() { DefaultWebSessionManager sessionManager = new DefaultWebSessionManager(); sessionManager.setSessionDAO(redisSessionDAO()); return sessionManager; } // @Bean("sessionManager") // public SessionManager sessionManager(ShiroSessionDao shiroSessionDa){ // DefaultWebSessionManager sessionManager = new DefaultWebSessionManager(); // sessionManager.setGlobalSessionTimeout(60 * 60 * 1000); // sessionManager.setSessionValidationSchedulerEnabled(true); // sessionManager.setSessionIdUrlRewritingEnabled(false); // sessionManager.setSessionDAO(shiroSessionDao); // /** 此注释代码 就是将JSESSIONID变成自定义名称 WEBJSESSIONID // sessionManager.setSessionIdCookieEnabled(true); // SimpleCookie cookie = new SimpleCookie("WEBJSESSIONID"); // cookie.setHttpOnly(true); // cookie.setMaxAge(60 * 60 * 1000); // sessionManager.setSessionIdCookie(cookie); **/ // return sessionManager; // } /** * RedisSessionDAO shiro sessionDao层的实现 通过redis * 使用的是shiro-redis开源插件 */ @Bean public RedisSessionDAO redisSessionDAO() { RedisSessionDAO redisSessionDAO = new RedisSessionDAO(); redisSessionDAO.setRedisManager(redisManager()); // // DefaultWebSessionManager sessionManager = new DefaultWebSessionManager(); // sessionManager.setGlobalSessionTimeout(60 * 60 * 1000); // sessionManager.setSessionValidationSchedulerEnabled(true); // sessionManager.setSessionIdUrlRewritingEnabled(false); // /** 此注释代码 就是将JSESSIONID变成自定义名称 WEBJSESSIONID */ // sessionManager.setSessionIdCookieEnabled(true); // SimpleCookie cookie = new SimpleCookie("WEBJSESSIONID"); // cookie.setHttpOnly(true); // cookie.setMaxAge(60 * 60 * 1000); // sessionManager.setSessionIdCookie(cookie); return redisSessionDAO; } } ``` ------ 3. MyShiroRealm.java ``` import com.chenzs.common.model.Role; import com.chenzs.common.model.User; import com.chenzs.common.service.RoleService; import com.chenzs.common.service.UserService; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import javax.annotation.Resource; import java.io.Serializable; import java.util.List; /** * @author ChenZS */ public class MyShiroRealm extends AuthorizingRealm{ @Resource private UserService userService; @Resource private RoleService roleService; @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { System.out.println("权限配置-->MyShiroRealm.doGetAuthorizationInfo()"); SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); // User user = (User) principals.getPrimaryPrincipal(); // List<Role> roleList = roleService.listRolesByUser(user); // TODO 后续应根据用户id 获取对应的权限,而不是现在的所有权限 ( 现在只有一种权限 --> admin ) List<Role> roleList = roleService.getListRole(); for (Role role : roleList) { authorizationInfo.addRole(role.getRole()); } return authorizationInfo; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { System.err.println("MyShiroRealm.doGetAuthenticationInfo() --> 开始权限验证!"); //获取用户的输入的账号. String username = (String) token.getPrincipal(); System.out.println(token.getCredentials()); //通过username从数据库中查找 User对象,如果找到,没找到. //实际项目中,这里可以根据实际情况做缓存,如果不做,Shiro自己也是有时间间隔机制,2分钟内不会重复执行该方法 User user = userService.getUser(username); if (user.getId() == null) { return null; } // User user = response.getData(); if (!user.getStatus()) { throw new LockedAccountException(username + "账号未激活或账号被封禁!"); } SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo( user, user.getPassword(), getName() ); return authenticationInfo; } } ``` 4. loginController .java ``` import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.LockedAccountException; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authc.UsernamePasswordToken; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller @RequestMapping("/login") public class LoginController { private static final String PATH = "login/"; @RequestMapping("") public String index() { return PATH + "index"; } /** * 登录提交 * @param model * @return * @throws Exception */ @PostMapping("/login_info") public String login(@RequestParam(required = true, value = "userName") String userName,@RequestParam(required = true, value = "password") String password, Model model) throws Exception { //1、验证用户名和密码 org.apache.shiro.subject.Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userName, password); String msg = "OK"; try { subject.login(usernamePasswordToken); // return "myhome/index"; } catch (UnknownAccountException e) { System.err.println("UnknownAccountException -- > 账号不存在:"); msg = "账号不存在!"; } catch (IncorrectCredentialsException e) { System.err.println("IncorrectCredentialsException -- > 密码不正确:"); msg = "密码不正确!"; } catch (LockedAccountException e) { System.err.println("LockedAccountException -- > 账号被锁定"); msg = "账号被锁定!"; } catch (Exception e) { System.err.println(e.getMessage()); } model.addAttribute("msg", msg); // return PATH + "index"; return "myhome/index"; } } ``` wechat: chen1749144759 求大佬 帮助 真的没有赏金了
cas + shiro 的问题 求大神解救~!!
我的项目地址为localhost:8090/admin cas-server地址为 localhost:8080/cas 登入后localhost:8090/admin后网页出现 localhost 将您重定向的次数过多的提示。 然后浏览器地址栏上面显示 http://localhost:8090/admin/shiro-cas/?ticket=ST-138-v4C4tODiTvNFVmXwNCKz-cas01.example.org 然后我看后台 提示 WHO: kkk WHAT: ST-136-WIcLSycjM9JasRLpionF-cas01.example.org for http://localhost:8090/admin/shiro-cas/ ACTION: SERVICE_TICKET_CREATED APPLICATION: CAS WHEN: Wed Feb 27 21:32:34 CST 2019 CLIENT IP ADDRESS: 0:0:0:0:0:0:0:1 SERVER IP ADDRESS: 0:0:0:0:0:0:0:1 ============================================================= > 2019-02-27 21:32:34,357 INFO [org.jasig.cas.CentralAuthenticationServiceImpl] - <Granted service ticket [ST-137-1neSWAn4taN2zY4Efgzd-cas01.example.org] for service [http://localhost:8090/admin/shiro-cas/] for user [kkk]> 2019-02-27 21:32:34,357 INFO [com.github.inspektr.audit.support.Slf4jLoggingAuditTrailManager] - <Audit trail record BEGIN ============================================================= WHO: kkk WHAT: ST-137-1neSWAn4taN2zY4Efgzd-cas01.example.org for http://localhost:8090/admin/shiro-cas/ ACTION: SERVICE_TICKET_CREATED APPLICATION: CAS WHEN: Wed Feb 27 21:32:34 CST 2019 CLIENT IP ADDRESS: 0:0:0:0:0:0:0:1 SERVER IP ADDRESS: 0:0:0:0:0:0:0:1 ============================================================= > 2019-02-27 21:32:34,362 INFO [org.jasig.cas.CentralAuthenticationServiceImpl] - <Granted service ticket [ST-138-v4C4tODiTvNFVmXwNCKz-cas01.example.org] for service [http://localhost:8090/admin/shiro-cas/] for user [kkk]> 2019-02-27 21:32:34,362 INFO [com.github.inspektr.audit.support.Slf4jLoggingAuditTrailManager] - <Audit trail record BEGIN ============================================================= WHO: kkk WHAT: ST-138-v4C4tODiTvNFVmXwNCKz-cas01.example.org for http://localhost:8090/admin/shiro-cas/ ACTION: SERVICE_TICKET_CREATED APPLICATION: CAS WHEN: Wed Feb 27 21:32:34 CST 2019 CLIENT IP ADDRESS: 0:0:0:0:0:0:0:1 SERVER IP ADDRESS: 0:0:0:0:0:0:0:1 ============================================================= > 貌似一直在创建票根,好像没有验证,这个怎么解决啊 求大神~!! 以下是我的shiro配置 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd" default-lazy-init="true"> <description>Shiro安全配置</description> <!-- Shiro Filter --> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager"/> <property name="loginUrl" value="http://localhost:8080/cas/login?service=http://localhost:8090/admin/shiro-cas/"/> <property name="successUrl" value="/" /> <property name="filters"> <map> <!-- 添加casFilter到shiroFilter --> <entry key="casFilter" value-ref="casFilter" /> <entry key="logout" value-ref="logout" /> </map> </property> <property name="filterChainDefinitions"> <value> <!-- 默认可以访问的 或者登陆可以访问的资源 --> /shiro-cas=casFilter /static/**= anon /manage=anon /getCode=anon /home=anon /error/**=anon /rest/**=anon /ssoReport/**=anon /logincheck=anon /logout = logout <!-- 日志文件查看 --> /logs/**=user <!-- 过滤条件 --> /**=authc </value> </property> </bean> <bean id="casFilter" class="org.apache.shiro.cas.CasFilter"> <!-- 配置验证错误时的失败页面 ,这里配置为登录页面 --> <property name="failureUrl" value="http://localhost:8080/cas/login?service=http://localhost:8090/admin/index/" /> </bean> <!-- 退出登录过滤器 --> <bean id="logout" class="org.apache.shiro.web.filter.authc.LogoutFilter"> <property name="redirectUrl" value="http://localhost:8080/cas/logout?service=http://localhost:8090/admin/index/" /> </bean> <bean id="casRealm" class="com.admin.shiro.ShiroDbRealm"> <!-- <property name="defaultRoles" value="ROLE_USER" /> --> <!-- 配置cas服务器地址 --> <property name="casServerUrlPrefix" value="http://localhost:8080/cas/" /> <!-- 客户端的回调地址设置,必须和上面的shiro-cas过滤器casFilter拦截的地址一致 --> <property name="casService" value="http://localhost:8090/admin/shiro-cas/" /> <!-- <property name="credentialsMatcher"> <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher"> <property name="hashAlgorithmName" value="md5"/> <property name="hashIterations" value="1"/> <property name="storedCredentialsHexEncoded" value="true"/> </bean> </property> --> </bean> <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"> <property name="cacheManagerConfigFile" value="classpath:security/ehcache-shiro.xml" /> </bean> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="casRealm" /> <property name="subjectFactory" ref="casSubjectFactory" /> <property name="cacheManager" ref="cacheManager" /> <property name="sessionManager" ref="shiroSessionManager" /> </bean> <!-- 如果要实现cas的remember me的功能,需要用到下面这个bean,并设置到securityManager的subjectFactory中 --> <bean id="casSubjectFactory" class="org.apache.shiro.cas.CasSubjectFactory" /> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" /> <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager" /> <property name="arguments" ref="securityManager" /> </bean> <bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO"> </bean> <bean id="shiroSessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager"> <property name="sessionDAO" ref="sessionDAO" /> <property name="sessionValidationInterval" value="10800000" /> <!-- 相隔多久检查一次session的有效性 --> <property name="globalSessionTimeout" value="10800000" /> <!-- session 有效时间为三个小时 (毫秒单位) --> <property name="sessionIdCookie.name" value="jsid" /> </bean> </beans>
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它是一个过程,是一个不断累积、不断沉淀、不断总结、善于传达自己的个人见解以及乐于分享的过程。
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过...
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...
linux系列之常用运维命令整理笔录
本博客记录工作中需要的linux运维命令,大学时候开始接触linux,会一些基本操作,可是都没有整理起来,加上是做开发,不做运维,有些命令忘记了,所以现在整理成博客,当然vi,文件操作等就不介绍了,慢慢积累一些其它拓展的命令,博客不定时更新 free -m 其中:m表示兆,也可以用g,注意都要小写 Men:表示物理内存统计 total:表示物理内存总数(total=used+free) use...
比特币原理详解
一、什么是比特币 比特币是一种电子货币,是一种基于密码学的货币,在2008年11月1日由中本聪发表比特币白皮书,文中提出了一种去中心化的电子记账系统,我们平时的电子现金是银行来记账,因为银行的背后是国家信用。去中心化电子记账系统是参与者共同记账。比特币可以防止主权危机、信用风险。其好处不多做赘述,这一层面介绍的文章很多,本文主要从更深层的技术原理角度进行介绍。 二、问题引入 假设现有4个人...
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 IT 类的外包开发,是非标品开发,所以很有可能在开发过程中会有这样那样的需求修改,而这种需求修改很容易造成扯皮,进而影响到费用支付,甚至出现做完了项目收不到钱的情况。 那么,怎么保证自己的薪酬安全呢? 我们在开工前,一定要做好一些证据方面的准备(也就是“讨薪”的理论依据),这其中最重要的就是需求文档和验收标准。一定要让需求方提供这两个文档资料作为开发的基础。之后开发...
网页实现一个简单的音乐播放器(大佬别看。(⊙﹏⊙))
今天闲着无事,就想写点东西。然后听了下歌,就打算写个播放器。 于是乎用h5 audio的加上js简单的播放器完工了。 演示地点演示 html代码如下` music 这个年纪 七月的风 音乐 ` 然后就是css`*{ margin: 0; padding: 0; text-decoration: none; list-...
Python十大装B语法
Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。
数据库优化 - SQL优化
以实际SQL入手,带你一步一步走上SQL优化之路!
通俗易懂地给女朋友讲:线程池的内部原理
餐盘在灯光的照耀下格外晶莹洁白,女朋友拿起红酒杯轻轻地抿了一小口,对我说:“经常听你说线程池,到底线程池到底是个什么原理?”
经典算法(5)杨辉三角
杨辉三角 是经典算法,这篇博客对它的算法思想进行了讲解,并有完整的代码实现。
使用 Docker 部署 Spring Boot 项目
Docker 技术发展为微服务落地提供了更加便利的环境,使用 Docker 部署 Spring Boot 其实非常简单,这篇文章我们就来简单学习下。首先构建一个简单的 S...
英特尔不为人知的 B 面
从 PC 时代至今,众人只知在 CPU、GPU、XPU、制程、工艺等战场中,英特尔在与同行硬件芯片制造商们的竞争中杀出重围,且在不断的成长进化中,成为全球知名的半导体公司。殊不知,在「刚硬」的背后,英特尔「柔性」的软件早已经做到了全方位的支持与支撑,并持续发挥独特的生态价值,推动产业合作共赢。 而对于这一不知人知的 B 面,很多人将其称之为英特尔隐形的翅膀,虽低调,但是影响力却不容小觑。 那么,在...
面试官:你连RESTful都不知道我怎么敢要你?
干货,2019 RESTful最贱实践
刷了几千道算法题,这些我私藏的刷题网站都在这里了!
遥想当年,机缘巧合入了 ACM 的坑,周边巨擘林立,从此过上了"天天被虐似死狗"的生活… 然而我是谁,我可是死狗中的战斗鸡,智力不够那刷题来凑,开始了夜以继日哼哧哼哧刷题的日子,从此"读题与提交齐飞, AC 与 WA 一色 ",我惊喜的发现被题虐既刺激又有快感,那一刻我泪流满面。这么好的事儿作为一个正直的人绝不能自己独享,经过激烈的颅内斗争,我决定把我私藏的十几个 T 的,阿不,十几个刷题网...
白话阿里巴巴Java开发手册高级篇
不久前,阿里巴巴发布了《阿里巴巴Java开发手册》,总结了阿里巴巴内部实际项目开发过程中开发人员应该遵守的研发流程规范,这些流程规范在一定程度上能够保证最终的项目交付质量,通过在时间中总结模式,并推广给广大开发人员,来避免研发人员在实践中容易犯的错误,确保最终在大规模协作的项目中达成既定目标。 无独有偶,笔者去年在公司里负责升级和制定研发流程、设计模板、设计标准、代码标准等规范,并在实际工作中进行...
SQL-小白最佳入门sql查询一
不要偷偷的查询我的个人资料,即使你再喜欢我,也不要这样,真的不好;
redis分布式锁,面试官请随便问,我都会
文章有点长并且绕,先来个图片缓冲下! 前言 现在的业务场景越来越复杂,使用的架构也就越来越复杂,分布式、高并发已经是业务要求的常态。像腾讯系的不少服务,还有CDN优化、异地多备份等处理。 说到分布式,就必然涉及到分布式锁的概念,如何保证不同机器不同线程的分布式锁同步呢? 实现要点 互斥性,同一时刻,智能有一个客户端持有锁。 防止死锁发生,如果持有锁的客户端崩溃没有主动释放锁,也要保证锁可以正常释...
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // doshom...
Nginx 原理和架构
Nginx 是一个免费的,开源的,高性能的 HTTP 服务器和反向代理,以及 IMAP / POP3 代理服务器。Nginx 以其高性能,稳定性,丰富的功能,简单的配置和低资源消耗而闻名。 Nginx 的整体架构 Nginx 里有一个 master 进程和多个 worker 进程。master 进程并不处理网络请求,主要负责调度工作进程:加载配置、启动工作进程及非停升级。worker 进程负责处...
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,...
程序员:我终于知道post和get的区别
是一个老生常谈的话题,然而随着不断的学习,对于以前的认识有很多误区,所以还是需要不断地总结的,学而时习之,不亦说乎
《程序人生》系列-这个程序员只用了20行代码就拿了冠军
你知道的越多,你不知道的越多 点赞再看,养成习惯GitHub上已经开源https://github.com/JavaFamily,有一线大厂面试点脑图,欢迎Star和完善 前言 这一期不算《吊打面试官》系列的,所有没前言我直接开始。 絮叨 本来应该是没有这期的,看过我上期的小伙伴应该是知道的嘛,双十一比较忙嘛,要值班又要去帮忙拍摄年会的视频素材,还得搞个程序员一天的Vlog,还要写BU...
加快推动区块链技术和产业创新发展,2019可信区块链峰会在京召开
11月8日,由中国信息通信研究院、中国通信标准化协会、中国互联网协会、可信区块链推进计划联合主办,科技行者协办的2019可信区块链峰会将在北京悠唐皇冠假日酒店开幕。   区块链技术被认为是继蒸汽机、电力、互联网之后,下一代颠覆性的核心技术。如果说蒸汽机释放了人类的生产力,电力解决了人类基本的生活需求,互联网彻底改变了信息传递的方式,区块链作为构造信任的技术有重要的价值。   1...
Java世界最常用的工具类库
Apache Commons Apache Commons有很多子项目 Google Guava 参考博客
程序员把地府后台管理系统做出来了,还有3.0版本!12月7号最新消息:已在开发中有github地址
第一幕:缘起 听说阎王爷要做个生死簿后台管理系统,我们派去了一个程序员…… 996程序员做的梦: 第一场:团队招募 为了应对地府管理危机,阎王打算找“人”开发一套地府后台管理系统,于是就在地府总经办群中发了项目需求。 话说还是中国电信的信号好,地府都是满格,哈哈!!! 经常会有外行朋友问:看某网站做的不错,功能也简单,你帮忙做一下? 而这次,面对这样的需求,这个程序员...
网易云6亿用户音乐推荐算法
网易云音乐是音乐爱好者的集聚地,云音乐推荐系统致力于通过 AI 算法的落地,实现用户千人千面的个性化推荐,为用户带来不一样的听歌体验。 本次分享重点介绍 AI 算法在音乐推荐中的应用实践,以及在算法落地过程中遇到的挑战和解决方案。 将从如下两个部分展开: AI算法在音乐推荐中的应用 音乐场景下的 AI 思考 从 2013 年 4 月正式上线至今,网易云音乐平台持续提供着:乐屏社区、UGC...
【技巧总结】位运算装逼指南
位算法的效率有多快我就不说,不信你可以去用 10 亿个数据模拟一下,今天给大家讲一讲位运算的一些经典例子。不过,最重要的不是看懂了这些例子就好,而是要在以后多去运用位运算这些技巧,当然,采用位运算,也是可以装逼的,不信,你往下看。我会从最简单的讲起,一道比一道难度递增,不过居然是讲技巧,那么也不会太难,相信你分分钟看懂。 判断奇偶数 判断一个数是基于还是偶数,相信很多人都做过,一般的做法的代码如下...
为什么要学数据结构?
一、前言 在可视化化程序设计的今天,借助于集成开发环境可以很快地生成程序,程序设计不再是计算机专业人员的专利。很多人认为,只要掌握几种开发工具就可以成为编程高手,其实,这是一种误解。要想成为一个专业的开发人员,至少需要以下三个条件: 1) 能够熟练地选择和设计各种数据结构和算法 2) 至少要能够熟练地掌握一门程序设计语言 3) 熟知所涉及的相关应用领域的知识 其中,后两个条件比较容易实现,而第一个...
Android 9.0 init 启动流程
阅读五分钟,每日十点,和您一起终身学习,这里是程序员Android本篇文章主要介绍Android开发中的部分知识点,通过阅读本篇文章,您将收获以下内容:一、启动流程概述一、 启动流程概述Android启动流程跟Linux启动类似,大致分为如下五个阶段。1.开机上电,加载固化的ROM。2.加载BootLoader,拉起Android OS。3.加载Uboot,初始外设,引导Kernel启动等。...
8年经验面试官详解 Java 面试秘诀
作者 |胡书敏 责编 | 刘静 出品 | CSDN(ID:CSDNnews) 本人目前在一家知名外企担任架构师,而且最近八年来,在多家外企和互联网公司担任Java技术面试官,前后累计面试了有两三百位候选人。在本文里,就将结合本人的面试经验,针对Java初学者、Java初级开发和Java开发,给出若干准备简历和准备面试的建议。 Java程序员准备和投递简历的实...
面试官如何考察你的思维方式?
1.两种思维方式在求职面试中,经常会考察这种问题:北京有多少量特斯拉汽车?某胡同口的煎饼摊一年能卖出多少个煎饼?深圳有多少个产品经理?一辆公交车里能装下多少个乒乓球?一个正常成年人有多少根头发?这类估算问题,被称为费米问题,是以科学家费米命名的。为什么面试会问这种问题呢?这类问题能把两类人清楚地区分出来。一类是具有文科思维的人,擅长赞叹和模糊想象,它主要依靠的是人的第一反应和直觉,比如小孩...
前后端分离,我怎么就选择了 Spring Boot + Vue 技术栈?
前两天又有小伙伴私信松哥,问题还是职业规划,Java 技术栈路线这种,实际上对于这一类问题我经常不太敢回答,每个人的情况都不太一样,而小伙伴也很少详细介绍自己的情况,大都是一两句话就把问题抛出来了,啥情况都不了解,就要指出一个方向,这实在是太难了。 因此今天我想从我学习 Spring Boot + Vue 这套技术栈的角度,来和大家聊一聊没有人指导,我是如何一步一步建立起自己的技术体系的。 线上大...
17张图带你解析红黑树的原理!保证你能看懂!
二叉查找树 由于红黑树本质上就是一棵二叉查找树,所以在了解红黑树之前,咱们先来看下二叉查找树。 二叉查找树(Binary Search Tree),也称有序二叉树(ordered binary tree),排序二叉树(sorted binary tree),是指一棵空树或者具有下列性质的二叉树: 若任意结点的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若任意结点的...
so easy! 10行代码写个"狗屁不通"文章生成器
前几天,GitHub 有个开源项目特别火,只要输入标题就可以生成一篇长长的文章。 背后实现代码一定很复杂吧,里面一定有很多高深莫测的机器学习等复杂算法 不过,当我看了源代码之后 这程序不到50行 尽管我有多年的Python经验,但我竟然一时也没有看懂 当然啦,原作者也说了,这个代码也是在无聊中诞生的,平时撸码是不写中文变量名的, 中文...
知乎高赞:中国有什么拿得出手的开源软件产品?(整理自本人原创回答)
知乎高赞:中国有什么拿得出手的开源软件产品? 在知乎上,有个问题问“中国有什么拿得出手的开源软件产品(在 GitHub 等社区受欢迎度较好的)?” 事实上,还不少呢~ 本人于2019.7.6进行了较为全面的回答,对这些受欢迎的 Github 开源项目分类整理如下: 分布式计算、云平台相关工具类 1.SkyWalking,作者吴晟、刘浩杨 等等 仓库地址: apache/skywalking 更...
相关热词 c# plc s1200 c#里氏转换原则 c# 主界面 c# do loop c#存为组套 模板 c# 停掉协程 c# rgb 读取图片 c# 图片颜色调整 最快 c#多张图片上传 c#密封类与密封方法
立即提问