一. ssm配置
1.首先在web.xml文件中配置过滤器和监听器
<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>
2.在resources文件夹下创建spring-security配置文件,还要创建验证用户名密码的方法
@Service("userService")
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements IUserService {
private final IUserDao userDao;
private final BCryptPasswordEncoder bCryptPasswordEncoder;
@Autowired
public UserServiceImpl(IUserDao userDao, BCryptPasswordEncoder bCryptPasswordEncoder) {
this.userDao = userDao;
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserInfo userInfo;
User user=null;
try {
userInfo = userDao.findByUsername(username);
if (userInfo!=null) {
user = new User(userInfo.getUsername(), userInfo.getPassword(), userInfo.getStatus() != 0,
true, true, true, getAuthority(userInfo.getRoles()));
}
} catch (Exception e) {
e.printStackTrace();
}
return user;
}
private List<SimpleGrantedAuthority> getAuthority(List<Role> roles){
List<SimpleGrantedAuthority> list=new ArrayList<>();
for (Role role : roles) {
list.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
}
return list;
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
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.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<security:global-method-security pre-post-annotations="enabled"
jsr250-annotations="enabled" secured-annotations="enabled"/>
<!-- 配置不拦截的资源 -->
<security:http pattern="/login.jsp" security="none"/>
<security:http pattern="/failer.jsp" security="none"/>
<security:http pattern="/css/**" security="none"/>
<security:http pattern="/img/**" security="none"/>
<security:http pattern="/plugins/**" security="none"/>
<security:http auto-config="true" use-expressions="true">
<!-- 配置具体的拦截的规则 pattern="请求路径的规则" access="访问系统的人,必须有ROLE_USER的角色" -->
<security:intercept-url pattern="/**" access="isAuthenticated()"/>
<!-- 定义跳转的具体的页面 -->
<security:form-login
login-page="/login.jsp"
login-processing-url="/login.do"
default-target-url="/index.jsp"
authentication-failure-url="/failer.jsp"
authentication-success-forward-url="/pages/main.jsp"
/>
<!-- 关闭跨域请求 -->
<security:csrf disabled="true"/>
<!-- 退出 -->
<security:logout invalidate-session="true" logout-url="/logout.do" logout-success-url="/login.jsp"/>
</security:http>
<!-- 切换成数据库中的用户名和密码 -->
<security:authentication-manager>
<security:authentication-provider user-service-ref="userService">
<!-- 配置加密的方式-->
<security:password-encoder ref="passwordEncoder"/>
</security:authentication-provider>
</security:authentication-manager>
<!-- 配置加密类 -->
<bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
</beans>
这是使用加密类的配置方式,如果不使用加密类,可把<security:authentication-manager>替换成如下所示,
注意:使用springsecurity5,需要加上{noop}指定使用NoOpPasswordEncoder给DelegatingPasswordEncoder去校验密码,这样我们再配置前端登录就可以了
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user name="user" password="{noop}user"
authorities="ROLE_USER" />
<security:user name="admin" password="{noop}admin"
authorities="ROLE_ADMIN" />
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
二.springBoot配置
1.springBoot配置起来就简单许多了,我们先配置一个不加密的
package com.logoxiang.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
/**
* @Author: logoxiang
* @Date: 2019/2/14 9:21
*/
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 配置拦截器保护请求
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.headers().frameOptions().sameOrigin().and().csrf() .disable().authorizeRequests()
.antMatchers("/admin/**").hasRole("USER")/*与之匹配的请求/用户/*要求对用户进行身份验证,并且必须与用户角色*/
.anyRequest().permitAll().and().
formLogin()
.loginPage("/login.html").loginProcessingUrl("/denglu").
defaultSuccessUrl("/admin/index.html").failureUrl("/login.html").and().logout().logoutSuccessUrl("/login.html");
}
/**
* 配置user-detail服务
* @param auth
* @throws Exception
*/
@Autowired
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder())
.withUser("logoxiang").password("1234").roles("USER");
}
}
public class MyPasswordEncoder implements PasswordEncoder {
@Override
public String encode(CharSequence charSequence) {
return charSequence.toString();
}
@Override
public boolean matches(CharSequence charSequence, String s) {
return s.equals(charSequence.toString());
}
}
2.再配置一个加密的:
@Component
public class UserDetailsConfig implements UserDetailsService {
@Autowired
private SellerService sellerService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException{
List<GrantedAuthority> grantAuths = new ArrayList();
grantAuths.add(new SimpleGrantedAuthority("USER"));
TbSeller seller = sellerService.findOne(username);
if(seller != null){
if(seller.getStatus().equals("1")){
return new User(username,seller.getPassword(),grantAuths );
}else{
return null;
}
}
return null ;
}
}
@Configuration
public class BcryptEncoderConfig {
@Bean
public BCryptPasswordEncoder createB(){
return new BCryptPasswordEncoder();
}
}
这个我写的有点不完善,待更