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