• Spring security 在项目中的使用第二篇之代码实现阶段


    第二步:我们给Spring ecurity 准备所需要的方法用来获取必须数据

    public interface UserDao extends GenericDao<User>{

    /**

    * 通过用户名获取唯一用户

    * @param userName

    * @return  用户

    */

       public User findUniqueBy(String userName);

    }

    public interface PermissionsDao  extends GenericDao<Permissions> {

    /**

    * 查询所有的权限

    * @return List<Permissions>

    */

        List<Permissions> findPermissionsAll();

    }

    // Spring security 所需要的
    public interface ResourceDetailsService {
    /**
    * 返回需要被拦截(保护)的 url 和 访问该 url 对应的权限的字符串, 若对应多个权限, 这些权限的名字有 ','  分隔
    * @return
    */
    public LinkedHashMap<String, String> buildSrcMap();
    }
    UserDetailsServiceImpl.java 
    /**
     * UserDetaialServiceImpl 实现自spring security UserDeailService
     * 获取当spring security 中的用户和 拥有的角色
     */
    public class UserDetailsServiceImpl implements UserDetailsService {
    private UserDao userDao;
     
    public UserDetails loadUserByUsername(String userName)
    throws UsernameNotFoundException, DataAccessException {
    User user = null;
    com.wlzx.domain.User nuser =userDao.findUniqueBy(userName);
    if(null==nuser){
    throw new UsernameNotFoundException("");
    }
    else{
    String name = nuser.getUserName();
    String pwd =nuser.getPassword();
    boolean enabled = 0==nuser.getDisabled();
    boolean accountNonExpired = true;
    boolean credentialsNonExpired = true;
    boolean accountNonLocked = true;
    Set<String> authSet = new HashSet<String>();
     
    for(Role role:nuser.getRoles()){
    authSet.add(role.getRo_name()); // 存放角色名
    }
    //保存当前的用户角色
    GrantedAuthority[] authorities = new GrantedAuthority[authSet.size()];
    int i = 0;
    for(String roleName: authSet){
    authorities[i++] = new GrantedAuthorityImpl(roleName);
    }
    user=new User(name, pwd, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
    }
    return user;
    }
    public UserDao getUserDao() {
    return userDao;
    }
    public void setUserDao(UserDao userDao) {
    this.userDao = userDao;
    }
     
    }
    ResourceDetailsServiceImpl.java
    public class ResourceDetailsServiceImpl implements ResourceDetailsService {
    private PermissionsDao permissionsDao;
    public LinkedHashMap<String, String> buildSrcMap() {
    LinkedHashMap<String, String> srcMap = new LinkedHashMap<String, String>();
    List<Permissions> pers = permissionsDao.findPermissionsAll();
    if(pers != null){
    for(Permissions per: pers){
    String url = per.getPer_name(); //需要保护的url 如actions/loginAction.action
    List<String> namelist=new ArrayList<String>();
    for(Role role:per.getRoles()){
    namelist.add(role.getRo_name()); // 角色名
    }
    //用,把角色名分开
    String roleNames= StringUtils.join(namelist, ",");
    //保存permission的名字(url)和角色名
    srcMap.put(url, roleNames);
    }
    }
    return srcMap;
    }
    public PermissionsDao getPermissionsDao() {
    return permissionsDao;
    }
    public void setPermissionsDao(PermissionsDao permissionsDao) {
    this.permissionsDao = permissionsDao;
    }
     
    }
    ObjectDefinitionSourceBean.java
    public class ObjectDefinitionSourceBean implements FactoryBean {
    private ResourceDetailsService resourceDetailsService;
    public void setResourceDetailsService(
    ResourceDetailsService resourceDetailsService) {
    this.resourceDetailsService = resourceDetailsService;
    }
    private UrlMatcher getUrlMatcher(){
    return new AntUrlPathMatcher();
    }
    public Object getObject() throws Exception {
    DefaultFilterInvocationDefinitionSource definitionSource = null;
    LinkedHashMap<String, String> srcMap = resourceDetailsService.buildSrcMap();
    LinkedHashMap<RequestKey, Object> requestMap = new LinkedHashMap<RequestKey, Object>(); 
    UrlMatcher matcher = getUrlMatcher();
    ConfigAttributeEditor editor = new ConfigAttributeEditor();
    for(Map.Entry<String, String> entity: srcMap.entrySet()){
    String path = entity.getKey();
    String access = entity.getValue();
    RequestKey requestKey = new RequestKey(path);
    if(!StringUtils.isEmpty(access)){
    editor.setAsText(access);
    requestMap.put(requestKey, editor.getValue());
    }else{
    requestMap.put(requestKey, ConfigAttributeDefinition.NO_ATTRIBUTES);
    }
    }
    definitionSource = new DefaultFilterInvocationDefinitionSource(matcher, requestMap);
    return definitionSource;
    }
    public Class getObjectType() {
     
    return ObjectDefinitionSource.class;
    }
    public boolean isSingleton() {
     
    return true;
    }
    }

    applicationContext-security.xml

    <?xml version="1.0" encoding="UTF-8"?>

    <beans:beans xmlns="http://www.springframework.org/schema/security"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xmlns:beans="http://www.springframework.org/schema/beans"

    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-2.0.2.xsd">

    <!-- 配置 spring-security 的安全属性 -->

    <!-- 配置登录页面 -->

    <http auto-config='true'>

           <form-login login-page="/login.jsp"   always-use-default-target="true" authentication-failure-url="/login.jsp" default-target-url="/actions/loginAction.action" /> 

         </http> 

        <authentication-provider user-service-ref="userDetailsService"/>

    <beans:bean id="userDetailsService" class="com.wlzx.service.UserDetailsServiceImpl">

    <beans:property name="userDao" ref="userDao"/>

    </beans:bean>

    <beans:bean id="resourceDetailsService" class="com.wlzx.service.ResourceDetailsServiceImpl">

    <beans:property name="permissionsDao" ref="permissionsDao"/>

    </beans:bean>

    <beans:bean id="objectDefinitionSource" class="com.wlzx.security.ObjectDefinitionSourceBean">

    <beans:property name="resourceDetailsService" ref="resourceDetailsService"/>

    </beans:bean>

    <beans:bean class="org.springframework.security.intercept.web.FilterSecurityInterceptor" autowire="byType">

    <beans:property name="objectDefinitionSource" ref="objectDefinitionSource"/>

    <custom-filter before="FILTER_SECURITY_INTERCEPTOR"/>

    </beans:bean>

    </beans:beans>

    web.xml

    <!-- 配置 spring-security 的  Filter 代理类  -->

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

    <!-- 无权限访问页面 -->

    <error-page>

    <error-code>403</error-code>

    <location>/common/403.jsp</location>

    </error-page>

    login.jsp

    <form action="j_spring_security_check" method="post" name="loginForm" id="loginForm">

      <input type="text" name="j_username" id="j_username">

      <input type="password" name="j_password" id="j_password">

    项目构架图:以上实体类按上边的说明放到项目中即可。

    没有权限提示:

    在数据库插入role时 role_name一定要是大写

  • 相关阅读:
    Spring
    vue实现大文件上传下载
    javascript实现大文件上传下载
    js实现大文件上传下载
    php实现大文件上传下载
    jsp实现大文件上传下载
    java实现大文件上传下载
    java实现大文件上传功能
    百度ueditor编辑器 复制word里面带图文的文章,图片可以直接显示
    百度ueditor 复制word里面带图文的文章,图片可以直接显示
  • 原文地址:https://www.cnblogs.com/java20130726/p/3218405.html
Copyright © 2020-2023  润新知