Spring Security 4.X xml配置,草稿记录

"org.springframework.security:spring-security-web:4.1.0.RELEASE",

"org.springframework.security:spring-security-taglibs:4.1.0.RELEASE",

"org.springframework.security:spring-security-config:4.1.0.RELEASE"

配置framework-spring-security.xml

在framework-spring-mvc.xml引用其它依赖的配置文件

<!--数据库 xml -->

<import resource="dbcp-spring-framework.xml"></import>

<!--spring-security xml
-->

<import resource="framework-spring-security.xml"></import>

<beans:beans
        xmlns="http://www.springframework.org/schema/security"
        xmlns:beans="http://www.springframework.org/schema/beans"
        xmlns:p="http://www.springframework.org/schema/p"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context.xsd
          http://www.springframework.org/schema/security
              http://www.springframework.org/schema/security/spring-security.xsd">

    <context:component-scan base-package="com.framework.security"/>

    <!--<http pattern="/pm/**" security="none" />-->
    <http pattern="/login.jsp" security="none" />
    <http pattern="/common/**" security="none" />
    <http pattern="/*.ico" security="none" />

    <http  use-expressions="false" >
        <!-- IS_AUTHENTICATED_ANONYMOUSLY 匿名登录 -->
        <intercept-url pattern="/login" access="IS_AUTHENTICATED_ANONYMOUSLY" />
        <intercept-url pattern="/pm/**/*.jsp" access="ROLE_STATIC" />
        <form-login login-page="/login"    authentication-failure-url="/login?error=1" authentication-success-forward-url="/main.to" />
        <logout invalidate-session="true" logout-url="/logout"  logout-success-url="/"  />
        <http-basic/>
        <headers >
            <frame-options disabled="true"></frame-options>
        </headers>

        <csrf token-repository-ref="csrfTokenRepository" />

        <session-management session-authentication-error-url="/frame.expired" >
            <!-- max-sessions只容许一个账号登录,error-if-maximum-exceeded 后面账号登录后踢出前一个账号,expired-url session过期跳转界面 -->
            <concurrency-control max-sessions="1" error-if-maximum-exceeded="false" expired-url="/frame.expired" session-registry-ref="sessionRegistry" />
        </session-management>

        <expression-handler ref="webexpressionHandler" ></expression-handler>
    </http>

    <beans:bean id="sessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl" />

    <beans:bean id="userDetailsService" class="com.framework.security.UserDetailsServiceImpl" />

    <!--配置web端使用权限控制-->
    <beans:bean id="webexpressionHandler" class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler" />

    <authentication-manager >
        <authentication-provider ref="authenticationProvider" />
    </authentication-manager>

    <!-- 自定义userDetailsService, 盐值加密 -->
    <beans:bean id="authenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
        <beans:property name="hideUserNotFoundExceptions" value="true" />
        <beans:property name="userDetailsService" ref="userDetailsService" />
        <beans:property name="passwordEncoder" ref="passwordEncoder" />
        <beans:property name="saltSource" ref="saltSource" />
    </beans:bean>

    <!-- Md5加密 -->
    <beans:bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" />

    <!-- 盐值加密 salt对应数据库字段-->
    <beans:bean id="saltSource" class="org.springframework.security.authentication.dao.ReflectionSaltSource">
        <beans:property name="userPropertyToUse" value="salt"/>
    </beans:bean>

    <beans:bean id="csrfTokenRepository" class="org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository" />
</beans:beans>

3.编写自定义UserDetailsService

package com.framework.security;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.core.authority.AuthorityUtils;
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 org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.*;
/****
 * @author tzz
 * @功能描述
 * @date 2016/5/3
 * 修改人    修改时间   修改说明
 ****/
