文章目录

  • 1 SpringSecurity和JWT
  • 1.1 SpringSecurity
  • 1.1.1 简介
  • 1.1.2 SpringSecurity原理
  • 1.1.3 Spring Security基于用户名和密码的认证模式流程
  • 1.1.4 基于内存认证
  • 1.2 JWT
  • 1.2.1 JWT的组成
  • 1.2.2 JWT实例
  • 1.2.3 JWT实现认证和授权的原理
  • 1.3 整合SpringSecurity及JWT
  • 1.3.1 添加依赖
  • 1.3.2 添加JWT token的工具类
  • 1.3.3 添加SpringSecurity的配置类
  • 1.3.3.1 demo示例
  • 1.3.3.2 示例说明
  • 1.3.4 相关依赖及方法说明
  • 1.3.5 添加RestfulAccessDeniedHandler
  • 1.3.6 添加RestAuthenticationEntryPoint
  • 1.3.7 添加AdminUserDetails
  • 1.3.8 添加JwtAuthenticationTokenFilter
  • 1.4 自定义登录认证
  • 1.4.1 新建登录成功处理类
  • 1.4.2 新建登录失败处理类
  • 1.4.3 新建登录认证管理器
  • 1.4.4 新建登录过滤器
  • 1.5 其他
  • 1.5.1 返回访问当前url的角色
  • 1.5.2 判断当前用户是否拥有访问当前url的角色


1 SpringSecurity和JWT

1.1 SpringSecurity

1.1.1 简介

SpringSecurity是一个强大的可高度定制的认证授权框架,对于Spring应用来说它是一套Web安全标准。SpringSecurity注重于为Java应用提供认证和授权功能,像所有的Spring项目一样,它对自定义需求具有强大的扩展性。

说明一下身份认证和用户授权:

  • 用户认证(Authentication):系统通过校验用户提供的用户名和密码来验证该用户是否为系统中的合法主体,即是否可以访问该系统;
  • 用户授权(Authorization):系统为用户分配不同的角色,以获取对应的权限,即验证该用户是否有权限执行该操作;

1.1.2 SpringSecurity原理

Security可以看做是由一组filter过滤器链组成的权限认证。Spring Security会在Web应用程序的过滤器链中添加一组自定义的过滤器,这些过滤器可以实现身份验证和授权功能。当用户请求资源时,Spring Security会拦截请求,并使用配置的身份验证机制来验证用户身份。如果身份验证成功,Spring Security会授权用户访问所请求的资源。

它的整个工作流程如下所示:

springsecurity的token过滤器_安全


图片图中绿色认证方式是可以配置的,橘黄色和蓝色的位置不可更改:

  • FilterSecurityInterceptor:最后的过滤器,它会决定当前的请求可不可以访问Controller
  • ExceptionTranslationFilter:异常过滤器,接收到异常消息时会引导用户进行认证;

springsecurity的token过滤器_java_02


Spring Security的具体工作原理如下:

  • 用户请求Web应用程序的受保护资源。
  • Spring Security拦截请求,并尝试获取用户的身份验证信息。
  • 如果用户没有经过身份验证,Spring Security将向用户显示一个登录页面,并要求用户提供有效的凭据(用户名和密码)。
  • 一旦用户提供了有效的凭据,Spring Security将验证这些凭据,并创建一个已认证的安全上下文(SecurityContext)对象。
  • 安全上下文对象包含已认证的用户信息,包括用户名、角色和授权信息。
  • 在接下来的请求中,Spring Security将使用已经认证的安全上下文对象来判断用户是否有权访问受保护的资源。
  • 如果用户有权访问资源,Spring Security将允许用户访问资源,否则将返回一个错误信息。

1.1.3 Spring Security基于用户名和密码的认证模式流程

请求的用户名密码可以通过表单登录基础认证数字认证三种方式从HttpServletRequest中获得,用于认证的数据源策略有内存数据库ldap自定义等。

拦截未授权的请求,重定向到登录页面的过程:

  • 当用户访问需要授权的资源时,Spring Security会检查用户是否已经认证(即是否已登录),如果没有登录则会重定向到登录页面。
  • 重定向到登录页面时,用户需要输入用户名和密码进行认证。

