权限管理-spring-security的使用

spring-security

依赖

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

        <dependency>
            <groupId>javax.annotationgroupId>
            <artifactId>jsr250-apiartifactId>
            <version>1.0version>
        dependency>

配置文件

  1. web.xml
    
  <context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath*:applicationContext.xml,classpath*:spring-security.xml
    param-value>
  context-param>
  
  
  <filter>
    <filter-name>springSecurityFilterChainfilter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class>
  filter>
  <filter-mapping>
    <filter-name>springSecurityFilterChainfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>
  1. spring-security
<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"/>

    
    <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: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>

方法级权限控制

  1. 开启权限控制

    <security:global-method-security jsr250-annotations="enabled"/>
    <security:global-method-security secured-annotations="enabled"/>
    <security:global-method-security pre-post-annotations="enabled"/>
  1. jsr250注解使用
//该方法只要具有"USER", "ADMIN"任意一种权限就可以访问。这里可以省略前缀ROLE_,实际的权限可能是ROLE_ADMIN
@RolesAllowed({"USER", "ADMIN"}) 
 @RequestMapping("/findAll.do")
  public ModelAndView findAll() throws Exception { }
  1. 支持表达式的注解
//该方法只有用户名为jack的用户才能访问。
@PreAuthorize("authentication.principal.username=='jack'")
@RequestMapping("/save.do")
    public String save(UserInfo user) throws Exception { }


//这里表示在changePassword方法执行之前,判断方法参数userId的值是否等于principal中保存的当前用户的userId,或者当前用户是否具有ROLE_ADMIN权限,两种符合其一,就可以访问该方法。
@PreAuthorize("#userId == authentication.principal.userId or hasAuthority(‘ADMIN’)")
void changePassword(@RequestParam("userId") long userId ){ }

页面权限控制

  1. 依赖
 <dependency>
    <groupId>org.springframework.securitygroupId>
    <artifactId>spring-security-taglibsartifactId>
    <version>versionversion>
dependency>
  1. 页面导入标签库
 <%@taglib uri="http://www.springframework.org/security/tags" prefix="security"%>
  1. 常用标签

<security:authentication property="principal.username">security:authentication>



<security:authorize access="hasRole('ROLE_ADMIN')">   
    <a     href="${pageContext.request.contextPath}/user/findAll.do"> 
    <i  class="fa fa-circle-o">i> 用户管理
    a>     
security:authorize>


用户登录

  1. 配置文件
    配置了 登录界面/失败界面,可登录权限,加密方式
 <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: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"/>


  1. 代码
    用户的密码必须加密后,才能登录成功

//指定service的名字,用于spring-security
@Service("userService")
@Transactional
public class IUserServiceImpl implements IUserService {
    @Autowired
    private IUserDao iUserDao;

    // spring-security提供的加密的类
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    /*
    * 实现spring-security 的验证方法loadUserByUsername
    * */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo=null;
        try {
            userInfo  = iUserDao.findByuserName(username);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //获取可访问的角色
        List<SimpleGrantedAuthority> authority = getAuthority(userInfo.getRoles());
        //处理用户对象封装成UserDetails
        //这里的user是spring-security提供的user,实现了UserDetails
        //user的status为0,账户不可用  enable为false
        User user =new User(userInfo.getUsername(),userInfo.getPassword(),userInfo.getStatus()==0?false:true,true,true,true,authority);
        return user;
    }

/**
     * 装入角色描述  允许访问的角色ROLE
     * 返回list集合
     * */
    public List<SimpleGrantedAuthority> getAuthority(List<Role> roles){
        List<SimpleGrantedAuthority> list=new ArrayList<>();
        for(Role role:roles){
            String roleName = role.getRoleName();
            list.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
        }
        return list;
    }
    
   /*
    * 添加用户
    * */
    @Override
    public void save(UserInfo userInfo) throws Exception {
        //保存时对密码进行加密处理
        userInfo.setPassword(bCryptPasswordEncoder.encode(userInfo.getPassword()));
       
       iUserDao.save(userInfo);
    }

你可能感兴趣的:(spring-security,权限管理,spring)