zoukankan      html  css  js  c++  java
  • springsecurity安全框架总结

    springSecurity安全框架为系统安全做了两件事

      1.系统权限设置

      2.用户登录认证

    配置springSecurity步骤

    1.导入依赖

      

    <!--spring security模块-->
    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-config</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!--spring security标签库包-->
    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-taglibs</artifactId>
      <version>${spring.version}</version>
    </dependency>

    2.web.xml配置  

      配置spring security 过滤器以及读取配置文件并创建bean
    <!--指定spring配置文件位置-->
    <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/applicationContext-*.xml</param-value>
    </context-param>
    
    <!--配置ContextLoaderListener监听器,说明:
          1.ContextLoaderListener监听器,监听ServletContext对象的创建。一旦ServletContext对象创建,
          它立即帮助我们创建spring容器,并且放入ServletContext域中。
          2.该监听器,默认只能加载WEB-INF目录下,名称为applicationContext.xml的配置文件
          3.通过context-param标签,配置指定spring的配置文件位置,改变默认行为。
      -->
    <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    
    
    <!--配置spring security 过滤器,说明:
    1.细节:springSecurityFilterChain名称是固定写法
        -->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    
    <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <!--配置所有请求都进入security过滤器处理-->
    <url-pattern>/*</url-pattern>
    </filter-mapping>

    3.springSecurity认证和授权的配置

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:security="http://www.springframework.org/schema/security"
           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">
    
    
    
        <!--配置http请求相关:授权,说明:
        auto-config:开启自动配置
            use-expressions:开启使用spel表达式-->
        <security:http auto-config="true" use-expressions="true">
            <!--配置权限拦截url规则,说明:
                pattern:url匹配模式
                access:可访问角色列表-->
            <!--系统管理模式块。要求需要管理员   http://localhost:8080/data-management/role/list/1/5-->
            <security:intercept-url pattern="/user/**" access="hasRole('ROLE_ADMIN')"></security:intercept-url>
            <security:intercept-url pattern="/role/**" access="hasRole('ROLE_ADMIN')"></security:intercept-url>
            <security:intercept-url pattern="/permission/**" access="hasRole('ROLE_ADMIN')"></security:intercept-url>
            <security:intercept-url pattern="/syslog/**" access="hasRole('ROLE_ADMIN')"></security:intercept-url>
    
            <!--基础数据模块。普通用户和管理员都可以访问-->
            <security:intercept-url pattern="/product/**" access="hasAnyRole('ROLE_USER','ROLE_ADMIN')"></security:intercept-url>
            <security:intercept-url pattern="/order/**" access="hasAnyRole('ROLE_USER','ROLE_ADMIN')"></security:intercept-url>
    
    
            <!--配置登录表单,说明:
                login-page:登录页面
                    default-target-url:成功登录跳转地址
                    authentication-failure-url:登录失败跳转页面-->
            <security:form-login login-page="/login.jsp"
                                 default-target-url="/index.jsp" authentication-failure-url="/failer.jsp"></security:form-login>
            <!--配置退出,说明:
            logout-success-url:成功退出后跳转地址
            invalidate-session:销毁 session-->
            <security:logout logout-success-url="/login.jsp" invalidate-session="true"></security:logout>
            <!--关闭伪造表单请求-->
            <security:csrf disabled="true"></security:csrf>
            <!--配置403禁止访问页面-->
            <security:access-denied-handler error-page="/403.jsp"></security:access-denied-handler>
        </security:http>
        
        
        
        
        
        <!--配置用户信息相关:认证-->
        <security:authentication-manager>
            <security:authentication-provider>
                <security:user-service>
                    <security:user name="黄思聪" password="{noop}123456" authorities="ROLE_USER"></security:user>
                    <security:user name="xiaom" password="{noop}123456" authorities="ROLE_ADMIN"></security:user>
                </security:user-service>
            </security:authentication-provider>
        </security:authentication-manager>
    </beans>

    注意点:页面方面文本输入框,name属性一定要写 username,password

    4.springSecurity获取用户名的方式

      首先数据库存放的用户名放进principal(主角),接着放进authentication,再放进SPRING_SECURITY_CONTEXT(context上下文对象),最后放进sessionScope(session对象)

      

      l   认证通过后会返回User对象,该对象中包含用户名等信息

      l   用户User对象,会封装到Authentication(认证)对象中,在Authentication中表现为Principal

      l   Principal(主角)就是User对象

      l   最终Authentication对象会封装到SecurityContext(Security上下文对象)中

      l   最后会把SecurityContext对象,设置到HttpSession中

      ${sessionScope.SPRING_SECURITY_CONTEXT.authentication.principal.username}

     实现根据数据库中的用户进行登录(自定义认证)

    需求分析

    根据用户在登录页面输入的用户名称,查询数据库中的用户,并且查询出用户关联的角色信息,结合spring security进行用户认证。

    用户dao接口

    1 **
    2      * 根据用户名称查询用户
    3      */
    4 List<User> findUserByName(String userName);
    5 }

    dao接口映射文件

    1 <!--根据用户名称查询用户-->
    2 <select id="findUserByName"parameterType="string"resultType="user">
    3      select * from `user` where username=#{userName}
    4 </select>

    service接口

    1 /**
    2      * 根据用户名称查询用户
    3      */
    4 List<User> findUserByName(String userName);

     service实现类

    1 /**
    2  * 根据用户名称查询用户
    3  */
    4 public List<User> findUserByName(String userName) {
    5 return userDao.findUserByName(userName);
    6 }

    编写SsmUserDetailService

     1 /**
     2  * 自定义认证service
     3  */
     4 
     5 public class SsmUserDetailService  implements UserDetailsService{
     6 
     7 // 注入用户service
     8 @Autowired
     9 private UserService userService;
    10 
    11 /**
    12      * 实现逻辑:
    13      *      1.根据用户名称查询用户信息
    14      *      2.根据用户id查询角色信息
    15      */
    16 public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
    17 
    18 // 定义角色权限集合
    19 List<GrantedAuthority> ga = new ArrayList<GrantedAuthority>();
    20 
    21 // 根据用户名称查询用户信息
    22 List<User> list = userService.findUserByName(s);
    23 
    24 // 根据用户名称查询到用户,则继续查询用户的角色
    25 if(list !=null && list.size()>0){
    26             User user = userService.findUserById(list.get(0).getId());
    27 
    28 // 获取角色列表
    29 List<Role> roleList = user.getRoleList();
    30 if(roleList != null && roleList.size()>0){
    31 for(Role r:roleList){
    32 // 添加角色
    33 ga.add(new SimpleGrantedAuthority(r.getRoleName()));
    34                 }
    35             }
    36 
    37 // 创建并返回security 用户对象
    38 org.springframework.security.core.userdetails.User securityUser =
    39 new org.springframework.security.core.userdetails.User(user.getUsername(),
    40 "{MD5}"+user.getPassword(),ga);
    41 
    42 return securityUser;
    43         }
    44 
    45 // 查询不到用户,返回null
    46 return null;
    47     }
    48 }

    配置自定义认证

     1     <!--配置用户信息相关:认证-->
     2     <security:authentication-manager>
     3         <security:authentication-provider user-service-ref="userDetailService">
     4             <!--  <security:user-service>
     5                 <security:user name="黄思聪" password="{noop}123456" authorities="ROLE_USER"></security:user>
     6                  <security:user name="xiaom" password="{noop}123456" authorities="ROLE_ADMIN"></security:user>
     7             </security:user-service>-->
     8         </security:authentication-provider>
     9     </security:authentication-manager>
    10     <!--配置自定义认证service-->
    11     <bean id="userDetailService" class="com.java1995.sercuity.SsmUserDetailService"></bean>
  • 相关阅读:
    CPU高问题排查
    java lambda特性(持续学习+更新)
    零星小记
    redis分布式锁和lua脚本
    webservice之拦截器
    扫一扫
    qq登录
    banner的使用
    surfaceview+mediaplayer
    viewpager加fragment可滑动加radio跟随滑动
  • 原文地址:https://www.cnblogs.com/Jeremy95-Sze/p/13191613.html
Copyright © 2011-2022 走看看