表单登录的过程:

  • 用户在登录页面输入用户名和密码,提交表单。
  • Spring SecurityUsernamePasswordAuthenticationFilter拦截表单提交的请求,并将用户名和密码封装成一个Authentication对象。
  • AuthenticationManager接收到Authentication对象后,会根据用户名和密码查询用户信息,并将用户信息封装成一个UserDetails对象。
  • 如果查询到用户信息,则将UserDetails对象封装成一个已认证的Authentication对象并返回,如果查询不到用户信息,则抛出相应的异常。
  • 认证成功后,用户会被重定向到之前访问的资源。如果之前访问的资源需要特定的角色或权限才能访问,则还需要进行授权的过程。

Spring Security的认证流程大致可以分为两个过程,首先是用户登录认证的过程,然后是用户访问受保护资源时的授权过程。在认证过程中,用户需要提供用户名和密码,Spring Security通过UsernamePasswordAuthenticationFilter将用户名和密码封装成Authentication对象,并交由AuthenticationManager进行认证。
如果认证成功,则认证结果会存储在SecurityContextHolder中。在授权过程中,Spring Security会检查用户是否有访问受保护资源的权限,如果没有则会重定向到登录页面进行认证。

拦截未授权的请求,重定向到登录页面

springsecurity的token过滤器_安全_03

表单登录的过程,进行账号密码认证

springsecurity的token过滤器_java_04

1.1.4 基于内存认证

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
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.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;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices;

@Configuration
@EnableWebSecurity
public class SecurityConfig  extends WebSecurityConfigurerAdapter {
	@Bean
    PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }
    /*@Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }*/
    //基于内存的用户存储
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("itguang").password("123456").roles("USER").and()
                .withUser("admin").password("{noop}" + "123456").roles("ADMIN");
    }

    //请求拦截
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().permitAll()
                .and()
                .formLogin()
                .permitAll()
                .and()
                .logout()
                .permitAll();
    }
}

1.2 JWT

JWTJSON WEB TOKEN的缩写,它是基于 RFC 7519 标准定义的一种可以安全传输的的JSON对象,由于使用了数字签名,所以是可信任和安全的。

1.2.1 JWT的组成

JWT token的格式:header.payload.signatureheader中用于存放签名的生成算法:{"alg":"HS512"}payload中用于存放用户名token的生成时间和过期时间

{
"sub":"admin",
"created":1489079981393,
"exp":1489684781
}

signature为以headerpayload生成的签名,一旦headerpayload被篡改,验证将失败

//secret为加密算法的密钥
String signature =
 HMACSHA512(base64UrlEncode(header)+
 "."+base64UrlEncode(payload),secret)

1.2.2 JWT实例

这是一个JWT的字符串

eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImNyZWF0ZWQiOjE1NTY3NzkxMjUzMDksImV4cCI6MTU1NzM4MzkyNX0.d-iki0193X0bBOETf2UN3r3PotNIEAV7mzIxxeI5IxFyzzkOZxS0PGfF_SK6wxCv2K8S0cZjMkv6b5bCqc0VBw

可以在该网站上获得解析结果:https://jwt.io/

springsecurity的token过滤器_java_05

1.2.3 JWT实现认证和授权的原理

用户调用登录接口,登录成功后获取到JWTtoken
之后用户每次调用接口都在httpheader中添加一个叫Authorization的头,值为JWTtoken
后台程序通过对Authorization头中信息的解码及数字签名校验来获取其中的用户信息,从而实现认证和授权。

1.3 整合SpringSecurity及JWT

1.3.1 添加依赖

pom.xml中添加项目依赖

<!--SpringSecurity依赖配置-->
<dependency>  
<groupId>org.springframework.boot</groupId>    
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!--Hutool Java工具包-->
<dependency>   
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.5.7</version>
</dependency>

<!--JWT(Json Web Token)登录支持-->
<dependency>   
<groupId>io.jsonwebtoken</groupId>    
<artifactId>jjwt</artifactId>    
<version>0.9.0</version>
</dependency>

1.3.2 添加JWT token的工具类

用于生成和解析JWT token的工具类
相关方法说明:

  • generateToken(UserDetails userDetails) :用于根据登录用户信息生成token
  • getUserNameFromToken(String token):从token中获取登录用户的信息
  • validateToken(String token, UserDetails userDetails):判断token是否还有效
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factor.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;


import java.util.Date;

import java.util.HashMap;

import java.util.Map;



/**
 * JwtToken生成的工具类
 */
@Component
public class JwtTokenUtil{
    
private static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenUtil.class);

