A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© lty123 初级黑马   /  2019-6-21 19:35  /  727 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

创建UserDetailServiceImpl类继承自带的UserDetailService接口

public class UserDetailServiceImpl implements UserDetailsService {
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        System.out.println("经过了!!!!!!!!!");
        //这个是角色集合,实际应该从数据库中查询角色
        List<GrantedAuthority> grantedAuthorities =new ArrayList<GrantedAuthority>();
        grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        //密码应该是在数据库中查询,UserDetails的实现类就是User
        return new User(s,"$2a$10$qHUggJayZl5JYfg2xIb3xu1QKPFc6XmBRLVkMBUQ/sn79EXGWUPDe",grantedAuthorities);
    }
}


在spring配置文件中配置
    <!--开放被拦截的权限-->
    <http pattern="/login.html" security="none"></http>
    <http pattern="/login_err.html" security="none"></http>
    <!--页面拦截规则-->
    <http>
        <!--拦截webapp下及其子目录下的所有资源-->
        <intercept-url pattern="/**" access="hasRole('ROLE_ADMIN')"></intercept-url>
        <!--登录-->
        <form-login login-page="/login.html" default-target-url="/index.html" authentication-failure-url="/login_err.html"/>
        <!--退出登录-->
        <logout/>
        <!--关闭csrf验证,跨站请求伪造-->
        <csrf disabled="true"/>
    </http>
    <!--认证管理器-->
    <authentication-manager>
        <!--服务提供者-->
        <authentication-provider user-service-ref="detailService">
            <password-encoder ref="bCryptPasswordEncoder"/>
        </authentication-provider>
    </authentication-manager>

    <beans:bean id="detailService" class="com.service.UserDetailServiceImpl"></beans:bean>
    <beans:bean id="bCryptPasswordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"></beans:bean>
</beans:beans>

在web.xml中配置
要加载在pringmvc配置之前

<!--<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-security.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    -->
    <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>

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马