使用SpringBoot2.0 整合SpringSecurity加入kaptcha验证码,使用redis实现session共享,请看源码,附上数据库脚本,绝对可以跑起来,源码地址为https://github.com/xueqinggit/SpringCloudLearn
4.0.0
com.xueqing.demo
spring-boot-security
0.0.1-SNAPSHOT
jar
spring-boot-security
Demo project for Spring Boot
org.springframework.boot
spring-boot-starter-parent
2.0.3.RELEASE
UTF-8
UTF-8
1.8
-Dfile.encoding=UTF-8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-devtools
org.springframework.boot
spring-boot-starter-jdbc
org.springframework.boot
spring-boot-starter-test
test
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.1
org.springframework.boot
spring-boot-starter-cache
org.springframework.boot
spring-boot-starter-data-redis
org.springframework.session
spring-session-data-redis
mysql
mysql-connector-java
8.0.11
org.springframework.boot
spring-boot-starter-security
org.springframework.boot
spring-boot-starter-thymeleaf
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.1
com.github.axet
kaptcha
0.0.9
org.springframework.boot
spring-boot-maven-plugin
package com.xueqing.demo.springbootsecurity.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) //开启方法权限控制
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
auth.userDetailsService(customUserDetailsService())
.passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
// 所有用户均可访问的资源
.antMatchers( "/favicon.ico","/css/**","/common/**","/js/**","/images/**","/captcha.jpg","/login","/userLogin","/login-error").permitAll()
// 任何尚未匹配的URL只需要验证用户即可访问
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").successForwardUrl("/index").failureForwardUrl("/login?error=1")
.and()
//权限拒绝的页面
.exceptionHandling().accessDeniedPage("/403");
http.logout().logoutSuccessUrl("/login");
}
/**
* 设置用户密码的加密方式
* @return
*/
@Bean
public Md5PasswordEncoder passwordEncoder() {
return new Md5PasswordEncoder();
}
/**
* 自定义UserDetailsService,授权
* @return
*/
@Bean
public CustomUserDetailsService customUserDetailsService(){
return new CustomUserDetailsService();
}
/**
* AuthenticationManager
* @return
* @throws Exception
*/
@Bean(name = BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
package com.xueqing.demo.springbootsecurity.security;
import com.xueqing.demo.springbootsecurity.bean.Menu;
import com.xueqing.demo.springbootsecurity.bean.User;
import com.xueqing.demo.springbootsecurity.service.MenuService;
import com.xueqing.demo.springbootsecurity.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
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 java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* 认证和授权
*/
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserService userService;
@Autowired
private MenuService menuService;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
//--------------------认证账号
User user = userService.loadUserByUsername(s);
if (user == null) {
throw new UsernameNotFoundException("账号不存在");
}
//-------------------开始授权
List
package com.xueqing.demo.springbootsecurity.security;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* 自定义密码比较器 3
* 在此 密码我就不加密了
*/
public class Md5PasswordEncoder implements PasswordEncoder {
@Override
public String encode(CharSequence charSequence) {
return charSequence.toString();
}
@Override
public boolean matches(CharSequence charSequence, String s) {
return s.equals(charSequence);
}
}
package com.xueqing.demo.springbootsecurity.security;
import com.xueqing.demo.springbootsecurity.bean.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import java.util.Collection;
public class SecurityUtils {
public static Authentication getAuthentication() {
return SecurityContextHolder.getContext().getAuthentication();
}
public static Collection extends GrantedAuthority> getAllPermission(){
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Collection extends GrantedAuthority> authorities = authentication.getAuthorities();
return authorities;
}
public static boolean hasPermission(String permission){
if(StringUtils.isEmpty(permission)){
return false;
}
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Collection extends GrantedAuthority> authorities = authentication.getAuthorities();
boolean hasPermission = false;
for(GrantedAuthority grantedAuthority : authorities){
String authority = grantedAuthority.getAuthority();
if(authority.equals(permission)){
hasPermission =true;
}
}
return hasPermission;
}
public static User getUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return (User) authentication.getPrincipal();
}
public static void logout(){
SecurityContextHolder.clearContext();
}
}
package com.xueqing.demo.springbootsecurity.controller;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.xueqing.demo.springbootsecurity.bean.R;
import com.xueqing.demo.springbootsecurity.bean.User;
import com.xueqing.demo.springbootsecurity.service.UserService;
import com.xueqing.demo.springbootsecurity.util.ConstantVal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
@Controller
public class LoginController {
@Autowired
private AuthenticationManager myAuthenticationManager;
@Autowired
DefaultKaptcha defaultKaptcha;
@RequestMapping(value = "/userLogin")
public String userLogin(HttpServletRequest request) {
User userInfo = new User();
String username = request.getParameter("username");
String password = request.getParameter("password");
String kaptcha = request.getParameter("kaptcha");
userInfo.setUsername(username);
userInfo.setPassword(password);
String s = request.getSession().getAttribute(ConstantVal.CHECK_CODE).toString();
if (StringUtils.isEmpty(kaptcha) || !s.equals(kaptcha)) {
return "redirect:login-error?error=1";
}
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, password);
try{
//使用SpringSecurity拦截登陆请求 进行认证和授权
Authentication authenticate = myAuthenticationManager.authenticate(usernamePasswordAuthenticationToken);
SecurityContextHolder.getContext().setAuthentication(authenticate);
//使用redis session共享
HttpSession session = request.getSession();
session.setAttribute("SPRING_SECURITY_CONTEXT", SecurityContextHolder.getContext()); // 这个非常重要,否则验证后将无法登陆
}catch (Exception e){
e.printStackTrace();
return "redirect:login-error?error=2";
}
return "redirect:index";
}
@RequestMapping("/captcha.jpg")
@ResponseBody
public R applyCheckCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
R r = new R();
response.setHeader("Cache-Control", "no-store, no-cache");
response.setContentType("image/jpeg");
//生成文字验证码
String text = defaultKaptcha.createText();
//生成图片验证码
BufferedImage image = defaultKaptcha.createImage(text);
//保存到session
request.getSession().setAttribute(ConstantVal.CHECK_CODE, text);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(image, "jpg", out);
return r;
}
}
user登陆的界面为
admin登陆的界面为
user用户操作用户新增、删除、修改、都改显示没权限,而admin可以