@Service
@Transactional(rollbackFor=Exception.class)
public class UserDetailsServiceImpl  implements UserDetailsService {
    @Resource
    CustomUserDao customUserDao;
    JdbcUserDetailsManager k;
    private Map<String, UserInfo> userMap = null;
    protected final Log logger = LogFactory.getLog(getClass());
    protected final MessageSourceAccessor messages = SpringSecurityMessageSource
            .getAccessor();
    private String usersByUsernameQuery = "SELECT account,pwd,stat,salt,id,company_id,name,login_stat,login_date ,login_ip FROM USER_ACCOUNT WHERE ACCOUNT = ?";
    private String authoritiesByUsernameQuery ="SELECT NAME,POWER_CODE FROM VW_USER_POWER WHERE ACCOUNT_ID = ?";
    public UserDetailsServiceImpl() {
        userMap = new HashMap<>();
    }

    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException, DataAccessException {
        /*SecurityContextHolder.getContext()
                .getAuthentication().getName();*/
        List<UserDetails> users = loadUsersByUsername(username);
        if (users.size() == 0) {
            logger.debug("Query returned no results for user '" + username + "'");
            throw new UsernameNotFoundException(messages.getMessage(
                    "JdbcDaoImpl.notFound", new Object[] { username },
                    "Username {0} not found"));
        }
        UserInfo user = (UserInfo)users.get(0);
       Set<GrantedAuthority> dbAuthsSet = new HashSet<>();

        dbAuthsSet.addAll(loadUserAuthorities(user.getId()));
        dbAuthsSet.add(new SimpleGrantedAuthority("ROLE_STATIC"));
        List<GrantedAuthority> dbAuths = new ArrayList<>(dbAuthsSet);

        if (dbAuths.size() == 0) {
            logger.debug("User '" + username
                    + "' has no authorities and will be treated as 'not found'");

            throw new UsernameNotFoundException(messages.getMessage(
                    "JdbcDaoImpl.noAuthority", new Object[] { username },
                    "User {0} has no GrantedAuthority"));
        }
        return createUserDetails(username,user,dbAuths);
        //return user;
    }