private static final String CLAIM_KEY_USERNAME = "sub";
    
private static final String CLAIM_KEY_CREATED = "created";    
@Value("${jwt.secret}")    
private String secret;

    
@Value("${jwt.expiration}")    
private Long expiration;    

private String generateToken(Map<String, Object> claims) {        
return Jwts.builder().setClaims(claims)
.setExpiration(generateExpirationDate())                
.signWith(SignatureAlgorithm.HS512, secret)                
.compact();    
}



    
/**
* 从token中获取JWT中的负载
*/    
private Claims getClaimsFromToken(String token) {        
Claims claims = null;
        
try {           
 claims = Jwts.parser()                    
 .setSigningKey(secret)                    
 .parseClaimsJws(token)                    
.getBody();        
} catch (Exception e) {
LOGGER.info("JWT格式验证失败:{}",token);        
}
        
return claims;
}
    
/**
 * 生成token的过期时间
*/
    
private Date generateExpirationDate() {
        
return new Date(System.currentTimeMillis() + expiration * 1000);    
}
    
/**
* 从token中获取登录用户名
*/   
public String getUserNameFromToken(String token) {
        
String username;        
try {            
Claims claims = getClaimsFromToken(token);
 username =  claims.getSubject();
} catch (Exception e) {
  username =null;        
}
        
return username;    
}



    
/**
* 验证token是否还有效
*
* @param token       客户端传入的token
* @param userDetails 从数据库中查询出来的用户信息
*/
    
public boolean validateToken(String token, UserDetails userDetails) {        
String username = getUserNameFromToken(token);        
return username.equals(userDetails.getUsername()) && !isTokenExpired(token);    
}

    
/**
* 判断token是否已经失效
*/

    
private boolean isTokenExpired(String token) {  
 Date expiredDate = getExpiredDateFromToken(token);        
return expiredDate.before(new Date());    
}



    
/**
* 从token中获取过期时间
*/

    
private 
Date getExpiredDateFromToken(String token) {        
Claims claims = getClaimsFromToken(token);
        
return claims.getExpiration();    
}



    
/**
* 根据用户信息生成token
*/

    
public String generateToken(UserDetails userDetails) {        
Map<String, Object> claims = new HashMap<>();
claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
claims.put(CLAIM_KEY_CREATED, new Date());
        
return generateToken(claims);    
}



    
/**
* 判断token是否可以被刷新
*/
   
public boolean canRefresh(String token) {        
return!isTokenExpired(token);    
}

   
/**
* 刷新token
 */

    
public String refreshToken(String token) {        
Claims claims = getClaimsFromToken(token);
 claims.put(CLAIM_KEY_CREATED, new Date());        
return generateToken(claims);    
}
}

1.3.3 添加SpringSecurity的配置类

1.3.3.1 demo示例
import com.macro.mall.tiny.component.JwtAuthenticationTokenFilter;
import com.macro.mall.tiny.component.RestAuthenticationEntryPoint;
import com.macro.mall.tiny.component.RestfulAccessDeniedHandler;
import com.macro.mall.tiny.dto.AdminUserDetails;
import com.macro.mall.tiny.mbg.model.UmsAdmin;
import com.macro.mall.tiny.mbg.model.UmsPermission;
import com.macro.mall.tiny.service.UmsAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
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;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import java.util.List;

