前言:
本文章包含Security的认证和授权方法
并且在执行Security之前会执行自已编写的PowerFilter过滤器
而且登录信息会存入Redis,也会从Redis取
本文章只是加各种根据类
使用方法前往:https://www.0po.cn/archives/26
需要注意:
- SecurityConfig,45行需要改成你的登录接口地址
- LoginUser,需要改动一些东西,注意看注释
- PowerFilter,为自已的拦截器,在执行Security之前会执行自已编写的PowerFilter过滤器,可以按需改动,也可不动
- 一个个加类过程中,如果那个类里面报错了,不用管,先加完所有类。
- 加完后,在看报错的类,不出意外都是引入的包是我的com.zb报的错,改成你的包
依赖
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-security</artifactId>
- </dependency>
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>fastjson</artifactId>
- <version>1.2.33</version>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-redis</artifactId>
- </dependency>
- <dependency>
- <groupId>io.jsonwebtoken</groupId>
- <artifactId>jjwt</artifactId>
- <version>0.9.0</version>
- </dependency>
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- <version>1.18.10</version>
- </dependency>
需要的工具类
新建config包,第一部分开始
FastJsonRedisSerializer
- package com.zb.config;
- import com.alibaba.fastjson.JSON;
- import com.alibaba.fastjson.parser.ParserConfig;
- import com.alibaba.fastjson.serializer.SerializerFeature;
- import com.fasterxml.jackson.databind.JavaType;
- import com.fasterxml.jackson.databind.type.TypeFactory;
- import org.springframework.data.redis.serializer.RedisSerializer;
- import org.springframework.data.redis.serializer.SerializationException;
- import java.nio.charset.Charset;
- /**
- * Redis使用FastJson序列化
- *
- * @author sg
- */
- public class FastJsonRedisSerializer<T> implements RedisSerializer<T>
- {
- public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
- private Class<T> clazz;
- static
- {
- ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
- }
- public FastJsonRedisSerializer(Class<T> clazz)
- {
- super();
- this.clazz = clazz;
- }
- @Override
- public byte[] serialize(T t) throws SerializationException
- {
- if (t == null)
- {
- return new byte[0];
- }
- return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
- }
- @Override
- public T deserialize(byte[] bytes) throws SerializationException
- {
- if (bytes == null || bytes.length <= 0)
- {
- return null;
- }
- String str = new String(bytes, DEFAULT_CHARSET);
- return JSON.parseObject(str, clazz);
- }
- protected JavaType getJavaType(Class<?> clazz)
- {
- return TypeFactory.defaultInstance().constructType(clazz);
- }
- }
JwtUtil
- package com.zb.config;
- import io.jsonwebtoken.Claims;
- import io.jsonwebtoken.JwtBuilder;
- import io.jsonwebtoken.Jwts;
- import io.jsonwebtoken.SignatureAlgorithm;
- import javax.crypto.SecretKey;
- import javax.crypto.spec.SecretKeySpec;
- import java.util.Base64;
- import java.util.Date;
- import java.util.UUID;
- /**
- * JWT工具类
- */
- public class JwtUtil {
- //有效期为
- public static final Long JWT_TTL = 60 * 60 *1000L;// 60 * 60 *1000 一个小时
- //设置秘钥明文
- public static final String JWT_KEY = "abcd";
- public static String getUUID(){
- String token = UUID.randomUUID().toString().replaceAll("-", "");
- return token;
- }
- /**
- * 生成jtw
- * @param subject token中要存放的数据(json格式)
- * @return
- */
- public static String createJWT(String subject) {
- JwtBuilder builder = getJwtBuilder(subject, null, getUUID());// 设置过期时间
- return builder.compact();
- }
- /**
- * 生成jtw
- * @param subject token中要存放的数据(json格式)
- * @param ttlMillis token超时时间
- * @return
- */
- public static String createJWT(String subject, Long ttlMillis) {
- JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID());// 设置过期时间
- return builder.compact();
- }
- private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) {
- SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
- SecretKey secretKey = generalKey();
- long nowMillis = System.currentTimeMillis();
- Date now = new Date(nowMillis);
- if(ttlMillis==null){
- ttlMillis=JwtUtil.JWT_TTL;
- }
- long expMillis = nowMillis + ttlMillis;
- Date expDate = new Date(expMillis);
- return Jwts.builder()
- .setId(uuid) //唯一的ID
- .setSubject(subject) // 主题 可以是JSON数据
- .setIssuer("sg") // 签发者
- .setIssuedAt(now) // 签发时间
- .signWith(signatureAlgorithm, secretKey) //使用HS256对称加密算法签名, 第二个参数为秘钥
- .setExpiration(expDate);
- }
- /**
- * 创建token
- * @param id
- * @param subject
- * @param ttlMillis
- * @return
- */
- public static String createJWT(String id, String subject, Long ttlMillis) {
- JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id);// 设置过期时间
- return builder.compact();
- }
- /**
- * 生成加密后的秘钥 secretKey
- * @return
- */
- public static SecretKey generalKey() {
- byte[] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
- SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
- return key;
- }
- /**
- * 解析
- *
- * @param jwt
- * @return
- * @throws Exception
- */
- public static Claims parseJWT(String jwt) throws Exception {
- SecretKey secretKey = generalKey();
- return Jwts.parser()
- .setSigningKey(secretKey)
- .parseClaimsJws(jwt)
- .getBody();
- }
- }
RedisConfig
- package com.zb.config;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.data.redis.connection.RedisConnectionFactory;
- import org.springframework.data.redis.core.RedisTemplate;
- import org.springframework.data.redis.serializer.StringRedisSerializer;
- @Configuration
- public class RedisConfig {
- @Bean
- @SuppressWarnings(value = { "unchecked", "rawtypes" })
- public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
- {
- RedisTemplate<Object, Object> template = new RedisTemplate<>();
- template.setConnectionFactory(connectionFactory);
- FastJsonRedisSerializer serializer = new FastJsonRedisSerializer(Object.class);
- // 使用StringRedisSerializer来序列化和反序列化redis的key值
- template.setKeySerializer(new StringRedisSerializer());
- template.setValueSerializer(serializer);
- // Hash的key也采用StringRedisSerializer的序列化方式
- template.setHashKeySerializer(new StringRedisSerializer());
- template.setHashValueSerializer(serializer);
- template.afterPropertiesSet();
- return template;
- }
- }
SecurityConfig,45行需要改成你的登录接口地址
- import com.zb.filters.PowerFilter;
- 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.config.annotation.method.configuration.EnableGlobalMethodSecurity;
- 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.AuthenticationEntryPoint;
- import org.springframework.security.web.access.AccessDeniedHandler;
- import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
- @Configuration
- @EnableGlobalMethodSecurity(prePostEnabled = true)
- public class SecurityConfig extends WebSecurityConfigurerAdapter {
- @Bean
- public BCryptPasswordEncoder cryptPasswordEncoder() {
- return new BCryptPasswordEncoder();
- }
- @Autowired
- private PowerFilter powerFilter;
- @Autowired
- private AuthenticationEntryPoint authenticationEntryPoint;
- @Autowired
- private AccessDeniedHandler accessDeniedHandler;
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- //关闭csrf
- .csrf().disable()
- //不通过Session获取SecurityContext
- .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
- .and()
- .authorizeRequests()
- // 对于登录接口 允许匿名访问(需要改成你的登录接口地址)
- .antMatchers("/user/login/**").anonymous()
- // 除上面外的所有请求全部需要鉴权认证
- .anyRequest().authenticated();
- //将用户开发的过滤器添加到用户登陆之前的过滤器上
- http.addFilterBefore(powerFilter, UsernamePasswordAuthenticationFilter.class);
- //添加自定义异常处理
- http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint).accessDeniedHandler(accessDeniedHandler);
- }
- @Bean
- public AuthenticationManager createAuthenticationManager() throws Exception {
- return super.authenticationManagerBean();
- }
- }
WebUtils
- package com.zb.config;
- import javax.servlet.http.HttpServletResponse;
- import java.io.IOException;
- public class WebUtils
- {
- /**
- * 自定义返回没有认证和授权信息用的
- * 将字符串渲染到客户端
- *
- * @param response 渲染对象
- * @param string 待渲染的字符串
- * @return null
- */
- public static String renderString(HttpServletResponse response, String string) {
- try
- {
- response.setStatus(200);
- response.setContentType("application/json");
- response.setCharacterEncoding("utf-8");
- response.getWriter().print(string);
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- return null;
- }
- }
config包结束,第一部分结束
entity包,第二部分开始
LoginUser,需要改动一些东西,注意看注释
- package com.zb.entity;
- import com.alibaba.fastjson.annotation.JSONField;
- import lombok.AllArgsConstructor;
- import lombok.Data;
- import lombok.NoArgsConstructor;
- import org.springframework.security.core.GrantedAuthority;
- import org.springframework.security.core.authority.SimpleGrantedAuthority;
- import org.springframework.security.core.userdetails.UserDetails;
- import java.util.ArrayList;
- import java.util.Collection;
- import java.util.List;
- @Data
- @NoArgsConstructor
- public class LoginUser implements UserDetails {
- //登录信息实体类,换成你的
- private User user;
- //存放查出来的用户有的权限
- private List<String> powers;
- //将用户信息和权限全放进去
- //User需要换成你的
- public LoginUser(User user, List<String> powers) {
- this.user = user;
- this.powers = powers;
- }
- @JSONField(serialize = false)
- private List<SimpleGrantedAuthority> authorities;
- @Override
- public Collection<? extends GrantedAuthority> getAuthorities() {
- if (authorities != null && authorities.size() > 0) {
- return authorities;
- }
- authorities = new ArrayList<>();
- for (String power : powers) {
- SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(power);
- authorities.add(simpleGrantedAuthority);
- }
- return authorities;
- }
- //user.getPasswd()为获取密码,换成你的
- @Override
- public String getPassword() {
- return user.getPasswd();
- }
- //user.getNickName();为获取用户名,换成你的
- @Override
- public String getUsername() {
- return user.getNickName();
- }
- @Override
- public boolean isAccountNonExpired() {
- return true;
- }
- @Override
- public boolean isAccountNonLocked() {
- return true;
- }
- @Override
- public boolean isCredentialsNonExpired() {
- return true;
- }
- @Override
- public boolean isEnabled() {
- return true;
- }
- }
entity包,第二部分结束
exception包,第三部分开始
AccessDeniedHandlerImpl
- package com.zb.exception;
- import com.alibaba.fastjson.JSON;
- import com.zb.config.WebUtils;
- import org.springframework.http.HttpStatus;
- import org.springframework.security.access.AccessDeniedException;
- import org.springframework.security.web.access.AccessDeniedHandler;
- import org.springframework.stereotype.Component;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.io.IOException;
- import java.util.HashMap;
- import java.util.Map;
- @Component
- public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
- @Override
- public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
- Map<String, Object> result = new HashMap<>();
- result.put("msg", "授权失败!");
- String json = JSON.toJSONString(result);
- WebUtils.renderString(response, json);
- }
- }
AuthenticationEntryPointImpl
- package com.zb.exception;
- import com.alibaba.fastjson.JSON;
- import com.zb.config.WebUtils;
- import org.springframework.http.HttpStatus;
- import org.springframework.security.core.AuthenticationException;
- import org.springframework.security.web.AuthenticationEntryPoint;
- import org.springframework.stereotype.Component;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.io.IOException;
- import java.util.HashMap;
- import java.util.Map;
- @Component
- public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
- @Override
- public void commence(HttpServletRequest request, HttpServletResponse response,
- AuthenticationException authException) throws IOException, ServletException {
- Map<String, Object> result = new HashMap<>();
- result.put("code", HttpStatus.UNAUTHORIZED);
- result.put("msg", "认证失败!");
- String json = JSON.toJSONString(result);
- WebUtils.renderString(response, json);
- }
- }
exception包,第三部分结束
filters包,第四部分开始
PowerFilter,为自已的拦截器,在执行Security之前会执行自已编写的PowerFilter过滤器,可以按需改动,也可不动
- package com.zb.filters;
- import com.alibaba.fastjson.JSON;
- import com.zb.config.JwtUtil;
- import com.zb.entity.LoginUser;
- import io.jsonwebtoken.Claims;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.redis.core.RedisTemplate;
- import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
- import org.springframework.security.core.context.SecurityContextHolder;
- import org.springframework.stereotype.Component;
- import org.springframework.util.ObjectUtils;
- import org.springframework.util.StringUtils;
- 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 PowerFilter extends OncePerRequestFilter {
- @Autowired
- private RedisTemplate redisTemplate;
- @Override
- protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
- String token = request.getHeader("token");
- //登陆接口放行
- if (!StringUtils.hasText(token)) {
- System.out.println("登陆接口放行...");
- filterChain.doFilter(request, response);
- return;
- }
- String username = "";
- try {//验证令牌的有效性
- Claims claims = JwtUtil.parseJWT(token);
- username = claims.getSubject();
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException("认证失败!");
- }
- //从redis中获取用户信息
- Object obj = redisTemplate.boundValueOps("token:" + username).get();
- if (ObjectUtils.isEmpty(obj)) {
- throw new RuntimeException("认证失败!");
- }
- LoginUser loginUser = JSON.parseObject(obj.toString(), LoginUser.class);
- //登陆的用户存储到上下文中
- UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
- SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
- //转发到下一过滤器或者是控制器
- filterChain.doFilter(request, response);
- }
- }