Spring Security 3 간단하게 사용 (파일 에 권한 설정)

39019 단어 Spring Security
1. 권한 이 설정 파일 에 적 혀 있 는 이상 데이터베이스 에 세 개의 표 만 있 으 면 됩 니 다.
1)t_사용자 테이블
2)t_역할 표
3)t_user_역할 사용자 역할 표
2. 대응 하 는 영역 실체
1) 사용자
package cn.luxh.app.domain;
/**
 *   
 * @author Luxh
 */
public class User {
    
    private Integer id;
    /**  */
    private String account;
    /**  */
    private String password;
    
    
    @Override
    public int hashCode() {
        return account.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        User user = (User) obj;
        return this.account.equals(user.getAccount());
    }
    
    //getter setter
    //...
}

2) 역할
package cn.luxh.app.domain;

/**
 *   
 * @author Luxh
 */
public class Role {
    
    private Integer id;
    /**    */
    private String name;
    
    //getter setter
    //...
}

3) 유저 - 캐릭터
package cn.luxh.app.domain;
/**
 *     
 * @author Luxh
 */
public class UserRole {
    private Integer id;
    /**  id*/
    private Integer userId;
    /**  id*/
    private Integer roleId;
    
    //getter setter
    //...
}

3. 프로필
웹. xml 파일 에 다음 과 같은 내용 을 추가 합 니 다.
<!-- SpringSecurity     -->  
  <filter>  
        <filter-name>springSecurityFilterChain</filter-name>  
        <filter-class>  
            org.springframework.web.filter.DelegatingFilterProxy  
        </filter-class>  
   </filter>  
    <filter-mapping>  
        <filter-name>springSecurityFilterChain</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>  

 <!--    Spring Security session     -->  
    <listener>  
        <listener-class>  
         org.springframework.security.web.session.HttpSessionEventPublisher   
        </listener-class>  
    </listener>  

물론 spring 모니터 를 설정 할 때 springsecurity 권한 설정 파일 을 불 러 와 야 합 니 다.
<!--   Spring    -->
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml,classpath:application-security.xml</param-value>
    </context-param>

권한 설정 파일 내용 은 다음 과 같 습 니 다.
<?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.2.xsd
                        http://www.springframework.org/schema/security 
                        http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <!--         -->
    <http pattern="/login" security="none" />
    <!--         -->
    <http pattern="/resources/**" security="none" />
    

    <http auto-config="true" use-expressions="true" access-denied-page="/denied">

        <!-- default-target-url                    always-use-default-target true            
            authentication-failure-url              login-processing-url           ,     ,   j_spring_security_check 
            username-parameter,password-parameter              name,  :j_username,j_password 
            default-target-url="/user/home" -->
        <form-login login-page="/login"
            always-use-default-target="true"
            authentication-success-handler-ref="successHandler"
            authentication-failure-handler-ref="failureHandler" />
        
        <!--              -->
        <intercept-url pattern="/index" access="hasAnyRole('ROLE_ADMIN','ROLE_USER')" />
        <!--              -->
        <intercept-url pattern="/common" access="hasAnyRole('ROLE_ADMIN','ROLE_USER')" />
        <!--           -->
        <intercept-url pattern="/admin" access="hasAnyRole('ROLE_ADMIN')" />
        <!--          -->
        <logout logout-success-url="/login" />

        <!-- error-if-maximum-exceeded                   
            session-fixation-protection 
                sessionid  .                session.   
                    session,          session . -->

        <session-management invalid-session-url="/login?error=3"
            session-fixation-protection="none">
            <concurrency-control max-sessions="1"
                error-if-maximum-exceeded="true" expired-url="/login?error=2" /><!--         -->
        </session-management>
    </http>


    <authentication-manager alias="authenticationManager">
        <authentication-provider user-service-ref="UserDetailsService"/>
    </authentication-manager>

    <beans:bean id="UserDetailsService" class="cn.luxh.app.security.UserDetailsServiceImpl" />
    
    <!--          -->
    <beans:bean id="successHandler"
        class="cn.luxh.app.security.LoginAuthenticationSuccessHandler">
        <beans:property name="url" value="/index"></beans:property>  
    </beans:bean>
    
    <!--          -->
    <beans:bean id="failureHandler" class="cn.luxh.app.security.LoginAuthenticationFailureHandler"/>
    

</beans:beans>