/**
 * SpringSecurity的配置
 * Created by macro on 2018/4/26.
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
	@Autowired    
	private UmsAdminService adminService;
	    
	@Autowired    
	private RestfulAccessDeniedHandler restfulAccessDeniedHandler;
	    
	@Autowired    
	private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
	@Override    
	protected void configure(HttpSecurity httpSecurity) throws Exception {
		httpSecurity.csrf()
			// 由于使用的是JWT,我们这里不需要csrf                
			.disable()                
			.sessionManagement()
			// 基于token,所以不需要session                
			.sessionCreationPolicy(SessionCreationPolicy.STATELESS)                
			.and()                
			.authorizeRequests()                
			.antMatchers(HttpMethod.GET, 
			// 允许对于网站静态资源的无授权访问                        
			"/",                        
			"/*.html",                        
			"/favicon.ico",                        
			"/**/*.html",                        
			"/**/*.css",                        
			"/**/*.js",                        
			"/swagger-resources/**",                        
			"/v2/api-docs/**"                
			)
			.permitAll()                
			.antMatchers("/admin/login", "/admin/register")
			// 对登录注册要允许匿名访问                
			.permitAll()                
			.antMatchers(HttpMethod.OPTIONS)
			//跨域请求会先进行一次options请求                
			.permitAll()
			//.antMatchers("/**")//测试时全部运行访问
			//.permitAll()                
			.anyRequest()
			// 除上面外的所有请求全部需要鉴权认证                
			.authenticated();        
	// 禁用缓存
	httpSecurity.headers().cacheControl();        
	// 添加JWT filter
	httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);        
	//添加自定义未授权和未登录结果返回
	httpSecurity.exceptionHandling()                
	.accessDeniedHandler(restfulAccessDeniedHandler)                
	.authenticationEntryPoint(restAuthenticationEntryPoint);    
}
或者 这样放行
/**
  * Swagger等静态资源不进行拦截
   */
  @Override
  public void configure(WebSecurity web) {    
        web.ignoring().antMatchers(
                "/*.html",
                "/favicon.ico",
                "/**/*.html",
                "/**/*.css",
                "/**/*.js",
                "/error",
                "/webjars/**",
                "/resources/**",
                "/swagger-ui.html",
                "/swagger-resources/**",
                "/v2/api-docs");
    }
    
@Override    
protected void configure(AuthenticationManagerBuilder auth)throws Exception {

 auth.userDetailsService(userDetailsService())
.passwordEncoder(passwordEncoder());    
}

@Bean    
public PasswordEncoder passwordEncoder() {
        
return new BCryptPasswordEncoder();    
}
    
@Bean    
public UserDetailsService userDetailsService() {        
//获取登录用户信息        
return username -> {            
UmsAdmin admin = adminService.getAdminByUsername(username);
            
if (admin != null) {                
List<UmsPermission> permissionList = adminService.getPermissionList(admin.getId());                
return new AdminUserDetails(admin,permissionList);            
}           
throw new UsernameNotFoundException("用户名或密码错误");        
};    
}

@Bean    
public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter(){
        
return new JwtAuthenticationTokenFilter();    
}

    
@Bean    
@Override    
public AuthenticationManager authenticationManagerBean() throws Exception {        
return super.authenticationManagerBean();    
}
}
1.3.3.2 示例说明

SecurityConfig拦截规则:

  • anyRequest:匹配所有请求路径
  • access:SpringEl表达式结果为true时可以访问
  • anonymous:匿名可以访问
  • denyAll:拒绝所有用户访问该请求
  • fullyAuthenticated:用户完全认证可以访问(非remember-me下自动登录)
  • hasAnyAuthority:要求用户具有多个权限中的至少一个权限才能访问该请求
  • hasAnyRole:要求用户具有多个角色中的至少一个角色才能访问该请求
  • hasAuthority:要求用户具有特定的权限才能访问该请求
    基于权限进行访问控制的。它检查用户是否有指定的权限,并且这些权限没有前缀
  • hasIpAddress:如果有参数,参数表示IP地址,如果用户IP和参数匹配,则可以访问
  • hasRole:要求用户具有特定的角色才能访问该请求
    基于角色进行访问控制的。它检查用户是否有指定的角色,并且这些角色以ROLE_前缀作为前缀(例如ROLE_ADMIN
    .antMatchers("/admin/**").hasRole("ADMIN"):只有具有ROLE_ADMIN角色的用户才能访问/admin/路径下的页面
  • permitAll:允许所有用户访问该请求,不需要进行任何身份验证
  • rememberMe:允许通过remember-me登录的用户访问
  • authenticated:要求用户进行身份验证,但是不要求用户具有任何特定的角色

1.3.4 相关依赖及方法说明

  • configure(HttpSecurity httpSecurity):用于配置需要拦截的url路径、jwt过滤器及出异常后的处理器;
  • configure(AuthenticationManagerBuilder auth):用于配置UserDetailsServicePasswordEncoder
  • RestfulAccessDeniedHandler:当用户没有访问权限时的处理器,用于返回JSON格式的处理结果;
  • RestAuthenticationEntryPoint:当未登录或token失效时,返回JSON格式的结果;
  • UserDetailsService : SpringSecurity定义的核心接口,用于根据用户名获取用户信息,需要自行实现;
  • UserDetailsSpringSecurity定义用于封装用户信息的类(主要是用户信息和权限),需要自行实现;
  • PasswordEncoderSpringSecurity定义的用于对密码进行编码及比对的接口,目前使用的是BCryptPasswordEncoder
  • JwtAuthenticationTokenFilter:在用户名和密码校验前添加的过滤器,如果有jwt的token,会自行根据token信息进行登录。

1.3.5 添加RestfulAccessDeniedHandler

import cn.hutool.json.JSONUtil;
import com.macro.mall.tiny.common.api.CommonResult;

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;
/**
 * 当访问接口没有权限时,自定义的返回结果
 */

@Component
public class RestfulAccessDeniedHandler implements AccessDeniedHandler{    
@Override    
public void handle(HttpServletRequest request,                    
HttpServletResponse response,                       
AccessDeniedException e)throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(JSONUtil.parse(CommonResult.forbidden(e.getMessage())));
        response.getWriter().flush();    
}
}