    protected UserDetails createUserDetails(String username,
                                            UserInfo userFromUserQuery, List<GrantedAuthority> combinedAuthorities) {
        String returnUsername = userFromUserQuery.getUsername();
        UserInfo user = new UserInfo(returnUsername,userFromUserQuery.getPassword(), userFromUserQuery.isEnabled(), true, true, true,
                combinedAuthorities);
        user.setId(userFromUserQuery.getId());
        user.setCompanyId(userFromUserQuery.getCompanyId());
        user.setName(userFromUserQuery.getName());
        user.setLoginStat(userFromUserQuery.getLoginStat());
        user.setLoginDate(userFromUserQuery.getLoginDate());
        user.setLoginIP(userFromUserQuery.getLoginIP());
        user.setSalt(userFromUserQuery.getSalt());
        return user;
    }
    /**
     * Loads authorities by executing the SQL from
     * <tt>groupAuthoritiesByUsernameQuery</tt>.
     *
     * @return a list of GrantedAuthority objects for the user
     */
    protected List<GrantedAuthority> loadUserAuthorities(int userId) {
        try {
           return customUserDao.queryForList(this.authoritiesByUsernameQuery,
                    new Object[] { userId },(rs,rowNum)-> {
                            String roleName = getRolePrefix() + rs.getString(2);
                            return new SimpleGrantedAuthority(roleName);
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public String getRolePrefix() {
        return "ROLE_";
    }
    /**
     * Loads authorities by executing the SQL from <tt>authoritiesByUsernameQuery</tt>.
     *
     * @return a list of GrantedAuthority objects for the user
     */
    protected List<UserDetails> loadUsersByUsername(String username)  {
        try {

           return customUserDao.queryForList(this.usersByUsernameQuery, new Object[] { username},
                    (rs, rowNum) -> {
                        String username1 = rs.getString(1);
                        String password = rs.getString(2);
                        boolean enabled = rs.getBoolean(3);
                        UserInfo user = new UserInfo(username1, password, enabled, true, true, true,
                                AuthorityUtils.NO_AUTHORITIES);
                        user.setSalt(rs.getString(4));
                        user.setId(rs.getInt(5));
                        user.setCompanyId(rs.getInt(6));
                        user.setName(rs.getString(7));
                        user.setLoginStat(rs.getInt(8));
                        user.setLoginDate(rs.getLong(9));
                        user.setLoginIP(rs.getString(10));
                        return user;
                    }
            );
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
spring Security 调试的时候用到

BasicAuthenticationFilter

UsernamePasswordAuthenticationFilter

BasicAuthenticationFilter

MessageDigestPasswordEncoder.isPasswordValid

package com.framework.security;
import com.framework.db.BaseDao;
import org.springframework.stereotype.Repository;
@Repository("customUserDao")
public class CustomUserDao extends BaseDao {
	public CustomUserDao() {
		super(Object.class);
	}
}
基于框架的BaseDao 

@Repository("baseDao")
public class BaseDao<T> implements BaseDaoImp<T> {
	Logger log1 = LoggerFactory.getLogger(BaseDao.class);
	@Resource(name="jdbcTemplate")
	private JdbcTemplate jdbcTemplate;

	public JdbcTemplate getJdbcTemplate(){
		return this.jdbcTemplate;
	}
	private Class<T> entityClass;  

	public BaseDao(){}

	public BaseDao(Class<T> entityClass) {
        this.entityClass = entityClass;
	}
	@Override
<span style="white-space:pre">	</span>public <T1> List<T1> queryForList(String sql, Object[] args, RowMapper<T1> rowMapper) throws DataAccessException {
 <span style="white-space:pre">		</span>return jdbcTemplate.query(sql, args,rowMapper);
 <span style="white-space:pre">	</span>}
}

自定义UserInfo对象

package com.framework.security;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;

import java.util.Collection;

/****
 * @author tzz
 * @功能描述
 * @date 2016/5/3
 * 修改人    修改时间   修改说明
 ****/
public class UserInfo extends User {
    private int id;
    private int companyId;//所属公司
    private int loginSystemId = 0;//当前登录系统ID
    private String name;//用户名称
    private int loginStat;//登录状态 1:登录 2:未登陆
    private String loginIP;//登录IP
    private long loginDate;//登录时间
    private String salt;//盐值字段
    public UserInfo(String username, String password, Collection<? extends GrantedAuthority> authorities) {
        super(username, password, authorities);
    }

    public UserInfo(String username, String password, boolean enabled, boolean accountNonExpired, 
boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) {
        super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);

    }

    public String getSalt() {
        return salt;
    }

    public void setSalt(String salt) {
        this.salt = salt;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getCompanyId() {
        return companyId;
    }

    public void setCompanyId(int companyId) {
        this.companyId = companyId;
    }

    public int getLoginSystemId() {
        return loginSystemId;
    }

    public void setLoginSystemId(int loginSystemId) {
        this.loginSystemId = loginSystemId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getLoginStat() {
        return loginStat;
    }

    public void setLoginStat(int loginStat) {
        this.loginStat = loginStat;
    }

    public String getLoginIP() {
        return loginIP;
    }

    public void setLoginIP(String loginIP) {
        this.loginIP = loginIP;
    }

    public long getLoginDate() {
        return loginDate;
    }

    public void setLoginDate(long loginDate) {
        this.loginDate = loginDate;
    }

}
时间: 2024-10-11 00:55:07

Spring Security 4.X xml配置,草稿记录的相关文章

spring管理SessionFactory中XML配置

1. 综合练习目标 2. 综合练习需求 3.模块划分 1. 综合练习目标 <1>复习 Java 基本语法 <2>熟悉掌握Java开发常用API <3>尝试建立面向对象思想 2. 综合练习需求 <1>接收用户的命令行输入 <2>以文件为基础完成数据的增删改查操作          3.模块划分 UI模块:(Java存在文本中都是以字符型式) 数据验证模块:验证用户输入是否合法 spring管理SessionFactory中XML配置,布布扣,bub

Spring装配Bean---使用xml配置

声明Bean Spring配置文件的根元素是<beans>. 在<beans>元素内,你可以放所有的Spring配置信息,包括<bean>元素的声明. 除了Beans命名空间,Spring的核心框架总共自带了10个命名空间配置:  命名空间 用途  aop     为声明切面以及将@AspectJ注解的类代理为Spring切面提供了配置元素  beans     支持声明Bean和装配Bean,是Spring最核心也是最原始的命名空间  context 为配置Sprin

Spring的配置文件ApplicationContext.xml配置头文件解析

Spring的配置文件ApplicationContext.xml配置头文件解析 原创 2016年12月16日 14:22:43 标签: spring配置文件 5446 spring中的applicationContext.xml配置头文件解析 <?xmlversion="1.0"encoding="UTF-8"?> <beansxmlns="http://www.springframework.org/schema/beans"

Spring Aop实例之xml配置

上篇博文<3幅图让你了解Spring AOP>中介绍了aop通知类型,AOP的配置方式有2种方式:xml配置和AspectJ注解方式.今天我们就来实践一下xml配置方式. http://blog.csdn.net/xiaoxian8023/article/details/17258933 我采用的jdk代理,所以首先将接口和实现类代码附上 [java] view plaincopy package com.tgb.aop; public interface UserManager { publ

spring mvc 中web.xml配置信息解释

在项目中总会遇到一些关于加载的优先级问题,近期也同样遇到过类似的,所以自己查找资料总结了下,下面有些是转载其他人的,毕竟人家写的不错,自己也就不重复造轮子了,只是略加点了自己的修饰. 首先可以肯定的是,加载顺序与它们在 web.xml 文件中的先后顺序无关.即不会因为 filter 写在 listener 的前面而会先加载 filter.最终得出的结论是:listener -> filter -> servlet 同时还存在着这样一种配置节:context-param,它用于向 Servlet

Spring MVC的web.xml配置详解(转)

出处http://blog.csdn.net/u010796790 1.spring 框架解决字符串编码问题:过滤器 CharacterEncodingFilter(filter-name) 2.在web.xml配置监听器ContextLoaderListener(listener-class) ContextLoaderListener的作用就是启动Web容器时,自动装配ApplicationContext的配置信息.因为它实现了ServletContextListener这个接口,在web.

spring注解机制和XML配置机制之间的比较

XML配置的优缺点: 优点有:1. XML配置方式进一步降低了耦合,使得应用更加容易扩展,即使对配置文件进一步修改也不需要工程进行修改和重新编译.2. 在处理大的业务量的时候,用XML配置应该更加好一些.因为XML更加清晰的表明了各个对象之间的关系,各个业务类之间的调用.同时spring的相关配置也能一目了然.当然,有人会说,用XML配置,在大的业务量时候会使得XML文件过大,不容易查看.这一点我们完全可以利用业务分解书写多个XML配置文件就可以了. 3.xml,在乎:整体业务关系:维护性. 缺

尚硅谷Spring整合Hibernate基于xml配置

描述:这是一个最简单网上书城demo. 下载地址:http://download.csdn.net/detail/u013488580/8370899 1. Spring 整合 Hibernate 整合什么 ? 1). 有 IOC 容器来管理 Hibernate 的 SessionFactory 2). 让 Hibernate 使用上 Spring 的声明式事务 2. 整合步骤: 1). 加入 hibernate ①. jar 包 ②. 添加 hibernate 的配置文件: hibernate

spring事务管理,xml配置aop事务和注解配置aop事务

xml配置和注解配合共同代码 AccountService.java public interface AccountService { //转账方法 void transfer(Integer from,Integer to,Double money); } AccountServiceImpl.java xml配置aop事务的AccountServiceImpl.java public class AccountServiceImpl implements AccountService {