其整提框架和之前博客纯Java配置一样,在之前代码上进行二次开发主要改动为:
pom.xml
<!-- Spring and security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
SecurityConfig.java
package com.niugang;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
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.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@Configuration // 里面已经包含了@Component 所以不用再上下文中在引入入了
@EnableWebSecurity
@ComponentScan("com.niugang.service")
/**
* WebSecurityConfig类使用了@EnableWebSecurity注解 ,以启用Spring
* Security的Web安全支持,并提供Spring
* MVC集成。它还扩展了WebSecurityConfigurerAdapter,并覆盖了一些方法来设置Web安全配置的一些细节。
*
* WebSecurityConfigurerAdapter 提供了一种便利的方式去创建 WebSecurityConfigurer的实例,只需要重写
* WebSecurityConfigurerAdapter 的方法,即可配置拦截什么URL、设置什么权限等安全控制。
*
*/
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//spring自带的
@Autowired
private UserDetailsService userDetailsService;
/**
* configure(HttpSecurity)方法定义了哪些URL路径应该被保护
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()// 该方法所返回的对象的方法来配置请求级别的安全细节
.antMatchers("/login").permitAll()// 登录页面不拦截
.antMatchers(HttpMethod.POST, "/checkLogin").permitAll().anyRequest().authenticated()// 对于登录路径不进行拦截
.and().formLogin()// 配置登录页面
.loginPage("/login")// 登录页面的访问路径;
.loginProcessingUrl("/checkLogin")// 登录页面下表单提交的路径
.failureUrl("/login")// 登录失败后跳转的路径
.defaultSuccessUrl("/index")// 登录成功后默认跳转的路径;
.and().logout()// 用户退出操作
.logoutUrl("/logout")// 用户退出所访问的路径,需要使用Post方式
.permitAll().logoutSuccessUrl("/login?logout=true").and().csrf().disable();
}
/**
* 忽略静态资源
*/
/*
* @Override public void configure(WebSecurity web) throws Exception {
* web.ignoring().antMatchers("/static/*"); }
*/
/**
* 配置自定义用户服务
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
/**
* 密码加密
*/
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
UserDetailsServiceImpl.java 主要用于检测用户是否在数据库里已经存在
package com.niugang.service;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.security.core.GrantedAuthority;
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.stereotype.Service;
import com.niugang.entity.User;
/**
* 授权认证业务类
*
* @author niugang UserDetailsService spring security包里面的
* 重写loadUserByUsername方法
*
*/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
//UserService自定义的,从数据查询信息
@Resource
private UserService userService;
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = new User();
user.setName(username);
// 查询用户是否存在
List<User> queryList = userService.queryList(user);
if (queryList != null & queryList.size() == 1) {
// 查询用户拥有的角色
List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
list.add(new SimpleGrantedAuthority("ROLE_"));
org.springframework.security.core.userdetails.User authUser = new org.springframework.security.core.userdetails.User(
queryList.get(0).getName(), queryList.get(0).getPassword(), list);
return authUser;
} else {
throw new UsernameNotFoundException("用户不存在");
}
}
}
UserService.java
package com.niugang.service;
import java.util.List;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.niugang.dao.UserDao;
import com.niugang.entity.User;
@Service
public class UserService {
private static Logger logger = LoggerFactory.getLogger(UserService.class);
@Resource
private UserDao userDao;
public List<User> queryList(User user) {
logger.info("访问queryList方法");
return userDao.queryList(user);
}
@Transactional
public void save(User user) {
logger.info("访问save方法");
//调用密码加密方法
encryptPassword(user);
userDao.save(user);
// throw new ServiceException("业务层异常处理");
}
public User get(Integer id) {
logger.info("访问get方法");
return userDao.get(id);
}
public void delete(Integer id) {
logger.info("访问delete方法");
userDao.delete(id);
}
/**
* 加密密码
*/
private void encryptPassword(User userEntity){
String password = userEntity.getPassword();
password = new BCryptPasswordEncoder().encode(password);
userEntity.setPassword(password);
}
}
contorller部分代码
@Resource
private UserService userService;
//spring自带的
@Autowired(required=true)
private UserDetailsService userDetailsService;
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String tologin() {
return "login";
}
@RequestMapping(value = "/logout")
public String logout() {
return "login";
}
//用户登录检测
@RequestMapping(value = "/checkLogin", method = RequestMethod.GET)
public void checkLogin(String username,String password) {
userDetailsService.loadUserByUsername(username);
}
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<#if (SPRING_SECURITY_LAST_EXCEPTION.message)??>
用户名或密码错误
</#if>
<form action="checkLogin" method="post">
用户名:<input name="username" type="text"><br>
密码:<input
name="password" type="password"><br>
<input
type="submit" value="登录">
</form>
</body>
</html>
运行代码
http://localhost:8080/6_springjavaconfig_security/index 因为没有登录,所以会跳转到登录页面
只有登录成功才能进行其他操作。
微信公众号