授权实现流程
定义授权过滤器:新建com.itheima.security.filter.AuthenticationFilter
package com.itheima.security.filter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.security.utils.JwtTokenUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
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;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 授权过滤器,相当于检票员
*/
public class AuthenticationFilter extends OncePerRequestFilter {//OncePerRequestFilter:对每个请求只会执行一次过滤
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String tokenStr = request.getHeader(JwtTokenUtil.TOKEN_HEADER);
if (StringUtils.isBlank(tokenStr)) {
filterChain.doFilter(request, response);
return;
}
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
Claims claims = JwtTokenUtil.checkJWT(tokenStr);
if(claims==null){
Map<String,String> info = new HashMap<>();
info.put("msg","票据无效");
info.put("code","0");
info.put("data","");
response.getWriter().write(new ObjectMapper().writeValueAsString(info));
return;
}
String username = JwtTokenUtil.getUsername(tokenStr);
//["P5","ROLE_ADMIN"]
String roles = JwtTokenUtil.getUserRole(tokenStr);
//去除[]
String strip = StringUtils.strip(roles, "[]");
//把以逗号分隔的字符串转换成GrantedAuthority对象
List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(strip);
//null为密码,认证通过后security会将密码置为null
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, null, authorities);
//把authenticationToken存入securityContext,以便后续过滤器使用
//该上下文以线程为维度,当前访问结束,该线程被回收,上下文凭证也会被回收
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
//后续的过滤器发现上下文中存在token信息,会认为用户已经通过认证
filterChain.doFilter(request, response);
}
}
配置授权过滤器
在com.itheima.security.config.SecurityConfig中配置
@Bean
public AuthenticationFilter authenticationFilter() {
return new AuthenticationFilter();
}
配置授权过滤器的执行顺序,SecurityConfig中配置
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin().and().logout().permitAll().and().csrf().disable().
authorizeRequests();
//将自定义过滤器加入过滤器链并在默认过滤器的前面执行
http.addFilterBefore(myUsernamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
//配置授权过滤器,为了保证资源安全,给与最高优先级,在自定义认证过滤器之前执行
http.addFilterBefore(authenticationFilter(), MyUsernamePasswordAuthenticationFilter.class);
}
测试一下,携带token
不携带token访问
跳到security的内置登录页面