Spring Security的使用(入门)

 概述:Spring Security的前身是Acegi Security,是Spring项目组中用来提供安全认证服务的框架
      认证: 验证用户名密码是否正确的过程,authentication
      授权: 对用户所能访问的资源进行控制,authority

第一步:导入依赖
<dependencies>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>5.0.1.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>5.0.1.RELEASE</version>
    </dependency>
</dependencies>

第二步:配置web.xml
<!--配置listener-->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--环境加载监听器,默认只能加载WEB-INF目录下的资源,手动指定环境参数的位置-->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <!--classpath*可以加载多个资源文件-->
    <param-value>classpath*:applicationContext.xml,classpath*:spring-security.xml</param-value>
</context-param>
<!--配置filter-->
<filter>
    <!--此处springSecurityFilterChain固定写法,不能改变-->
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-value>org.springframework.web.filter.DelegatingFilterProxy</filter-value>
</filter>
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

第三步:配置spring-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">
    
    <!--配置不拦截的资源,注意不要把pages目录页配置进来-->
     <security:http pattern="/login.jsp" security="none"/>
     <security:http pattern="/failure.jsp" security="none"/>
     <security:http pattern="/css/**" security="none"/>
     <security:http pattern="/js/**" security="none"/>
     <security:http pattern="/img/**" security="none"/>
     <security:http pattern="/plugins/**" security="none"/>

    <!--配置具体的规则-->
    <security:http auto-config="true" use-expressions="false">
        <!--配置具体的拦截放行规则-->
        <security:intercept-url pattern="/**" access="ROLE_USER,ROLE_ADMIN"/>
        <!--配置具体的表单页面-->
        <security:form-page
            login-page="/login.jsp"        <!--指定登录页面-->              
             login-processing-url="/login.do"  <!--指定处理登录请求的url-->
             default-target-url="/login.jsp"   <!--指定登录成功的页面-->
             authentication-failure-url="/failure.jsp" <!--指定登录失败的页面-->
        <!--关闭跨域请求,注意少了这一行会一直403-->
        <security-csrf disabled="true"/>
        <!--配置注销用户,logout-url指定处理退出请求的url-->
        <security:logout invalidate-session="true" logout-url="/logout.do" 
logout-success-url="/login.jsp">     
    </security:http>
        
    <!--在service层从数据库查询账户信息-->
     <security:authentication-manager>
         <security:authentication-provider user-service-ref="userServiceImpl">
         </security:authentication-provider>
     </security:authentication-manager>
        
     <!--配置密码加密类对象-->
     <bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
     </bean>
</beans>

第四步:配置Service层
    自定义一个接口继承UserDetailsService接口
    public interface IUserService extends UserDetailsService{ 什么代码都不写 }
    实现自定义的IUserService接口
    public class UserServiceImpl implements IUserService{ ... }
    这里的User是由spring-security框架提供的,以下是User源码的Field
    public class User implements UserDetails, CredentialsContainer {
        private String password;
        private final String username;
        private final Set<GrantedAuthority> authorities;
        private final boolean accountNonExpired; //帐户是否过期
        private final boolean accountNonLocked; //帐户是否锁定
        private final boolean credentialsNonExpired; //认证是否过期
        private final boolean enabled; //帐户是否可用
}    

@Service("userServiceImpl")
public class UserServiceImpl implements IUserService{ 
     @Autowired
    private IUserDao userDao;
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = userDao.findByUsername(username);
        User user = new User(userInfo.getUsername(),"    {noop}"+userInfo.getPassword(),userInfo.getStatus()==0?false:true,
                true,true,true,getAuthorities(userInfo.getRoles()));
        return user;
    }
    public List<SimpleGrantedAuthority> getAuthorities(List<Role> roles){
        List<SimpleGrantedAuthority> list=new ArrayList<>();
        for (Role role : roles) {
            String roleName = role.getRoleName();
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_"+roleName);
            System.out.println("ROLE_"+roleName);
            list.add(authority);
        }
        return list;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42514129/article/details/83187464