仅供自己所需,绝大多数参考 https://blog.csdn.net/larger5/article/details/81063438
部分参考 https://blog.csdn.net/ech13an/article/details/80779973
我这个是没用自带的登录方法,因此登录成功的操作是在我自己写的接口里的,如果使用了框架带的,就是在注释为:登录成功的地方设置操作
package com.example.entry.security.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
public class SpringSecurityConf extends WebSecurityConfigurerAdapter {
@Autowired
AjaxAuthenticationEntryPoint authenticationEntryPoint; // 未登陆时返回 JSON 格式的数据给前端(否则为 html)
@Autowired
AjaxAuthenticationSuccessHandler authenticationSuccessHandler; // 登录成功返回的 JSON 格式数据给前端(否则为 html)
@Autowired
AjaxAuthenticationFailureHandler authenticationFailureHandler; // 登录失败返回的 JSON 格式数据给前端(否则为 html)
@Autowired
AjaxLogoutSuccessHandler logoutSuccessHandler; // 注销成功返回的 JSON 格式数据给前端(否则为 登录时的 html)
@Autowired
AjaxAccessDeniedHandler accessDeniedHandler; // 无权访问返回的 JSON 格式数据给前端(否则为 403 html 页面)
@Autowired
SelfUserDetailsService userDetailsService; // 自定义user
@Autowired
JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter; // JWT 拦截器
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 加入自定义的安全认证
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
/**
* 密码加密
*/
@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.cors().and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 使用 JWT,关闭token
.and()
.httpBasic().authenticationEntryPoint(authenticationEntryPoint)
.and()
.authorizeRequests()
// 放行公共资源与登录接口
.antMatchers("/swagger-ui.html/**").permitAll()
.antMatchers("/webjars/**").permitAll()
.antMatchers("/v2/**").permitAll()
.antMatchers("/swagger-resources/**") .permitAll()
.antMatchers("/Location/**").permitAll()
.antMatchers("/**/partyFile").permitAll()
.antMatchers("/screen/**").permitAll()
.antMatchers("/**/upload").permitAll()
.antMatchers("/#/login").permitAll()
.antMatchers("/**/readFile/partyFile/**").permitAll()
.antMatchers("/**/LoginPC").permitAll()
.antMatchers("/**/LoginPhone").permitAll()
.antMatchers("/**/mac").hasAuthority("ADMIN") // 如果有需要权限的最好放在这最后面
.anyRequest()
.access("@rbacauthorityservice.hasPermission(request,authentication)"); // RBAC 动态 url 认证
// .and() 不使用自带的登录方法
// .formLogin() //开启登录
// .usernameParameter("userPhone") // 下面登录接口使用的接收参数名(默认username)
// .passwordParameter("password")
// .loginProcessingUrl("/tb-user/Login")
// .successHandler(authenticationSuccessHandler) // 登录成功
// .failureHandler(authenticationFailureHandler) // 登录失败
// .permitAll()
// .and()
// .logout()
// .logoutSuccessHandler(logoutSuccessHandler)
// .permitAll();
// 记住我
/* http.rememberMe().rememberMeParameter("remember-me")
.userDetailsService(userDetailsService).tokenValiditySeconds(300);*/
http.exceptionHandling().accessDeniedHandler(accessDeniedHandler); // 无权访问 JSON 格式的数据
http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class); // JWT Filter
}
}
上面用到的RBAC 动态 url 认证
package com.example.entry.security.config;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.Set;
@Component("rbacauthorityservice")
public class RbacAuthorityService {
public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
Object userInfo = authentication.getPrincipal();
boolean hasPermission = false;
if (userInfo instanceof UserDetails) {
String username = ((UserDetails) userInfo).getUsername();
//获取资源
Set<String> urls = new HashSet();
urls.add("/common/**");
urls.add("/**/**"); // 这些 url 都是要登录后才能访问,且其他的 url 都不能访问!
Set set2 = new HashSet();
Set set3 = new HashSet();
AntPathMatcher antPathMatcher = new AntPathMatcher();
System.out.println(request.getRequestURI());
for (String url : urls) {
if (antPathMatcher.match(url, request.getRequestURI())) {
hasPermission = true;
break;
}
}
return hasPermission;
} else {
return false;
}
}
}
jwt拦截器
这里设置了jwt前面是需要加个 Bearer和空格
package com.example.entry.security.config;
import com.example.entry.utis.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
@Autowired
SelfUserDetailsService userDetailsService;
@Autowired
AjaxAuthenticationEntryPoint authenticationEntryPoint;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
String authHeader = request.getHeader("Token");
// 如果请求头中有Token;Login不要传
if (authHeader != null && authHeader.startsWith("Bearer ")) {
final String authToken = authHeader.substring("Bearer ".length());
try {
String username = JwtTokenUtil.parseJWT(authToken);
System.out.println("username:"+username);
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
if (userDetails != null) {
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,DELETE,PUT,HEAD");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, Token, access_token");
chain.doFilter(request, response);
}
}
jwt拦截器里面用到的loadUserByUsername方法
package com.example.entry.security.config;
import com.example.entry.mapper.UserMapper;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
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.Component;
import java.util.HashSet;
import java.util.Set;
@Component
public class SelfUserDetailsService implements UserDetailsService {
@Autowired
UserMapper userMapper;
@SneakyThrows
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//构建用户信息的逻辑(取数据库/LDAP等用户信息)
SelfUserDetails userInfo = new SelfUserDetails();
String password = userMapper.getPassword(username);
if (StringUtils.isBlank(password)) {
return null;
}
userInfo.setUsername(username);
userInfo.setPassword(password);
Set authoritiesSet = new HashSet();
String role=userMapper.getRole(username);
/* String role="ADMIN";*/
GrantedAuthority authority = new SimpleGrantedAuthority(role);
authoritiesSet.add(authority);
userInfo.setAuthorities(authoritiesSet);
return userInfo;
}
}
package com.example.entry.utis;
import cn.hutool.core.codec.Base64;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class JwtTokenUtil {
private static InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("jwt.jks"); // 寻找证书文件
private static PrivateKey privateKey = null;
private static PublicKey publicKey = null;
public static String key = "XXX";
static { // 将证书文件里边的私钥公钥拿出来
try {
KeyStore keyStore = KeyStore.getInstance("JKS"); // java key store 固定常量
keyStore.load(inputStream, "123456".toCharArray());
privateKey = (PrivateKey) keyStore.getKey("jwt", "123456".toCharArray()); // jwt 为 命令生成整数文件时的别名
publicKey = keyStore.getCertificate("jwt").getPublicKey();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 用户登录成功后生成Jwt
* 使用Hs256算法 私匙使用用户密码
*
* @return
*/
public static String createJWT(String userPhone,String role) {
//指定签名的时候使用的签名算法,也就是header那部分,jjwt已经将这部分内容封装好了。
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
//生成JWT的时间
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
//创建payload的私有声明(根据特定的业务需要添加,如果要拿这个做验证,一般是需要和jwt的接收方提前沟通好验证方式的)
Map<String, Object> claims = new HashMap<String, Object>();
// claims.put("id", userId);
claims.put("role", role);
// claims.put("password", password);
String key = "XXX";
//下面就是在为payload添加各种标准声明和私有声明了
//这里其实就是new一个JwtBuilder,设置jwt的body
JwtBuilder builder = Jwts.builder()
//如果有私有声明,一定要先设置这个自己创建的私有的声明,这个是给builder的claim赋值,一旦写在标准的声明赋值之后,就是覆盖了那些标准的声明的
.setClaims(claims)
//设置jti(JWT ID):是JWT的唯一标识,根据业务需要,这个可以设置为一个不重复的值,主要用来作为一次性token,从而回避重放攻击。
// .setId(userId)
//iat: jwt的签发时间
.setIssuedAt(now)
//代表这个JWT的主体,即它的所有人,这个是一个json格式的字符串,可以存放什么userid,roldid之类的,作为什么用户的唯一标志。
.setSubject(userPhone)
//设置签名使用的签名算法和签名使用的秘钥
.signWith(signatureAlgorithm, Base64.encode(key.getBytes()));
long expMillis = nowMillis + (1000 * 60 * 60);
Date exp = new Date(expMillis);
//设置过期时间
builder.setExpiration(exp);
return builder.compact();
}
/**
* Token的解密
*
* @param token 加密后的token
* @return
*/
public static String parseJWT(String token) {
//得到DefaultJwtParser
Claims claims = Jwts.parser()
//设置签名的秘钥
.setSigningKey(Base64.encode(key.getBytes()))
//设置需要解析的jwt
.parseClaimsJws(token).getBody();
return claims.getSubject();
}
public static String parseRole(String token) {
//得到DefaultJwtParser
Claims claims = Jwts.parser()
//设置签名的秘钥
.setSigningKey(Base64.encode(key.getBytes()))
//设置需要解析的jwt
.parseClaimsJws(token).getBody();
return claims.get("role").toString();
}
}
在登录接口,所有的判断完成后就可以
String jwtToken = JwtTokenUtil.createJWT(user.getUserPhone(),user.getRoleId());
如果还想存储用户其他的信息,如密码什么的,就在createJWT方法里设置就好了,在调一下解析的就好了。
之后需要用到登录用户本人信息就可以不用查询了,直接从jwt中解析出来就可以操作了。
有兴趣的可以自己搞成工具类,就是需要去掉queryUserIdByUserPhone。
public Map getUserIdByToken(Map map , HttpServletRequest request){
String token = request.getHeader("Token");
token = token.substring("Bearer ".length());
String userPhone = JwtTokenUtil.parseJWT(token);
userPhone = userPhone == null ? "" : userPhone;
String userId = tbUserMapper.queryUserIdByUserPhone(userPhone);
map.put("userPhone",userPhone);
map.put("userId",userId);
return map;
}