1.3.6 添加RestAuthenticationEntryPoint

import cn.hutool.json.JSONUtil;
import com.macro.mall.tiny.common.api.CommonResult;
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;
/**
 * 当未登录或者token失效访问接口时,自定义的返回结果
 */
@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {    
@Override    
public void commence(
HttpServletRequest request, 
HttpServletResponse response, 
AuthenticationException authException) 
throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(JSONUtil.parse(CommonResult.unauthorized(authException.getMessage())));
        response.getWriter().flush();    
}
}

1.3.7 添加AdminUserDetails

import com.macro.mall.tiny.mbg.model.UmsAdmin;
import com.macro.mall.tiny.mbg.model.UmsPermission;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
/**
 * SpringSecurity需要的用户详情
 */

public class AdminUserDetails implements UserDetails {    
private UmsAdmin umsAdmin;
    
private List<UmsPermission> permissionList;
    
public AdminUserDetails(UmsAdmin umsAdmin, 
List<UmsPermission> permissionList) {
        this.umsAdmin = umsAdmin;
        this.permissionList = permissionList;    
}


@Override
public Collection<? extends GrantedAuthority> getAuthorities() {        
//返回当前用户的权限        
return permissionList.stream()                
.filter(permission -> permission.getValue()!=null)                
.map(permission ->new SimpleGrantedAuthority(permission
.getValue()))                
.collect(Collectors
.toList());    
}
   
@Override    
public String getPassword() {        
return umsAdmin.getPassword();    
}    
@Override    
public String getUsername() {        
return umsAdmin.getUsername();    
}
@Override    
public boolean isAccountNonExpired() {        
return true;   
 }    
@Override    
public boolean isAccountNonLocked() {        
return true;    
}    
@Override    public boolean isCredentialsNonExpired() {        
return true;    
}    
@Override    
public boolean isEnabled() {        
return umsAdmin.getStatus().equals(1);    
}
}

1.3.8 添加JwtAuthenticationTokenFilter

在用户名和密码校验前添加的过滤器,如果请求中有jwt的token且有效,会取出token中的用户名,然后调用SpringSecurity的API进行登录操作。

import com.macro.mall.tiny.common.utils.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
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;

/**
 * JWT登录授权过滤器
 */

public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {    
private static final Logger LOGGER = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);    
@Autowired    
private UserDetailsService userDetailsService;    
@Autowired    
private JwtTokenUtil jwtTokenUtil;    
@Value("${jwt.tokenHeader}")
private String tokenHeader;    
@Value("${jwt.tokenHead}")    
private String tokenHead;    
@Override    
protected void doFilterInternal(HttpServletRequest request,                                    
HttpServletResponse response,                                   
 FilterChain chain) throws ServletException, IOException {     
    String authHeader = request.getHeader(this.tokenHeader);        
if(authHeader != null && authHeader.startsWith(this.tokenHead)) {            
String authToken = authHeader.substring(this.tokenHead.length
());
// The part after "Bearer "
String username = jwtTokenUtil.getUserNameFromToken(authToken);
LOGGER.info("checking username:{}", username);            
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) 
{                
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
                
if (jwtTokenUtil.validateToken(authToken, userDetails)) {                    
UsernamePasswordAuthenticationToken authentication = new
 UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());

    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails
(request));
      LOGGER.info("authenticated user:{}", username);                  
SecurityContextHolder.getContext().setAuthentication(authentication);                
}            
}        
}
    chain.doFilter(request, response);
    
}
}

1.4 自定义登录认证

