中软国际实训-第七天

过滤器、权限管理

由于之前没有设置filter,所以不会对没有登陆的用户进行拦截,能够直接通过地址访问到其他页面,很不安全,所以今天就是要增加一个用过滤器来限制登陆用户。

Filter

LoginFilter

package com.zhongruan.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class LoginFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        HttpSession session =request.getSession();
        if(session.getAttribute("userinfo")==null&&request.getRequestURL().indexOf("/user/login.do")==-1){
            response.sendRedirect(request.getContextPath()+"/user/login.do");
        }else{
            filterChain.doFilter(request,response);
        }
    }

    @Override
    public void destroy() {

    }
}

Filter基本功能实现就是这样,在这之前,还需要在applicationContext中加入该filter,等一些其他声明。

spring.security

由于自己写的Filter函数功能不够强大,故而使用功能更为强大框架。

  • 首先导入jar包
  <spring.version>5.0.2.RELEASEspring.version>

 <dependency>
      <groupId>org.springframework.securitygroupId>
      <artifactId>spring-security-taglibsartifactId>
      <version>${spring.security.version}version>
    dependency>

  • 导入资源文件spring-security.xml

<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:global-method-security pre-post-annotations="enabled" jsr250-annotations="enabled" secured-annotations="enabled">security:global-method-security>

    
    <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"/>
    
    <security:http auto-config="true" use-expressions="true">
        
        <security:intercept-url pattern="/**" access="hasAnyRole('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:logout>

    security:http>

    
    <security:authentication-manager>
        <security:authentication-provider user-service-ref="UserinfoService">
            
        security:authentication-provider>
    security:authentication-manager>

    
    <bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
    
    

beans>
  • 创建对应的文件
    中软国际实训-第七天_第1张图片
  • 先在Service抽象类中继承UserDetailsService 之后在UserinfoServiceImp.java中实现方法
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {


        Userinfo userinfo = userinfoDao.findByUserName(username);
        List<Role>roles=RoleDao.findRoleByuserId(userinfo.getId());

        User user=new User(userinfo.getName(),"{noop}"+userinfo.getPassword(),getAutherity(roles));
        return user;
    }

    private Collection<? extends GrantedAuthority> getAutherity(List<Role> roles) {
        List<SimpleGrantedAuthority>list =new ArrayList<>();
        for(Role role:roles){
            list.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
        }
        return list;
    }


}

  • 最后还要记得在login.jsp中改变文件路径

总结

最坑的地方在于loadUserByUsername传回来的参数一开始老为空,发现是jsp那边的名称与函数名称不对应,然而两边都为name的时候,依旧为空值,我猜测是这个框架内部设置的问题,反正name就是不OK,值得注意一下。
在写项目的过程中,问题发生最多的地方,就是名称不匹配的问题了,值得反思!!!

你可能感兴趣的:(中软国际实训-第七天)