4. 권한 설정 파일 에 사용 할 클래스
1)UserDetailsServiceImpl
package cn.luxh.app.security;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import cn.luxh.app.domain.Role;
import cn.luxh.app.domain.User;
import cn.luxh.app.persistence.RoleMapper;
import cn.luxh.app.persistence.UserMapper;

public class UserDetailsServiceImpl implements UserDetailsService{
    
    private static Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private RoleMapper roleMapper;
    
    /**
     * @param account     
     */
    public UserDetails loadUserByUsername(String account)
            throws UsernameNotFoundException {
        log.info("    :"+account);
        org.springframework.security.core.userdetails.User userDetails = null;
        User user = userMapper.selectByAccount(account);
        
        //      ,           ,        AuthenticationFailureHandler    
        
        Collection<GrantedAuthority> grantedAuthorities = getGrantedAuthorities(user);  
        boolean enables = true;  
        boolean accountNonExpired = true;  
        boolean credentialsNonExpired = true;  
        boolean accountNonLocked = true; 
        userDetails = new org.springframework.security.core.userdetails.User(user.getAccount(), user.getPassword(), enables, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuthorities);  
        return userDetails;
    }
    
    /**
     *               
     * @param user
     * @return
     */
    private Set<GrantedAuthority> getGrantedAuthorities(User user) {
        Set<GrantedAuthority> grantedAuthorities = new HashSet<GrantedAuthority>();  
        List<Role> roles = roleMapper.selectByUserId(user.getId()); 
        if(roles != null) {
            for(Role role : roles) {  
                grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
            }  
        }
        return grantedAuthorities;  
    }

}

UserMapper 와 RoleMapper 는 내 가 MyBatis 를 사용 하여 데이터 베 이 스 를 방문 하 는 인터페이스 이다.
2)LoginAuthenticationSuccessHandler
package cn.luxh.app.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

/**
 *          
 * @author Luxh
 */
public class LoginAuthenticationSuccessHandler implements AuthenticationSuccessHandler{
    
    private static Logger log = LoggerFactory.getLogger(LoginAuthenticationSuccessHandler.class);
    
    //            url
    private String url;
    
    public void onAuthenticationSuccess(HttpServletRequest request,
            HttpServletResponse response, Authentication authentication) throws IOException,
            ServletException {
        log.info("      :"+request.getContextPath()+url);
        //response.sendRedirect(request.getContextPath()+url);
        request.getRequestDispatcher(url).forward(request, response);
    }
    
    public void setUrl(String url) {
        this.url = url;
    }

}

3)LoginAuthenticationFailureHandler
package cn.luxh.app.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;


/**
 *         
 * @author Luxh
 */
public class LoginAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
            HttpServletResponse response, AuthenticationException ae)
            throws IOException, ServletException {
        
        //  AuthenticationException     
        //          
        //...
        
        response.sendRedirect(request.getContextPath()+"/login");
    }

}

 
5. SpringMVC 의 Controller
1)LoginController
package cn.luxh.app.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class LoginController {
    
    private static Logger log = LoggerFactory.getLogger(LoginController.class);
    
    /**
     *     
     */
    @RequestMapping(value={"/","/login"})
    public String login(@RequestParam(required=false) String error) {
        log.info("login......");
        if("1".equals(error)) {
            log.info("    !");
        }else if("2".equals(error)) {
            log.info("       ,       !");
        }else if("3".equals(error)) {
            log.info("    !");
        }
        return "login";
    }
    
    /**
     *         url
     */
    @RequestMapping(value="/denied")
    public String denied(){
        log.info("denied......");
        return "denied";
    }
    
    /**
     *     url
     */
    @RequestMapping(value="/timeout")
    public String timedout(){
        log.info("timeout......");
        return "timedout";
    }
}

2)IndexController
package cn.luxh.app.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class IndexController {
    
    private static Logger log = LoggerFactory.getLogger(IndexController.class);
    
    /**
     *             
     */
    @RequestMapping(value="/index")
    public String index(){
        log.info("index.......");
        return "index";
    }
    
    /**
     *             
     */
    @RequestMapping(value="/common")
    public String myJsp(){
        log.info("common.......");
        return "common";
    }
    
    /**
     *        
     */
    @RequestMapping(value="/admin")
    public String admin(){
        log.info("admin.......");
        return "admin";
    }
}

  6. 소스 코드, jar 패키지 포함 하지 않 음
spring3.2.2+springsecurity3.1.3+myBatis3.2.2
http://files.cnblogs.com/luxh/app3.rar
 

좋은 웹페이지 즐겨찾기