springSecurity是基于过滤器进行安全认证的。
我们需要自定义:

  • 登录成功处理类:顾名思义,登录成功后的一些处理(设置返回信息提示“登录成功!”,返回数据类型为json);
  • 登录失败处理类:类似登录成功处理类Ps:登录成功处理类和失败处理类有默认的实现可以不自定义但是建议自定义,因为返回的信息为英文,一般情况不符合要求;
  • 登录过滤器:负责过滤登录请求,再交由自定义的登录认证管理器处理;
  • 登录认证管理器:根据过滤器传过来的登录参数,进行登录认证,认证后授权;

1.4.1 新建登录成功处理类

需要实现 AuthenticationSuccessHandler

@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(CustomAuthenticationSuccessHandler.class);

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { 
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        //登录成功返回的认证体,具体格式在后面的登录认证管理器中
        String responseJson = JackJsonUtil.object2String(ResponseFactory.success(authentication));
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("登录成功!");
        }
        response.getWriter().write(responseJson);
    }
}

1.4.2 新建登录失败处理类

需要实现AuthenticationFailureHandler

@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
  
    private static final Logger LOGGER = LoggerFactory.getLogger(CustomAuthenticationFailureHandler.class);
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {     
        String errorMsg;
        if (StringUtils.isNotBlank(e.getMessage())) {        
            errorMsg = e.getMessage();
        } else {     
            errorMsg = CodeMsgEnum.LOG_IN_FAIL.getMsg();
        }
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        String responseJson = JackJsonUtil.object2String(ResponseFactory.fail(CodeMsgEnum.LOG_IN_FAIL,errorMsg));
        if (LOGGER.isDebugEnabled()) {    
            LOGGER.debug("认证失败!");
        }
        response.getWriter().write(responseJson);
    }
}

1.4.3 新建登录认证管理器

实现AuthenticationProvider ,负责具体的身份认证(一般数据库认证,在登录过滤器过滤掉请求后传入)

@Component
public class UserVerifyAuthenticationProvider implements AuthenticationProvider {
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserService userService;
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String userName = (String) authentication.getPrincipal(); // Principal 主体,一般指用户名
        String passWord = (String) authentication.getCredentials(); //Credentials 网络凭证,一般指密码
        //通过账号去数据库查询用户以及用户拥有的角色信息
        UserRoleVo userRoleVo = userService.findUserRoleByAccount(userName);
        //数据库密码
        String encodedPassword = userRoleVo.getPassWord();
        //credentials凭证即为前端传入密码,因为前端一般用Base64加密过所以需要解密。
        String credPassword = new String(Base64Utils.decodeFromString(passWord), StandardCharsets.UTF_8);
        // 验证密码:前端明文,数据库密文
        passwordEncoder = new MD5Util();
        if (!passwordEncoder.matches(credPassword, encodedPassword)) {  
            throw new AuthenticationServiceException("账号或密码错误!");
        }
        //ps:GrantedAuthority对认证主题的应用层面的授权,含当前用户的权限信息,通常使用角色表示
        List<GrantedAuthority> roles = new LinkedList<>();
        List<Role> roleList = userRoleVo.getRoleList();
        roleList.forEach(role -> {
            SimpleGrantedAuthority roleId = new SimpleGrantedAuthority(role.getRoleId().toString());
            roles.add(roleId);
        });
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userName, passWord, roles);
        token.setDetails(userRoleVo);//这里可以放用户的详细信息
        return token;
    }

    @Override
    public boolean supports(Class<?> authentication) {     
        return false;
    }
}

1.4.4 新建登录过滤器

需要继承UsernamePasswordAuthenticationFilter,负责过滤登录请求并交由登录认证管理器进行具体的认证。

public class LoginFilter extends UsernamePasswordAuthenticationFilter {
    private UserVerifyAuthenticationProvider authenticationManager;
    /**
     * @param authenticationManager 认证管理器
     * @param successHandler 认证成功处理类
     * @param failureHandler 认证失败处理类
     */
    public LoginFilter(UserVerifyAuthenticationProvider authenticationManager,
                       CustomAuthenticationSuccessHandler successHandler,
                       CustomAuthenticationFailureHandler failureHandler) {     
        //设置认证管理器(对登录请求进行认证和授权)
        this.authenticationManager = authenticationManager;
        //设置认证成功后的处理类
        this.setAuthenticationSuccessHandler(successHandler);
        //设置认证失败后的处理类
        this.setAuthenticationFailureHandler(failureHandler);
        //可以自定义登录请求的url
        super.setFilterProcessesUrl("/myLogin");
    }
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { 
        try {     
            //转换请求入参
            UserDTO loginUser = new ObjectMapper().readValue(request.getInputStream(), UserDTO.class);
            //入参传入认证管理器进行认证
            return authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginUser.getUserName(), loginUser.getPassWord())
            );
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

最后配置到WebSecurityConfig中:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserVerifyAuthenticationProvider authenticationManager;//认证用户类
    @Autowired
    private CustomAuthenticationSuccessHandler successHandler;//登录认证成功处理类
    @Autowired
    private CustomAuthenticationFailureHandler failureHandler;//登录认证失败处理类

    /**
     * Swagger等静态资源不进行拦截
     */
    @Override
    public void configure(WebSecurity web) {     
        web.ignoring().antMatchers(
                "/*.html",
                "/favicon.ico",
                "/**/*.html",
                "/**/*.css",
                "/**/*.js",
                "/error",
                "/webjars/**",
                "/resources/**",
                "/swagger-ui.html",
                "/swagger-resources/**",
                "/v2/api-docs");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
       
        http.authorizeRequests()
                //配置一些不需要登录就可以访问的接口
                .antMatchers("/demo/**", "/about/**").permitAll()
                //任何尚未匹配的URL只需要用户进行身份验证
                .anyRequest().authenticated()
                .and()
                //配置登录过滤器
                .addFilter(new LoginFilter(authenticationManager, successHandler, failureHandler))
                .csrf().disable();
    }
}

1.5 其他

1.5.1 返回访问当前url的角色

定义一个MyFilterInvocationSecurityMetadataSource实现FilterInvocationSecurityMetadataSource的类,重写getAttributes方法方法的作用是:返回哪些角色可以访问当前url,这个肯定是从数据库中获取要注意的是对于PathVariable传参的url,数据库中存的是这样的:/getUserByName/{name}但实际访问的url中name是具体的值类似的/user/getUserById也要可以匹配/user/getUserById?1;

package com.aliyu.security.provider;

import com.aliyu.service.role.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 *@description: 第一步:数据库查询所有权限出来:
 * 之所以要所有权限,因为数据库url和实际请求url并不能直接匹配需要。比方:/user/getUserById 匹配 /user/getUserById?1
 * 第二步:通过httpUrl匹配器找出允许访问当前请求的角色列表(哪些角色可以访问此请求)
 */
@Component
public class MyFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private RoleService roleService;

    /**
     * 返回当前URL允许访问的角色列表
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
     
        //入参转为HttpServletRequest
        FilterInvocation fi = (FilterInvocation) object;
        HttpServletRequest request = fi.getRequest();
        //从数据库中查询系统所有的权限,格式为<"权限url","能访问url的逗号分隔的roleid">
        List<Map<String, String>> allUrlRoleMap = roleService.getAllUrlRoleMap();
        for (Map<String, String> urlRoleMap : allUrlRoleMap) {
     
            String url = urlRoleMap.get("url");
            String roles = urlRoleMap.get("roles");
            //new AntPathRequestMatcher创建httpUrl匹配器:里面url匹配规则已经给我们弄好了,
            // 能够支持校验PathVariable传参的url(例如:/getUserByName/{name})
            // 也能支持 /user/getUserById 匹配 /user/getUserById?1
            AntPathRequestMatcher matcher = new AntPathRequestMatcher(url);
            if (matcher.matches(request)){
   
      //当前请求与httpUrl匹配器进行匹配
                return SecurityConfig.createList(roles.split(","));
            }
        }
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {     
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {     
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}

1.5.2 判断当前用户是否拥有访问当前url的角色

定义一个MyAccessDecisionManager,实现AccessDecisionManager接口自定义一个决策管理器,判断是否有访问权限。上一步MyFilterInvocationSecurityMetadataSource中返回的当前请求可以的访问角色列表会传到这里的decide方法里面(如果没有角色的话,不会进入decide方法。正常情况你访问的url必然和某个角色关联,如果没有关联就不应该可以访问)。decide方法传了当前登录用户拥有的角色,通过判断用户拥有的角色中是否有一个角色和当前url可以访问的角色匹配。如果匹配,权限校验通过。

package com.aliyu.security.provider;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Iterator;

/**
 *@description: 接口权限判断(根据MyFilterInvocationSecurityMetadataSource获取到的请求需要的角色
 * 和当前登录人的角色进行比较)
 */
@Component
public class MyAccessDecisionManager implements AccessDecisionManager {
   
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
     
        //循环请求需要的角色,只要当前用户拥有的角色中包含请求需要的角色中的一个,就算通过。
        Iterator<ConfigAttribute> iterator = configAttributes.iterator();
        while(iterator.hasNext()){
             ConfigAttribute configAttribute = iterator.next();
            String needCode = configAttribute.getAttribute();
            //获取到了登录用户的所有角色
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            for (GrantedAuthority authority : authorities) {
    
                if (StringUtils.equals(authority.getAuthority(), needCode)) {   
                    return;
                }
            }
        }
        throw new AccessDeniedException("当前访问没有权限");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> clazz) {
         return FilterInvocation.class.isAssignableFrom(clazz);
    }
}

配置到WebSecurityConfig上面去

package com.aliyu.security.config;

import com.aliyu.filter.LoginFilter;
import com.aliyu.security.handler.*;
import com.aliyu.security.provider.MyAccessDecisionManager;
import com.aliyu.security.provider.MyFilterInvocationSecurityMetadataSource;
import com.aliyu.security.provider.UserVerifyAuthenticationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.session.web.http.HeaderHttpSessionIdResolver;
import org.springframework.session.web.http.HttpSessionIdResolver;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserVerifyAuthenticationProvider authenticationManager;//认证用户类

    @Autowired
    private CustomAuthenticationSuccessHandler successHandler;//登录认证成功处理类

    @Autowired
    private CustomAuthenticationFailureHandler failureHandler;//登录认证失败处理类

    @Autowired
    private MyFilterInvocationSecurityMetadataSource securityMetadataSource;//返回当前URL允许访问的角色列表
    @Autowired
    private MyAccessDecisionManager accessDecisionManager;//除登录登出外所有接口的权限校验

    /**
     * 密码加密
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(PasswordEncoder.class)
    public PasswordEncoder passwordEncoder() {    
        return new BCryptPasswordEncoder();
    }

    /**
     * 配置 HttpSessionIdResolver Bean
     * 登录之后将会在 Response Header x-auth-token 中 返回当前 sessionToken
     * 将token存储在前端 每次调用的时候 Request Header x-auth-token 带上 sessionToken
     */
    @Bean
    public HttpSessionIdResolver httpSessionIdResolver() {
   
     
        return HeaderHttpSessionIdResolver.xAuthToken();
    }
    /**
     * Swagger等静态资源不进行拦截
     */
    @Override
    public void configure(WebSecurity web) {
   
     
        web.ignoring().antMatchers(
                "/*.html",
                "/favicon.ico",
                "/**/*.html",
                "/**/*.css",
                "/**/*.js",
                "/error",
                "/webjars/**",
                "/resources/**",
                "/swagger-ui.html",
                "/swagger-resources/**",
                "/v2/api-docs");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
   
     
        http.authorizeRequests()
                //配置一些不需要登录就可以访问的接口
                .antMatchers("/demo/**", "/about/**").permitAll()
                //任何尚未匹配的URL只需要用户进行身份验证
                .anyRequest().authenticated()
                //登录后的接口权限校验
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O object) {
                        object.setAccessDecisionManager(accessDecisionManager);
                        object.setSecurityMetadataSource(securityMetadataSource);
                        return object;
                    }
                })
                .and()
                //配置登出处理
                .logout().logoutUrl("/logout")
                .logoutSuccessHandler(new CustomLogoutSuccessHandler())
                .clearAuthentication(true)
                .and()
                //用来解决匿名用户访问无权限资源时的异常
                .exceptionHandling().authenticationEntryPoint(new CustomAuthenticationEntryPoint())
                //用来解决登陆认证过的用户访问无权限资源时的异常
                .accessDeniedHandler(new CustomAccessDeniedHandler())
                .and()
                //配置登录过滤器
                .addFilter(new LoginFilter(authenticationManager, successHandler, failureHandler))
                .csrf().disable();
        //配置头部
        http.headers()
                .contentTypeOptions()
                .and()
                .xssProtection()
                .and()
                //禁用缓存
                .cacheControl()
                .and()
                .httpStrictTransportSecurity()
                .and()
                //禁用页面镶嵌frame劫持安全协议  // 防止iframe 造成跨域
                .frameOptions().disable();
    }
}